问:
Constants in Kotlin -- what's a recommended way to create them?
How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.

```<code>companion object {
    //1
    val MY_CONST = "something"

    //2
    const val MY_CONST = "something"

    //3
    val myConst = "something"
}
</code>```

Or ...?

答:
Kotlin static and constant value & method declare

```<code>object MyConstant {

@JvmField   // for access in java code
val PI: Double = 3.14

@JvmStatic // JvmStatic annotation for access in java code
fun sumValue(v1: Int, v2: Int): Int {
    return v1 + v2
}
</code>```

}

Access value anywhere

```<code>val value = MyConstant.PI
val value = MyConstant.sumValue(10,5)
</code>```

Body:
How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.

companion object {
    //1
    val MY_CONST = "something"

    //2
    const val MY_CONST = "something"

    //3
    val myConst = "something"
}

Or ...?

Body:
Kotlin static and constant value & method declare

object MyConstant {

@JvmField   // for access in java code
val PI: Double = 3.14

@JvmStatic // JvmStatic annotation for access in java code
fun sumValue(v1: Int, v2: Int): Int {
    return v1 + v2
}

}

Access value anywhere

val value = MyConstant.PI
val value = MyConstant.sumValue(10,5)


来源: stackexchange

问:
import csv with different number of columns per row using Pandas
What is the best approach for importing a CSV that has a different number of columns for each row using Pandas or the CSV module into a Pandas DataFrame.

```<code>"H","BBB","D","Ajxxx Dxxxs"
"R","1","QH","DTR"," "," ","spxxt rixxls, raxxxd","1"
</code>```

Using this code:

```<code>import pandas as pd
data = pd.read_csv("smallsample.txt",header = None)
</code>```

the following error is generated

```<code>Error tokenizing data. C error: Expected 4 fields in line 2, saw 8
</code>```

答:
Error tokenizing data. C error: Expected 4 fields in line 2, saw 8

The error gives a clue to solve the problem "Expected 4 fields in line 2", saw 8 means length of the second row is 8 and first row is 4.

```<code>import pandas as pd
# inside range set the maximum value you can see in "Expected 4 fields in line 2, saw 8"
# here will be 8
data = pd.read_csv("smallsample.txt",header = None,names=range(8))
</code>```

Use range instead of manually setting names as it will be cumbersome when you have many columns.

You can use shantanu pathak's method to find longest row length in your data.

Additionally you can fill up the NaN values with 0, if you need to use even data length. Eg. for clustering (k-means)

```<code>new_data = data.fillna(0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the best approach for importing a CSV that has a different number of columns for each row using Pandas or the CSV module into a Pandas DataFrame.

"H","BBB","D","Ajxxx Dxxxs"
"R","1","QH","DTR"," "," ","spxxt rixxls, raxxxd","1"

Using this code:

import pandas as pd
data = pd.read_csv("smallsample.txt",header = None)

the following error is generated

Error tokenizing data. C error: Expected 4 fields in line 2, saw 8

Body:
Error tokenizing data. C error: Expected 4 fields in line 2, saw 8

The error gives a clue to solve the problem "Expected 4 fields in line 2", saw 8 means length of the second row is 8 and first row is 4.

import pandas as pd
# inside range set the maximum value you can see in "Expected 4 fields in line 2, saw 8"
# here will be 8
data = pd.read_csv("smallsample.txt",header = None,names=range(8))

Use range instead of manually setting names as it will be cumbersome when you have many columns.

You can use shantanu pathak's method to find longest row length in your data.

Additionally you can fill up the NaN values with 0, if you need to use even data length. Eg. for clustering (k-means)

new_data = data.fillna(0)

ContentLicense: CC BY-SA 4.0


问:
How to rename files based on an XML content tag?
I am new to batch script writing and need to some help. I have a folder which has several subfolders with files as listed in below structure:

FOLDER 0001

0001.a00

0001.a01

0001.a02

0001.a03

annotations.xml

FOLDER 0002

0001.a00

0001.a01

0001.a02

0001.a03

0002.b00

0002.b01

0002.b02

0002.b03

annotations.xml

FOLDER 0003

0001.a00

0001.a01

0001.a02

0001.a03

annotations.xml

Each folder has annotations.xml. This file has various XML tags.

I wish to extract the first two details between a1 tag with the attribute value New and rename (or append) the files *.[a-z][0-9][0-9] such as *.a00, *.a01, *.b01, *.b02, etc.

```<code><a1 L="New" T="xxx" etc..>ABC9876, 20200115-1630, 20200115-1730</a1>
</code>```

I want to rename the files to:

ABC9876.20200115-1630.a00

ABC9876.20200115-1630.a01

ABC9876.20200115-1630.a02

I have used the following script:

```<code>call xpath.bat "annotations.xml" "//a1" >> renamed.txt
</code>```

The created file renamed.txt contains:

```<code>ABC9876, 20200115-1630, 20200115-1730*
</code>```

I do not know how to move on with the rename, including looping all the folders and skipping those that were already done. I would be glad if I can get some ideas and assistance.

Further I tried the following:

```<code>@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1-2 delims=," %%a in (renamed.txt) do (
    echo ****************
    echo %%a echo %%b
    echo ****************
    set "new=%%a.%%b"
    set new=!new: =!
    echo !new!
    ren 0004.a03 !new!.mp3
)
pause
</code>```

I am able to rename only one file, but I do not know how to rename all the files while keeping their existing extensions. In the above example I tried to rename one into mp3.

答:
This task could be done depending on XML file content with a batch file containing a single command line with four FOR loops with batch file stored in directory containing the folders with the files to rename and the XML files annotations.xml.

```<code>@for /F "delims=" %%I in ('dir "%~dp0annotations.xml" /A-D /B /S 2^>nul') do for /F "tokens=2 delims=<>" %%J in ('%SystemRoot%\System32\findstr.exe /R /C:"<[^<>]*=\"New\" [^<>]*>.*,.*," "%%I"') do for /F "tokens=1,2 delims=, " %%K in ("%%J") do for /F "delims=" %%O in ('dir "%%~dpI" /A-D /B ^| %SystemRoot%\System32\findstr.exe /I /R "^[0123456789][0123456789][0123456789][0123456789]\.[a-z][0123456789][0123456789]$"') do ren "%%~dpI%%O" "%%K.%%L%%~xO"
</code>```

Better readable is the following multi-line variant:

```<code>@echo off
for /F "delims=" %%I in ('dir "%~dp0annotations.xml" /A-D /B /S 2^>nul') do (
    for /F "tokens=2 delims=<>" %%J in ('%SystemRoot%\System32\findstr.exe /R /C:"<[^<>]*=\"New\" [^<>]*>.*,.*," "%%I"') do (
        for /F "tokens=1,2 delims=, " %%K in ("%%J") do (
            for /F "delims=" %%O in ('dir "%%~dpI" /A-D /B ^| %SystemRoot%\System32\findstr.exe /I /R "^[0123456789][0123456789][0123456789][0123456789]\.[a-z][0123456789][0123456789]$"') do (
                echo ren "%%~dpI%%O" "%%K.%%L%%~xO"
            )
        )
    )
)
pause
</code>```

Note: There is the command echo left to command ren in above code to just output the file renaming command instead of executing the rename command. It is recommended to run this multi-line batch file first to verify if the XML files are really correct processed and so the new file name is built right.

The first FOR executes in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So executed is with Windows installed into C:\Windows:

```<code>C:\Windows\System32\cmd.exe /c dir "C:\batch file directory\annotations.xml" /A-D /B /S 2>nul
</code>```

DIR executed by separate command process in background searches

in batch file directory and all its subdirectories because of option /S

for just files because of option /A-D (attribute not directory)

with file name annotations.xml and

outputs in bare format just the found file names because of option /B with full path because of option /S to handle STDOUT (standard output) of background command process.

It is possible that DIR cannot find any file matching these criteria. In this case an error message would be output by DIR to handle STDERR (standard error) which is suppressed by redirecting it to device NUL.

Read the Microsoft article about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.

FOR captures the output to handle STDOUT of started background command process and processes this output line by line after started cmd.exe closed itself after finishing execution of DIR.

Empty lines are skipped by default by FOR, but there are no empty lines in this case.

FOR would split up each non-empty line by default into substrings using normal space and horizontal tab as string delimiters and would assign just the first space/tab separated string to the specified loop variable. This line splitting behavior is not wanted here because of the path to file annotations.xml could contain one or more spaces. For that reason the option delims= is used to define an empty list of string delimiters which disables line splitting behavior.

FOR would ignore also the lines on which first substring, being the entire line in this case, starts with default end of line character ;. But a full qualified file name as output by DIR cannot start with a semicolon. The full path of a file starts always either with a drive letter or a backslash in case of a UNC path. So no line is ignored by FOR in this case.

The first FOR iterates over all annotations.xml found in directory of the batch file and its subdirectories.

The second FOR runs again in background one more command process to execute FINDSTR with a case-sensitive regular expression on current annotations.xml to find the line containing the string ="New" somewhere within a tag with at least two comma separated strings in value of this XML element.

The found line output by FINDSTR is captured by FOR and processed with splitting the line up into substrings using the angle brackets as string delimiters because of option delims=<>. Just the second angle bracket delimited string being the value of the XML element found by FINDSTR is assigned to specified loop variable J because of tokens=2.

The third FOR processes the value string of the XML element by splitting it up using comma and normal space as string delimiters as specified with delims=, . The first substring is assigned to specified loop variable K and because of tokens=1,2 the second comma/space separated substring is assigned to next loop variable according to ASCII table which is the loop variable L.

The fourth FOR runs DIR in a separate command process to find all files in directory of current annotations.xml. The output is additionally filtered with FINDSTR to output finally to STDOUT of background command process just those file names without file path of which name is exactly four digits and the file extension starts case-insensitive with an ASCII letter and has exactly two digits next. This filtering makes it possible to run the batch file multiple times on same directory tree with avoiding to rename files which were renamed already by a previous batch file execution.

The fourth FOR processes the file names without file path one by one and runs the rename command with the wanted new name respectively outputs the rename command line.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /? ... explains %~dp0 ... drive and path of argument 0 which is the currently processed batch file, i.e. full path of batch file always ending with a backslash.

dir /?

echo /?

findstr /?

for /?

pause /?

ren /?

Body:
I am new to batch script writing and need to some help. I have a folder which has several subfolders with files as listed in below structure:

FOLDER 0001

0001.a00

0001.a01

0001.a02

0001.a03

annotations.xml

FOLDER 0002

0001.a00

0001.a01

0001.a02

0001.a03

0002.b00

0002.b01

0002.b02

0002.b03

annotations.xml

FOLDER 0003

0001.a00

0001.a01

0001.a02

0001.a03

annotations.xml

Each folder has annotations.xml. This file has various XML tags.

I wish to extract the first two details between a1 tag with the attribute value New and rename (or append) the files *.[a-z][0-9][0-9] such as *.a00, *.a01, *.b01, *.b02, etc.

<a1 L="New" T="xxx" etc..>ABC9876, 20200115-1630, 20200115-1730</a1>

I want to rename the files to:

ABC9876.20200115-1630.a00

ABC9876.20200115-1630.a01

ABC9876.20200115-1630.a02

I have used the following script:

call xpath.bat "annotations.xml" "//a1" >> renamed.txt

The created file renamed.txt contains:

ABC9876, 20200115-1630, 20200115-1730*

I do not know how to move on with the rename, including looping all the folders and skipping those that were already done. I would be glad if I can get some ideas and assistance.

Further I tried the following:

@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1-2 delims=," %%a in (renamed.txt) do (
    echo ****************
    echo %%a echo %%b
    echo ****************
    set "new=%%a.%%b"
    set new=!new: =!
    echo !new!
    ren 0004.a03 !new!.mp3
)
pause

I am able to rename only one file, but I do not know how to rename all the files while keeping their existing extensions. In the above example I tried to rename one into mp3.

Body:
This task could be done depending on XML file content with a batch file containing a single command line with four FOR loops with batch file stored in directory containing the folders with the files to rename and the XML files annotations.xml.

@for /F "delims=" %%I in ('dir "%~dp0annotations.xml" /A-D /B /S 2^>nul') do for /F "tokens=2 delims=<>" %%J in ('%SystemRoot%\System32\findstr.exe /R /C:"<[^<>]*=\"New\" [^<>]*>.*,.*," "%%I"') do for /F "tokens=1,2 delims=, " %%K in ("%%J") do for /F "delims=" %%O in ('dir "%%~dpI" /A-D /B ^| %SystemRoot%\System32\findstr.exe /I /R "^[0123456789][0123456789][0123456789][0123456789]\.[a-z][0123456789][0123456789]$"') do ren "%%~dpI%%O" "%%K.%%L%%~xO"

Better readable is the following multi-line variant:

@echo off
for /F "delims=" %%I in ('dir "%~dp0annotations.xml" /A-D /B /S 2^>nul') do (
    for /F "tokens=2 delims=<>" %%J in ('%SystemRoot%\System32\findstr.exe /R /C:"<[^<>]*=\"New\" [^<>]*>.*,.*," "%%I"') do (
        for /F "tokens=1,2 delims=, " %%K in ("%%J") do (
            for /F "delims=" %%O in ('dir "%%~dpI" /A-D /B ^| %SystemRoot%\System32\findstr.exe /I /R "^[0123456789][0123456789][0123456789][0123456789]\.[a-z][0123456789][0123456789]$"') do (
                echo ren "%%~dpI%%O" "%%K.%%L%%~xO"
            )
        )
    )
)
pause

Note: There is the command echo left to command ren in above code to just output the file renaming command instead of executing the rename command. It is recommended to run this multi-line batch file first to verify if the XML files are really correct processed and so the new file name is built right.

The first FOR executes in background one more command process with %ComSpec% /c and the command line between ' appended as additional arguments. So executed is with Windows installed into C:\Windows:

C:\Windows\System32\cmd.exe /c dir "C:\batch file directory\annotations.xml" /A-D /B /S 2>nul

DIR executed by separate command process in background searches

in batch file directory and all its subdirectories because of option /S

for just files because of option /A-D (attribute not directory)

with file name annotations.xml and

outputs in bare format just the found file names because of option /B with full path because of option /S to handle STDOUT (standard output) of background command process.

It is possible that DIR cannot find any file matching these criteria. In this case an error message would be output by DIR to handle STDERR (standard error) which is suppressed by redirecting it to device NUL.

Read the Microsoft article about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.

FOR captures the output to handle STDOUT of started background command process and processes this output line by line after started cmd.exe closed itself after finishing execution of DIR.

Empty lines are skipped by default by FOR, but there are no empty lines in this case.

FOR would split up each non-empty line by default into substrings using normal space and horizontal tab as string delimiters and would assign just the first space/tab separated string to the specified loop variable. This line splitting behavior is not wanted here because of the path to file annotations.xml could contain one or more spaces. For that reason the option delims= is used to define an empty list of string delimiters which disables line splitting behavior.

FOR would ignore also the lines on which first substring, being the entire line in this case, starts with default end of line character ;. But a full qualified file name as output by DIR cannot start with a semicolon. The full path of a file starts always either with a drive letter or a backslash in case of a UNC path. So no line is ignored by FOR in this case.

The first FOR iterates over all annotations.xml found in directory of the batch file and its subdirectories.

The second FOR runs again in background one more command process to execute FINDSTR with a case-sensitive regular expression on current annotations.xml to find the line containing the string ="New" somewhere within a tag with at least two comma separated strings in value of this XML element.

The found line output by FINDSTR is captured by FOR and processed with splitting the line up into substrings using the angle brackets as string delimiters because of option delims=<>. Just the second angle bracket delimited string being the value of the XML element found by FINDSTR is assigned to specified loop variable J because of tokens=2.

The third FOR processes the value string of the XML element by splitting it up using comma and normal space as string delimiters as specified with delims=, . The first substring is assigned to specified loop variable K and because of tokens=1,2 the second comma/space separated substring is assigned to next loop variable according to ASCII table which is the loop variable L.

The fourth FOR runs DIR in a separate command process to find all files in directory of current annotations.xml. The output is additionally filtered with FINDSTR to output finally to STDOUT of background command process just those file names without file path of which name is exactly four digits and the file extension starts case-insensitive with an ASCII letter and has exactly two digits next. This filtering makes it possible to run the batch file multiple times on same directory tree with avoiding to rename files which were renamed already by a previous batch file execution.

The fourth FOR processes the file names without file path one by one and runs the rename command with the wanted new name respectively outputs the rename command line.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /? ... explains %~dp0 ... drive and path of argument 0 which is the currently processed batch file, i.e. full path of batch file always ending with a backslash.

dir /?

echo /?

findstr /?

for /?

pause /?

ren /?


问:
Generic repository pattern ASP NET CORE Web Api: using include with async
I have following problem.
My exemplary models looks as follows:

```<code>public class FacilityType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeleted { get; set; }
}

public class Training
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual FacilityType FacilityType { get; set; }
    public int FacilityTypeID { get; set; }
    public bool IsDeleted { get; set; }

}
</code>```

When I create new object of training type, I want it to be returned by my API with not only FacilityTypeID but also FacilityType as object, serialized in JSON.

Structure of my project is as follows.
I have generic repository pattern which I use in my controllers

```<code>public interface IGenericRepository<TEntity> where TEntity: class, IEntity
{
    IEnumerable<TEntity> GetAllEntities();
    Task<TEntity> GetEntityById(int id );
    Task CreateEntity(TEntity entity);
    Task UpdateEntity(int id, TEntity entity);
    Task DeleteEntity(int id);
}
public async Task<TEntity> GetEntityById(int id )
    {

        return await context.Set<TEntity>().Where(ent => ent.IsDeleted != true && ent.Id == id).FirstOrDefaultAsync();
    }
</code>```

And what I try to accomplish is find a way how to include related facility type to training which I return in method below.

```<code>    [HttpGet("{id}")]
    public async Task<ActionResult<Training>> GetTraining(int id)
    {
         return await repository.GetEntityById(id);

    }
</code>```

Thank you in advance for your contributions :)

P.S:

Is using predicates in methods parameter a good idea? Like this:
And btw. how to call such method using for example include linq expression?

```<code>   public async Task<ICollection<TEntity>> GetEntityById(Expression<Func<TEntity, bool>> predicate)
    {

        //return await context.Set<TEntity>().Where(ent => ent.IsDeleted != true && ent.Id == id).FirstOrDefaultAsync();
        return await context.Set<TEntity>().Where(predicate).ToListAsync();
    }
</code>```

答:
Option 1

If you have the interface IEntity already implementing the property Id:

public async Task<T> Get<T>(int id, Expression<Func<T, object>> include) where T : class, IEntity
{
    using (var context = new AppContext())
    {
        return await context.Set<T>()
                           .AsNoTracking()
                           .Where(x => x.Id == id)
                           .Include(include)
                           .FirstOrDefaultAsync();
    }
}
```

<p>To call this method:</p>

<pre class="lang-cs prettyprint-override"><code>var entity = await _context.Get<Training>(1, x => x.FacilityType);
</code>```

Option 2

Without the interface IEntity (more generic way):

public async Task<T> Get<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> include) where T : class
{
    using (var context = new AppContext())
    {
        return await context.Set<T>()
                           .AsNoTracking()
                           .Where(predicate)
                           .Include(include)
                           .FirstOrDefaultAsync();
    }
}
```

<p>To call this method:</p>

<pre class="lang-cs prettyprint-override"><code>var entity = await _context.Get<Training>(x => x.Id == 1, x => x.FacilityType);
</code>```

Body:
I have following problem.
My exemplary models looks as follows:

public class FacilityType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeleted { get; set; }
}

public class Training
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual FacilityType FacilityType { get; set; }
    public int FacilityTypeID { get; set; }
    public bool IsDeleted { get; set; }

}

When I create new object of training type, I want it to be returned by my API with not only FacilityTypeID but also FacilityType as object, serialized in JSON.

Structure of my project is as follows.
I have generic repository pattern which I use in my controllers

public interface IGenericRepository<TEntity> where TEntity: class, IEntity
{
    IEnumerable<TEntity> GetAllEntities();
    Task<TEntity> GetEntityById(int id );
    Task CreateEntity(TEntity entity);
    Task UpdateEntity(int id, TEntity entity);
    Task DeleteEntity(int id);
}
public async Task<TEntity> GetEntityById(int id )
    {

        return await context.Set<TEntity>().Where(ent => ent.IsDeleted != true && ent.Id == id).FirstOrDefaultAsync();
    }

And what I try to accomplish is find a way how to include related facility type to training which I return in method below.

    [HttpGet("{id}")]
    public async Task<ActionResult<Training>> GetTraining(int id)
    {
         return await repository.GetEntityById(id);

    }

Thank you in advance for your contributions :)

P.S:

Is using predicates in methods parameter a good idea? Like this:
And btw. how to call such method using for example include linq expression?

   public async Task<ICollection<TEntity>> GetEntityById(Expression<Func<TEntity, bool>> predicate)
    {

        //return await context.Set<TEntity>().Where(ent => ent.IsDeleted != true && ent.Id == id).FirstOrDefaultAsync();
        return await context.Set<TEntity>().Where(predicate).ToListAsync();
    }

Body:
Option 1

If you have the interface IEntity already implementing the property Id:

public async Task<T> Get<T>(int id, Expression<Func<T, object>> include) where T : class, IEntity
{
    using (var context = new AppContext())
    {
        return await context.Set<T>()
                           .AsNoTracking()
                           .Where(x => x.Id == id)
                           .Include(include)
                           .FirstOrDefaultAsync();
    }
}

To call this method:

var entity = await _context.Get<Training>(1, x => x.FacilityType);

Option 2

Without the interface IEntity (more generic way):

public async Task<T> Get<T>(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> include) where T : class
{
    using (var context = new AppContext())
    {
        return await context.Set<T>()
                           .AsNoTracking()
                           .Where(predicate)
                           .Include(include)
                           .FirstOrDefaultAsync();
    }
}

To call this method:

var entity = await _context.Get<Training>(x => x.Id == 1, x => x.FacilityType);


问:
How can I throw TypeError with message inside if statement in Python?

What I want to do

I would like to fix my current code to pass the coding challenge, Codewars Prefill an Array.

I hope to learn how to throw TypeError with message with if statement in this case.

Create the function prefill that returns an array of n elements thatall have the same value v. See if you can do this without using a loop.

You have to validate input: v can be anything (primitive orotherwise) if v is ommited, fill the array with undefined if n is 0, return an empty array if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError

When throwing a TypeError, the message should be n is invalid, where
  you replace n for the actual value passed to the function.

```<code>Code Examples
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"
</code>```

Problem

I have passed 4 sample tests among 5 sample tests, but I cannot pass the below one.

```<code>    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"
</code>```

Error Message

```<code>Traceback (most recent call last): File "main.py", line 8,
in <module> prefill('xyz', 1) File "/home/codewarrior/solution.py",
line 3, in prefill if int(n): ValueError: invalid literal for int() with base 10: 'xyz'
</code>```

Current code

def prefill(n,v):

    if int(n):
        result = [0] * int(n)
        for i in range(len(result)):
            result[i] = v
        return result

    else:
        return TypeError, str(n) + "is invalid"
```

Developing Environment

Python 3.4.3

答:
Use the raise keyword to raise an exception, rather than return it. raise is used to generate a new exception:

```<code>>>> raise TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError
</code>```

In this example I raised the TypeError by using the exception class directly. You can also create instances of the error like this:

```<code>>>> t=TypeError()
>>> raise t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError
</code>```

Doing it that way allows various properties to be set on the object before using raise. The problem posted includes this requirement:

When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.

That is an example of a situation where it is necessary to create an instance of the error and set a message property on it before using raise. That can still be done in one line:

```<code>>>> raise TypeError("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo
</code>```

To catch exceptions, use a try-except block, rather than an if block:

```<code>x = 'hello, world!'
try:
    y = x / 2
except TypeError as e:
    e.args = (*e.args, str(x) + " is not valid")
    raise
</code>```

This will raise an error:

```<code>TypeError: ("unsupported operand type(s) for /: 'str' and 'int'", 'hello, world! is not valid')
</code>```

note that you can check the datatype of a variable using type():

```<code>>>> x = 5
>>> type(x)
<class 'int'>
>>> if type(x) == int:
...   print("it's an int")
...
it's an int
</code>```

Also, the code sample could be simplified to:

```<code>    return [v for _ in range(n)]

</code>```

Body:
What I want to do

I would like to fix my current code to pass the coding challenge, Codewars Prefill an Array.

I hope to learn how to throw TypeError with message with if statement in this case.

Create the function prefill that returns an array of n elements thatall have the same value v. See if you can do this without using a loop.

You have to validate input: v can be anything (primitive orotherwise) if v is ommited, fill the array with undefined if n is 0, return an empty array if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError

When throwing a TypeError, the message should be n is invalid, where
  you replace n for the actual value passed to the function.

Code Examples
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"

Problem

I have passed 4 sample tests among 5 sample tests, but I cannot pass the below one.

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"

Error Message

Traceback (most recent call last): File "main.py", line 8,
in <module> prefill('xyz', 1) File "/home/codewarrior/solution.py",
line 3, in prefill if int(n): ValueError: invalid literal for int() with base 10: 'xyz'

Current code

def prefill(n,v):

    if int(n):
        result = [0] * int(n)
        for i in range(len(result)):
            result[i] = v
        return result

    else:
        return TypeError, str(n) + "is invalid"

Developing Environment

Python 3.4.3

Body:
Use the raise keyword to raise an exception, rather than return it. raise is used to generate a new exception:

>>> raise TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

In this example I raised the TypeError by using the exception class directly. You can also create instances of the error like this:

>>> t=TypeError()
>>> raise t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

Doing it that way allows various properties to be set on the object before using raise. The problem posted includes this requirement:

When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.

That is an example of a situation where it is necessary to create an instance of the error and set a message property on it before using raise. That can still be done in one line:

>>> raise TypeError("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo

To catch exceptions, use a try-except block, rather than an if block:

x = 'hello, world!'
try:
    y = x / 2
except TypeError as e:
    e.args = (*e.args, str(x) + " is not valid")
    raise

This will raise an error:

TypeError: ("unsupported operand type(s) for /: 'str' and 'int'", 'hello, world! is not valid')

note that you can check the datatype of a variable using type():

>>> x = 5
>>> type(x)
<class 'int'>
>>> if type(x) == int:
...   print("it's an int")
...
it's an int

Also, the code sample could be simplified to:

    return [v for _ in range(n)]


问:
Jenkins falls into deadlock while executing a pipeline in parallel
I have a Jenkins pipeline that has 6 stages.

In 4 of the 6 stages the pipeline triggers Jenkins jobs using build job.

Both the pipeline and the job are set to allow concurrent parallel executions.

The node on which the pipeline and the jobs run is a single node having number of executer set to 10.

Everything works fine when I run 10 parallel concurrent pipeline.

But if I run more than 10 parallel pipelines then all of them seem to go in a deadlock, none of them completes no matter how long you wait and send they are waiting on each other to complete.

If I kill the 11th execution then all the 10 start completing successfully.

My requirement is that if someone executes more concurrent builds of a pipeline than the number of executors it has for the node that it runs on; then in that case 10 should complete parallel execution and 11 onwards should wait until then and should be executed in the second batch of 10 executions rather than all going to a hung state.

Please help me understand if this is a bug with Jenkins latest version and what is the workaround to avoid all pipeline builds from falling in hung state?

答:
The issue can be that the master or the node runs out of CPU and/or memory.
You can also look at Jenkins master/slave node logs for exceptions. </p>


问:
All possible String Patterns
When I have a string containing multiple "P" or "S", e.g. "PPP", "PSP", "PSSSPPS", "SPSPSS",
and I have to find all patterns where P is replaced to "Q" or "R" and S is replaced to "T" or "U".

e.g. input "P" -> output ["Q", "R"]; input "PP" ->output ["QQ", "QR", "RR", "RQ"]; input "PS" => output ["QT", "QU", "RT", "RU"];

How can I implement this procedure? the point is that the numbers of P and S are not fixed..

I would like to use Java however please give me a sample of algorithm..

so far like this,

```<code>String[] getAllPatterns(String toBeChanged){
   List<Integer> pPlace = new ArrayList<>();
   List<Integer> sPlace = new ArrayList<>();
   for (int i = 0; i < toBeChanged.length(); i++) {
        char c = toBeChanged.charAt(i);
        if (c == 'P') pPlace.add(i);
        if (c == 'S') sPlace.add(i);
    }
    int numP = pPlace.size();
    int numS = sPlace.size();
    int numCase = (int) Math.round(Math.pow(2, numP) * Math.pow(2, numS)); // 2 is P-> Q or R; S -> T or U
    String[] allcases = new String[numCase];
       .................
  return allcases;
}

getAllPatterns("PS"); //-> {"QT","QU","RT","RU"}
getAllPatterns("SP"); //-> {"TQ","UQ","TR","UR"}
</code>```

In this case "P" can be only "Q" or "R", but in the future,
possible characters are also variables..

"P" can be "P1", "P2", "P3", ...or "Pn"

答:
Since each input character is replaced by one of 2 characters, the replacement choice fits exactly in a bit.

So to go through all combinations of an N-letter input, you can iterate through all values of an N-bit number.

Building all the combinations in a List will require a lot of memory, so using an int for iterating values, and limiting length of input to 30, shouldn't be an issue.

In this case, the replacement characters are actually the following two ASCII characters, so we can calculate the replacement character as replacementChar = inputChar + 1 + bit.

That means the code could look something like this:

```<code>static List<String> generatePatterns(String input) {
    if (! input.matches("[PS]{0,30}"))
        throw new IllegalArgumentException("Invalid input: " + input);
    final int end = 1 << input.length();
    char[] chars = new char[input.length()];
    List<String> result = new ArrayList<>(end);
    for (int combo = 0; combo < end; combo++) {
        for (int i = input.length() - 1, bits = combo; i >= 0; i--, bits >>>= 1)
            chars[i] = (char) (input.charAt(i) + 1 + (bits & 1));
        result.add(new String(chars));
    }
    return result;
}
</code>```

Tests

```<code>for (String input : new String[] {"", "P", "PP", "PS", "PPP", "PSP", "PSSSPPS", "SPSPSS"}) {
    List<String> result = generatePatterns(input);
    System.out.println(input + " -> " + result);
}
</code>```

Output

 -> []
P -> [Q, R]
PP -> [QQ, QR, RQ, RR]
PS -> [QT, QU, RT, RU]
PPP -> [QQQ, QQR, QRQ, QRR, RQQ, RQR, RRQ, RRR]
PSP -> [QTQ, QTR, QUQ, QUR, RTQ, RTR, RUQ, RUR]
PSSSPPS -> [QTTTQQT, QTTTQQU, QTTTQRT, QTTTQRU, QTTTRQT, QTTTRQU, QTTTRRT, QTTTRRU, QTTUQQT, QTTUQQU, QTTUQRT, QTTUQRU, QTTURQT, QTTURQU, QTTURRT, QTTURRU, QTUTQQT, QTUTQQU, QTUTQRT, QTUTQRU, QTUTRQT, QTUTRQU, QTUTRRT, QTUTRRU, QTUUQQT, QTUUQQU, QTUUQRT, QTUUQRU, QTUURQT, QTUURQU, QTUURRT, QTUURRU, QUTTQQT, QUTTQQU, QUTTQRT, QUTTQRU, QUTTRQT, QUTTRQU, QUTTRRT, QUTTRRU, QUTUQQT, QUTUQQU, QUTUQRT, QUTUQRU, QUTURQT, QUTURQU, QUTURRT, QUTURRU, QUUTQQT, QUUTQQU, QUUTQRT, QUUTQRU, QUUTRQT, QUUTRQU, QUUTRRT, QUUTRRU, QUUUQQT, QUUUQQU, QUUUQRT, QUUUQRU, QUUURQT, QUUURQU, QUUURRT, QUUURRU, RTTTQQT, RTTTQQU, RTTTQRT, RTTTQRU, RTTTRQT, RTTTRQU, RTTTRRT, RTTTRRU, RTTUQQT, RTTUQQU, RTTUQRT, RTTUQRU, RTTURQT, RTTURQU, RTTURRT, RTTURRU, RTUTQQT, RTUTQQU, RTUTQRT, RTUTQRU, RTUTRQT, RTUTRQU, RTUTRRT, RTUTRRU, RTUUQQT, RTUUQQU, RTUUQRT, RTUUQRU, RTUURQT, RTUURQU, RTUURRT, RTUURRU, RUTTQQT, RUTTQQU, RUTTQRT, RUTTQRU, RUTTRQT, RUTTRQU, RUTTRRT, RUTTRRU, RUTUQQT, RUTUQQU, RUTUQRT, RUTUQRU, RUTURQT, RUTURQU, RUTURRT, RUTURRU, RUUTQQT, RUUTQQU, RUUTQRT, RUUTQRU, RUUTRQT, RUUTRQU, RUUTRRT, RUUTRRU, RUUUQQT, RUUUQQU, RUUUQRT, RUUUQRU, RUUURQT, RUUURQU, RUUURRT, RUUURRU]
SPSPSS -> [TQTQTT, TQTQTU, TQTQUT, TQTQUU, TQTRTT, TQTRTU, TQTRUT, TQTRUU, TQUQTT, TQUQTU, TQUQUT, TQUQUU, TQURTT, TQURTU, TQURUT, TQURUU, TRTQTT, TRTQTU, TRTQUT, TRTQUU, TRTRTT, TRTRTU, TRTRUT, TRTRUU, TRUQTT, TRUQTU, TRUQUT, TRUQUU, TRURTT, TRURTU, TRURUT, TRURUU, UQTQTT, UQTQTU, UQTQUT, UQTQUU, UQTRTT, UQTRTU, UQTRUT, UQTRUU, UQUQTT, UQUQTU, UQUQUT, UQUQUU, UQURTT, UQURTU, UQURUT, UQURUU, URTQTT, URTQTU, URTQUT, URTQUU, URTRTT, URTRTU, URTRUT, URTRUU, URUQTT, URUQTU, URUQUT, URUQUU, URURTT, URURTU, URURUT, URURUU]
```

Title: All possible String Patterns

Body:
When I have a string containing multiple "P" or "S", e.g. "PPP", "PSP", "PSSSPPS", "SPSPSS",
and I have to find all patterns where P is replaced to "Q" or "R" and S is replaced to "T" or "U".

e.g. input "P" -> output ["Q", "R"]; input "PP" ->output ["QQ", "QR", "RR", "RQ"]; input "PS" => output ["QT", "QU", "RT", "RU"];

How can I implement this procedure? the point is that the numbers of P and S are not fixed..

I would like to use Java however please give me a sample of algorithm..

so far like this,

String[] getAllPatterns(String toBeChanged){
   List<Integer> pPlace = new ArrayList<>();
   List<Integer> sPlace = new ArrayList<>();
   for (int i = 0; i < toBeChanged.length(); i++) {
        char c = toBeChanged.charAt(i);
        if (c == 'P') pPlace.add(i);
        if (c == 'S') sPlace.add(i);
    }
    int numP = pPlace.size();
    int numS = sPlace.size();
    int numCase = (int) Math.round(Math.pow(2, numP) * Math.pow(2, numS)); // 2 is P-> Q or R; S -> T or U
    String[] allcases = new String[numCase];
       .................
  return allcases;
}

getAllPatterns("PS"); //-> {"QT","QU","RT","RU"}
getAllPatterns("SP"); //-> {"TQ","UQ","TR","UR"}

In this case "P" can be only "Q" or "R", but in the future,
possible characters are also variables..

"P" can be "P1", "P2", "P3", ...or "Pn"

Body:
Since each input character is replaced by one of 2 characters, the replacement choice fits exactly in a bit.

So to go through all combinations of an N-letter input, you can iterate through all values of an N-bit number.

Building all the combinations in a List will require a lot of memory, so using an int for iterating values, and limiting length of input to 30, shouldn't be an issue.

In this case, the replacement characters are actually the following two ASCII characters, so we can calculate the replacement character as replacementChar = inputChar + 1 + bit.

That means the code could look something like this:

static List<String> generatePatterns(String input) {
    if (! input.matches("[PS]{0,30}"))
        throw new IllegalArgumentException("Invalid input: " + input);
    final int end = 1 << input.length();
    char[] chars = new char[input.length()];
    List<String> result = new ArrayList<>(end);
    for (int combo = 0; combo < end; combo++) {
        for (int i = input.length() - 1, bits = combo; i >= 0; i--, bits >>>= 1)
            chars[i] = (char) (input.charAt(i) + 1 + (bits & 1));
        result.add(new String(chars));
    }
    return result;
}

Tests

for (String input : new String[] {"", "P", "PP", "PS", "PPP", "PSP", "PSSSPPS", "SPSPSS"}) {
    List<String> result = generatePatterns(input);
    System.out.println(input + " -> " + result);
}

Output

 -> []
P -> [Q, R]
PP -> [QQ, QR, RQ, RR]
PS -> [QT, QU, RT, RU]
PPP -> [QQQ, QQR, QRQ, QRR, RQQ, RQR, RRQ, RRR]
PSP -> [QTQ, QTR, QUQ, QUR, RTQ, RTR, RUQ, RUR]
PSSSPPS -> [QTTTQQT, QTTTQQU, QTTTQRT, QTTTQRU, QTTTRQT, QTTTRQU, QTTTRRT, QTTTRRU, QTTUQQT, QTTUQQU, QTTUQRT, QTTUQRU, QTTURQT, QTTURQU, QTTURRT, QTTURRU, QTUTQQT, QTUTQQU, QTUTQRT, QTUTQRU, QTUTRQT, QTUTRQU, QTUTRRT, QTUTRRU, QTUUQQT, QTUUQQU, QTUUQRT, QTUUQRU, QTUURQT, QTUURQU, QTUURRT, QTUURRU, QUTTQQT, QUTTQQU, QUTTQRT, QUTTQRU, QUTTRQT, QUTTRQU, QUTTRRT, QUTTRRU, QUTUQQT, QUTUQQU, QUTUQRT, QUTUQRU, QUTURQT, QUTURQU, QUTURRT, QUTURRU, QUUTQQT, QUUTQQU, QUUTQRT, QUUTQRU, QUUTRQT, QUUTRQU, QUUTRRT, QUUTRRU, QUUUQQT, QUUUQQU, QUUUQRT, QUUUQRU, QUUURQT, QUUURQU, QUUURRT, QUUURRU, RTTTQQT, RTTTQQU, RTTTQRT, RTTTQRU, RTTTRQT, RTTTRQU, RTTTRRT, RTTTRRU, RTTUQQT, RTTUQQU, RTTUQRT, RTTUQRU, RTTURQT, RTTURQU, RTTURRT, RTTURRU, RTUTQQT, RTUTQQU, RTUTQRT, RTUTQRU, RTUTRQT, RTUTRQU, RTUTRRT, RTUTRRU, RTUUQQT, RTUUQQU, RTUUQRT, RTUUQRU, RTUURQT, RTUURQU, RTUURRT, RTUURRU, RUTTQQT, RUTTQQU, RUTTQRT, RUTTQRU, RUTTRQT, RUTTRQU, RUTTRRT, RUTTRRU, RUTUQQT, RUTUQQU, RUTUQRT, RUTUQRU, RUTURQT, RUTURQU, RUTURRT, RUTURRU, RUUTQQT, RUUTQQU, RUUTQRT, RUUTQRU, RUUTRQT, RUUTRQU, RUUTRRT, RUUTRRU, RUUUQQT, RUUUQQU, RUUUQRT, RUUUQRU, RUUURQT, RUUURQU, RUUURRT, RUUURRU]
SPSPSS -> [TQTQTT, TQTQTU, TQTQUT, TQTQUU, TQTRTT, TQTRTU, TQTRUT, TQTRUU, TQUQTT, TQUQTU, TQUQUT, TQUQUU, TQURTT, TQURTU, TQURUT, TQURUU, TRTQTT, TRTQTU, TRTQUT, TRTQUU, TRTRTT, TRTRTU, TRTRUT, TRTRUU, TRUQTT, TRUQTU, TRUQUT, TRUQUU, TRURTT, TRURTU, TRURUT, TRURUU, UQTQTT, UQTQTU, UQTQUT, UQTQUU, UQTRTT, UQTRTU, UQTRUT, UQTRUU, UQUQTT, UQUQTU, UQUQUT, UQUQUU, UQURTT, UQURTU, UQURUT, UQURUU, URTQTT, URTQTU, URTQUT, URTQUU, URTRTT, URTRTU, URTRUT, URTRUU, URUQTT, URUQTU, URUQUT, URUQUU, URURTT, URURTU, URURUT, URURUU]


问:
templates, function uses wrong constructor to copy my object
I created a class template that initializes a simple array
using the parameter pack expansion and the class has a copy constructor for my function that takes an object of that class. Initialization works, but when passing an object to my function, the initialization constructor is called and not the copy constructor.

How can I make my function use the correct constructor to be
able to pass an object by value?

Working with c++17.

My class looks as follows:

```<code>template<typename I, std::size_t val>
class myClass{

    public:
        std::array<I, val> data;

    template<typename ...T>
    constexpr myClass(T&& ... elem) : data{elem...}{};

    /*copy c'tr*/
    template<typename T, std::size_t value>
    constexpr myClass(myClass<T, value> mObj){
        data = mObj.data;
    }
};

struct myStruct{
    myClass<int, 5> aC{1,2,3,4,5};
};

template<typename I, std::size_t val>
constexpr auto myfunction(myClass<T, val> obj){
    int a = obj.data[0];
    return a;
}
</code>```

This is my main:

```<code>int main() {
    myStruct myStructObj;
    auto myvalue = myfunction(myStructObj.aC);
    return 0;
}
</code>```

At the end, my error message:

```<code>tensor.h: In instantiation of ‘constexpr myClass<I, val>::myClass(T&& ...) [with T = {myClass<int, 5>&}; I = int; long unsigned int val = 5]’:
main.cpp:72:30:   required from here
tensor.h:188:51: error: cannot convert ‘myClass<int, 5>’ to ‘int’ in initialization
  188 |     constexpr myClass(T&& ... elem) : data{elem...}{};
      |

                                            ^
</code>```

答:
/*copy c'tr*/

That is not a correct assertion. This is a constructor template. A copy c'tor is always a normal member of an instantiation, never a template member function. Also, this c'tor is taking its argument by value. This is a no-starter, since function arguments that are passed by value are copy-initialized, which requires... a copy/move c'tor. The correct signature for the copy c'tor would be this

```<code>constexpr myClass(myClass const& mObj){
    data = mObj.data;
}
</code>```

Take the argument by reference (to const). A copy c'tor may exist next to your c'tor template. So you may have conversions from other instantiations and copying, both well defined.

Or, since you are after the default implementation anyway

```<code>constexpr myClass(myClass const& mObj) = default;
</code>```

Body:
I created a class template that initializes a simple array
using the parameter pack expansion and the class has a copy constructor for my function that takes an object of that class. Initialization works, but when passing an object to my function, the initialization constructor is called and not the copy constructor.

How can I make my function use the correct constructor to be
able to pass an object by value?

Working with c++17.

My class looks as follows:

template<typename I, std::size_t val>
class myClass{

    public:
        std::array data;

    template<typename ...T>
    constexpr myClass(T&& ... elem) : data{elem...}{};

    /*copy c'tr*/
    template<typename T, std::size_t value>
    constexpr myClass(myClass<T, value> mObj){
        data = mObj.data;
    }
};

struct myStruct{
    myClass<int, 5> aC{1,2,3,4,5};
};

template<typename I, std::size_t val>
constexpr auto myfunction(myClass<T, val> obj){
    int a = obj.data[0];
    return a;
}

This is my main:

int main() {
    myStruct myStructObj;
    auto myvalue = myfunction(myStructObj.aC);
    return 0;
}

At the end, my error message:

tensor.h: In instantiation of ‘constexpr myClass::myClass(T&& ...) [with T = {myClass<int, 5>&}; I = int; long unsigned int val = 5]’:
main.cpp:72:30:   required from here
tensor.h:188:51: error: cannot convert ‘myClass<int, 5>’ to ‘int’ in initialization
  188 |     constexpr myClass(T&& ... elem) : data{elem...}{};
      |

                                            ^

Body:
/*copy c'tr*/

That is not a correct assertion. This is a constructor template. A copy c'tor is always a normal member of an instantiation, never a template member function. Also, this c'tor is taking its argument by value. This is a no-starter, since function arguments that are passed by value are copy-initialized, which requires... a copy/move c'tor. The correct signature for the copy c'tor would be this

constexpr myClass(myClass const& mObj){
    data = mObj.data;
}

Take the argument by reference (to const). A copy c'tor may exist next to your c'tor template. So you may have conversions from other instantiations and copying, both well defined.

Or, since you are after the default implementation anyway

constexpr myClass(myClass const& mObj) = default;


问:
What am I doing wrong when trying to set a cookie using Express
I'm currently trying to send a cookie back to my react app after logging in,
In my server I have a test response:

```<code>res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end();
</code>```

and in the app I have

```<code>Axios.post('http://localhost:5000/User/login', userDetails).then(res => {
    console.log(JSON.stringify(res))
    this.props.history.push('/list');
})
</code>```

The response is recieved by call,

{"data":"","status":200,"statusText":"OK","headers":{"content-length":"0"},"config":{"url":"http://localhost:5000/User/login","method":"post","data":"{\"email\":\"a\",\"password\":\"a\"}","headers":{"Accept":"application/json,
  text/plain,
  /","Content-Type":"application/json;charset=utf-8"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

But no cookie ends up being set, could somebody tell me what the issue here is?
Thanks-

I also have

```<code>app.use(cookieParser());
</code>```

as the first app use, as that was recommended, but this did not help

答:
I have finally figured it out:

It turns out by default Axios has 'withCredentials' set to false, so I created a new instance with an override and used this instead

```<code>var myAxios = Axios.create ({
    withCredentials: true
})
</code>```

This also required me to update cors to accept these credentials

```<code>app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
</code>```

Body:
I'm currently trying to send a cookie back to my react app after logging in,
In my server I have a test response:

res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end();

and in the app I have

Axios.post('http://localhost:5000/User/login', userDetails).then(res => {
    console.log(JSON.stringify(res))
    this.props.history.push('/list');
})

The response is recieved by call,

{"data":"","status":200,"statusText":"OK","headers":{"content-length":"0"},"config":{"url":"http://localhost:5000/User/login","method":"post","data":"{\"email\":\"a\",\"password\":\"a\"}","headers":{"Accept":"application/json,
  text/plain,
  /","Content-Type":"application/json;charset=utf-8"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

But no cookie ends up being set, could somebody tell me what the issue here is?
Thanks-

I also have

app.use(cookieParser());

as the first app use, as that was recommended, but this did not help

Body:
I have finally figured it out:

It turns out by default Axios has 'withCredentials' set to false, so I created a new instance with an override and used this instead

var myAxios = Axios.create ({
    withCredentials: true
})

This also required me to update cors to accept these credentials

app.use(cors({credentials: true, origin: 'http://localhost:3000'}));


问:
Left join not showing all data while using sum
I have 2 Tables named Product, Stock as follows
Product Table:-

```<code>Id     Name     Hand
1      A        50
2      B        5
3      C        10
</code>```

Stock Table:-

```<code>Id    Pid     Qty
1     1       50
</code>```

I want total stock of every product so hand column showing the opening stock.
I tried:

```<code>select product.id, name, hand, count(qty)
from product
left join stock on pid=product.id
</code>```

but it's giving me only the first product detail even i am doing left join

答:
You must group by product and use sum() instead of count():

```<code>select p.id, p.name, p.hand, coalesce(sum(qty), 0) totalstock
from product p left join stock s
on s.pid = p.id
group by p.id, p.name, p.hand
</code>```

See the demo.

Results:

```<code>| id  | name | hand | totalstock |
| --- | ---- | ---- | ---------- |
| 1   | A    | 50   | 50         |
| 2   | B    | 5    | 0          |
| 3   | C    | 10   | 0          |
</code>```

Body:
I have 2 Tables named Product, Stock as follows
Product Table:-

Id     Name     Hand
1      A        50
2      B        5
3      C        10

Stock Table:-

Id    Pid     Qty
1     1       50

I want total stock of every product so hand column showing the opening stock.
I tried:

select product.id, name, hand, count(qty)
from product
left join stock on pid=product.id

but it's giving me only the first product detail even i am doing left join

Body:
You must group by product and use sum() instead of count():

select p.id, p.name, p.hand, coalesce(sum(qty), 0) totalstock
from product p left join stock s
on s.pid = p.id
group by p.id, p.name, p.hand

See the demo.

Results:

| id  | name | hand | totalstock |
| --- | ---- | ---- | ---------- |
| 1   | A    | 50   | 50         |
| 2   | B    | 5    | 0          |
| 3   | C    | 10   | 0          |


问:
Problems calling an as3 function from javascript
So my team's project has an swf embedded in JavaScript, we're actually using java servlet's to create the html/JavaScript. I am attempting to use as3's ExternalInterface to add a callback which would get called in the javascript but everything I have tried will not work.

Here is some of the related code:

Javascript:(remember using servlets thats why this is all inside a string)

```<code><html>
<head>
    <script src='/oddmanor/AC_OETags.js' language='javascript'></script>
    <script language='JavaScript' type='text/javascript'>
        var requiredMajorVersion = 10;
        var requiredMinorVersion = 1;
        var requiredRevision = 0;
    </script>
</head>
<body marginwidth='0' marginheight='0' leftmargin='0' topmargin='0'>
    <script language='JavaScript' type='text/javascript'>
    var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
    if (hasReqestedVersion) {
        AC_FL_RunContent(
            'src', 'http://localhost:8080/download/FlashClient',
            'width', '760',
            'height', '600',
            'align', 'middle',
            'id', 'myswf',
            'quality', 'high',
            'bgcolor', '#FFFFFF',
            'name', 'myswf',
            'allowScriptAccess','always',
            'type', 'application/x-shockwave-flash',
            'codebase', 'http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab',
            'pluginspage', 'http://www.adobe.com/go/getflashplayer',
            'wmode', 'opaque',
            'flashvars', 'challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk'
        );
    } else {
        var alternateContent = 'Alternate HTML content should be placed here.<BR>'
        + 'This content requires the Adobe Flash Player. '
        + '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
        document.write(alternateContent);
    }

    </script>
    <noscript>
    <div align="middle" id="swf">
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">
    <param name="src" value="http://localhost:8080/download/FlashClient">
    <param name="width" value="760">
    <param name="height" value="600">
    <param name="align" value="middle">
    <param name="id" value="myswf">
    <param name="quality" value="high">
    <param name="bgcolor" value="#FFFFFF">
    <param name="name" value="myswf">
    <param name="allowScriptAccess" value="always">
    <param name="type" value="application/x-shockwave-flash">
    <param name="codebase" value="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="pluginspage" value="http://www.adobe.com/go/getflashplayer">
    <param name="wmode" value="opaque">
    <param name="flashvars" value="challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk">
    <embed src="http://localhost:8080/download/FlashClient" width="760" height="600" align="middle" id="myswf" quality="high" bgcolor="#FFFFFF" name="myswf" allowScriptAccess="always" type="application/x-shockwave-flash" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="opaque" flashvars="challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk" />
    </object>
        This content requires the Adobe Flash Player and a browser with JavaScript enabled.
        <a href='http://www.adobe.com/go/getflash/'>Get Flash</a>
    </div>
    </noscript>
    <div>
        <a href='http://d1fjc9whyjwawe.cloudfront.net/KingX_Studios_Terms_of_Service.pdf' TARGET='_blank'>KingX Terms of Service</a> |
        <a href='http://d1fjc9whyjwawe.cloudfront.net/Privacy_Policy_Odd_Manor.pdf' TARGET='_blank'>Privacy Policy</a> |
        <a href='http://www.activeboard.com/forum.spark?aBID=138536&topicID=42164567&p=3' TARGET='_blank'>Report a Bug</a>
    </div>
    <div id='fb-root'></div>
    <script src='http://connect.facebook.net/en_US/all.js'></script>
    <script type='text/javascript'>
        FB.init(
            {
                'appId': '191461020878253',
                'status': true,
                'cookie': true,
                'channelUrl': 'http://nimbus.com:8080/oddmanor/fb_channel.html'
            }
        );

        var callback = function(data) {
            var res;
            if (data['order_id']) {
                res = true;
            }
            else {
                res = false;
            }
            var me;
            if (navigator.appName.indexOf('Microsoft') != -1) {
                me = window['myswf'];
            }
            else {
                me = document['myswf'];
            }
            me.onPurchaseCompletion(res);
        };

        function getFlashMovie(movieName) {
           var isIE = navigator.appName.indexOf("Microsoft") != -1;
           return (isIE) ? window[movieName] : document[movieName];  }

        function getFriendsUsingApp()
        {
            alert("ALERRRRRT!!!");
            getFlashMovie("myswf").passFriendArrayToFlash();
            return "set2";
        }

        function makePurchase(objectInfo) {
            var obj = {
                'method': 'pay',
                'order_info': objectInfo,
                'purchase_type': 'item'
            };

            FB.ui(obj, callback);
        }
    </script>
</body>
</html>
</code>```

Also I ripped out a bit of JavaScript code that didnt have anything to do with this problem(hopefully) so if there is a missing tag or something that's probably not my problem.

NOTE I embed this correctly and get into the swf allowing it to call javascript functions(as3 calls the getStuff fn), using the ExternalInterface, which works but JS->as3 does NOT work ='(.

Other notes,
FlashClient is the name of the swf....

I cant use the movie object for anything (the return value of getFlashMovie), if I try to use no code after works...

The action script code calls the external interface addCallback function correctly(called in a try catch that's how I know)
if(External...Availible)
External...addCallback("passStuff", as3PassStuff)

The only things I can think of;
1) The embed code isnt creating the object correctly, since I cant use the movie for anything
2) my swf is being created weird and doesnt allow script access.

We are using FlashBuilder to build the swf.

答:
```<code>System.security.allowDomain("*");
</code>```

in my swf and we're good.

Body:
So my team's project has an swf embedded in JavaScript, we're actually using java servlet's to create the html/JavaScript. I am attempting to use as3's ExternalInterface to add a callback which would get called in the javascript but everything I have tried will not work.

Here is some of the related code:

Javascript:(remember using servlets thats why this is all inside a string)

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">
    <param name="src" value="http://localhost:8080/download/FlashClient">
    <param name="width" value="760">
    <param name="height" value="600">
    <param name="align" value="middle">
    <param name="id" value="myswf">
    <param name="quality" value="high">
    <param name="bgcolor" value="#FFFFFF">
    <param name="name" value="myswf">
    <param name="allowScriptAccess" value="always">
    <param name="type" value="application/x-shockwave-flash">
    <param name="codebase" value="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="pluginspage" value="http://www.adobe.com/go/getflashplayer">
    <param name="wmode" value="opaque">
    <param name="flashvars" value="challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk">
    <embed src="http://localhost:8080/download/FlashClient" width="760" height="600" align="middle" id="myswf" quality="high" bgcolor="#FFFFFF" name="myswf" allowScriptAccess="always" type="application/x-shockwave-flash" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="opaque" flashvars="challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk" />
    </object>
        This content requires the Adobe Flash Player and a browser with JavaScript enabled.
        Get Flash

        KingX Terms of Service |
        Privacy Policy |
        Report a Bug

Also I ripped out a bit of JavaScript code that didnt have anything to do with this problem(hopefully) so if there is a missing tag or something that's probably not my problem.

NOTE I embed this correctly and get into the swf allowing it to call javascript functions(as3 calls the getStuff fn), using the ExternalInterface, which works but JS->as3 does NOT work ='(.

Other notes,
FlashClient is the name of the swf....

I cant use the movie object for anything (the return value of getFlashMovie), if I try to use no code after works...

The action script code calls the external interface addCallback function correctly(called in a try catch that's how I know)
if(External...Availible)
External...addCallback("passStuff", as3PassStuff)

The only things I can think of;
1) The embed code isnt creating the object correctly, since I cant use the movie for anything
2) my swf is being created weird and doesnt allow script access.

We are using FlashBuilder to build the swf.

Body:
System.security.allowDomain("*");

in my swf and we're good.


问:
'The following gems are missing'
I am trying to create a Rails app that can be copied to another hard drive without having to reinstall its gems.

One thing I've tried is bundle install the gems into vendor/bundle, then copy the entire app over to the new location.

At the new location:

```<code>bundle config set path 'vendor/bundle'
bundle check
# which returns...
The following gems are missing
 * nokogiri (1.10.8)
 * nio4r (2.5.2)
 * websocket-driver (0.7.1)
 * bcrypt (3.1.7)
 * ffi (1.12.2)
 * sassc (2.2.1)
 * pg (1.2.2)
 * puma (4.3.1)
Install missing gems with `bundle install`
</code>```

However, when I go to vendor/bundle/ruby/2.7.0/gems, I see every one of those gems listed.

Try to follow the instruction using the gems in the folder above:

```<code>bundle install --local
=> Could not find nokogiri-1.10.8 in any of the sources
</code>```

Bundle configuration:

```<code>~/myapp/.bundle/config:
---
BUNDLE_PATH: "vendor/bundle"
</code>```

What's going on here?

答:
Not an answer to your specific question but, a taking a higher view of the issue and recommending a change in approach.

Containerised applications have been created to solve issues like this. Docker is a freely available tool which I recommend you use here.

Here are some links to start you off. It will take a medium investment now of 1-6 hours of playing around but, you'll save time overall. I've been where you are before, since moving to containerised applications I've never looked back

Docker getting started

Docker and Rails

Title: 'The following gems are missing'

Body:
I am trying to create a Rails app that can be copied to another hard drive without having to reinstall its gems.

One thing I've tried is bundle install the gems into vendor/bundle, then copy the entire app over to the new location.

At the new location:

bundle config set path 'vendor/bundle'
bundle check
# which returns...
The following gems are missing
 * nokogiri (1.10.8)
 * nio4r (2.5.2)
 * websocket-driver (0.7.1)
 * bcrypt (3.1.7)
 * ffi (1.12.2)
 * sassc (2.2.1)
 * pg (1.2.2)
 * puma (4.3.1)
Install missing gems with `bundle install`

However, when I go to vendor/bundle/ruby/2.7.0/gems, I see every one of those gems listed.

Try to follow the instruction using the gems in the folder above:

bundle install --local
=> Could not find nokogiri-1.10.8 in any of the sources

Bundle configuration:

~/myapp/.bundle/config:
---
BUNDLE_PATH: "vendor/bundle"

What's going on here?


问:
Is there any C function that can evalute a string expression defined in the standard library?
I am looking for a function that can evaluate a string expression into an integer, like f.e.:

```<code>10/2+4*3-(12+5); //Equals 0
</code>```

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

```<code>2^(1/2)-99
</code>```

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.

答:
Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

No, not even in the more recent standard libraries of C11 or C18.

Is there any non-standard library which has such an function?

I couldn´t found one either. You have to write your own function to accomplish that.

Maybe scan the string and store every value in it to a separate string at the first step.

As I already suggested in the comments, strtol is used to convert an integer value like 11 in a string to a value of type int. You might need to take use of that. In the libraries there is also a function of atoi to convert an integer value inside a string to an int but this function is more susceptible for errors and should not be used.

The arithmetic operators shall be stored in separate strings also, but later evaluated by a self-made routine.

But good examples and recommendations can be found here, where a user have been asked a similar (if not the same) question:

C: convert a mathematical expression string into an int with the result

Body:
I am looking for a function that can evaluate a string expression into an integer, like f.e.:

10/2+4*3-(12+5); //Equals 0

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

2^(1/2)-99

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.


问:
Uploaded file from Html form to S3 using python but getting blank text file
I have an HTML form (implemented in Flask) for uploading files. And I want to store the uploaded files directly to S3.

The relevant part of the Flask implementation is as follows:

```<code>@app.route('/',methods=['GET'])
def index():
    return '<form method="post" action="/upload" enctype="multipart/form-data"><input type="file" name="file" /><button>Upload</button></form>'
</code>```

I then use boto3 to upload the file to S3 as follows:

```<code>@app.route('/upload',methods = ['GET','POST'])
    def upload_file():
        if request.method =='POST':
            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                #file.save(os.path.join(UPLOAD_FOLDER,filename))
                s3_resource = boto3.resource('s3',aws_access_key_id='****',
                            aws_secret_access_key='*****')
                buck = s3_resource.Bucket('MY_BUCKET_NAME')
                buck.Object(file.filename).put(Body=file.read())

            return 'uploaded'
</code>```

File is getting uploaded successfully in S3 Bucket. And when trying to open that file it is opening as blank text file. Even I tried to set ContentType in put() method but still not working.

Also its size is showing 0B

Please let me know whats going wrong?

Thanks!

答:
You have certainly reached end of stream.

file.read() has no bytes to read, hence empty file on s3.

Either try file.seek(0) to reset the stream or you must ensure that you are reading file once.

For example:

```<code># You just read the file here.
file.save(os.path.join(UPLOAD_FOLDER, filename))
# file.read() is empty now, you reached to the end of stream

# You are again reading the file here but file.read() is empty, so reset the stream.
file.seek(0)
# file.read() is back to original now
buck.Object(file.filename).put(Body=file.read())
</code>```

Body:
I have an HTML form (implemented in Flask) for uploading files. And I want to store the uploaded files directly to S3.

The relevant part of the Flask implementation is as follows:

@app.route('/',methods=['GET'])
def index():
    return '<form method="post" action="/upload" enctype="multipart/form-data"><input type="file" name="file" /><button>Upload</button></form>'

I then use boto3 to upload the file to S3 as follows:

@app.route('/upload',methods = ['GET','POST'])
    def upload_file():
        if request.method =='POST':
            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                #file.save(os.path.join(UPLOAD_FOLDER,filename))
                s3_resource = boto3.resource('s3',aws_access_key_id='****',
                            aws_secret_access_key='*****')
                buck = s3_resource.Bucket('MY_BUCKET_NAME')
                buck.Object(file.filename).put(Body=file.read())

            return 'uploaded'

File is getting uploaded successfully in S3 Bucket. And when trying to open that file it is opening as blank text file. Even I tried to set ContentType in put() method but still not working.

Also its size is showing 0B

Please let me know whats going wrong?

Thanks!

Body:
You have certainly reached end of stream.

file.read() has no bytes to read, hence empty file on s3.

Either try file.seek(0) to reset the stream or you must ensure that you are reading file once.

For example:

# You just read the file here.
file.save(os.path.join(UPLOAD_FOLDER, filename))
# file.read() is empty now, you reached to the end of stream

# You are again reading the file here but file.read() is empty, so reset the stream.
file.seek(0)
# file.read() is back to original now
buck.Object(file.filename).put(Body=file.read())


问:
How do I parse this file in cpp?
I want to parse a file with the following content:

```<code>2 300
abc12 130
bcd22 456
3 400
abfg12 230
bcpd22 46
abfrg2 13
</code>```

Here, 2 is the number of lines, 300 is the weight.

Each line has a string and a number(price). Same with 3 and 400.

I need to store 130, 456 in an array.

Currently, I am reading the file and each line is processed as std::string. I need help to progress further.

Code:

```<code>#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//void processString(string line);
void process2(string line);

int main(int argc, char ** argv) {
    cout << "You have entered " << argc <<
        " arguments:" << "\n";

    for (int i = 1; i < argc; ++i)
        cout << argv[i] << "\n";

    //2, 4 are the file names

    //Reading file - market price file
    string line;
    ifstream myfile(argv[2]);
    if (myfile.is_open()) {
        while (getline(myfile, line)) {
            //  cout << line << '\n';
        }
        myfile.close();
    } else cout << "Unable to open market price file";

    //Reading file - price list file
    string line_;
    ifstream myfile2(argv[4]);
    int c = 1;
    if (myfile2.is_open()) {
        while (getline(myfile2, line_)) {
            // processString(line_);
            process2(line_);
        }
        myfile2.close();
    } else cout << "Unable to open price lists file";

    //processString(line_);
    return 0;
}

void process2(string line) {

    string word = "";

    for (auto x: line) {
        if (x == ' ') {
            word += " ";
        } else {
            word = word + x;
        }
    }
    cout << word << endl;
}
</code>```

Is there a split function like in Java, so I can split and store everything as tokens?

答:
You have 2 questions in your post:

How do I parse this file in cpp?

Is there a split function like in Java, so I can split and store everything as tokens?

I will answer both questions and show a demo example.

Let's start with splitting a string into tokens. There are several possibilities. We start with the easy ones.

Since the tokens in your string are delimited by a whitespace, we can take advantage of the functionality of the extractor operator (>>). This will read data from an input stream, up to a whitespace and then converts this read data into the specified variable. You know that this operation can be chained.

Then for the example string

```<code>    const std::string line{ "Token1 Token2 Token3 Token4" };
</code>```

you can simply put that into a std::istringstream and then extract the variables from the stream:

```<code>    std::istringstream iss1(line);
    iss1 >> subString1 >> subString2 >> subString3 >> subString4;
</code>```

The disadvantage is that you need to write a lot of stuff and you have to know the number of elements in the string.

We can overcome this problem with using a vector as the taget data store and fill it with its range constructor. The vectors range constructor takes a begin and and end interator and copies the data into it.

As iterator we use the std::istream_iterator. This will, in simple terms, call the extractor operator (>>) until all data is consumed. Whatever number of data we will have.

This will then look like the below:

```<code>    std::istringstream iss2(line);
    std::vector token(std::istream_iterator<std::string>(iss2), {});
</code>```

This may look complicated, but is not. We define a variable "token" of type std::vector. We use its range constructor.

And, we can define the std::vector without template argument. The compiler can deduce the argument from the given function parameters. This feature is called CTAD ("class template argument deduction", C++17 required).

Additionally, you can see that I do not use the "end()"-iterator explicitely.

This iterator will be constructed from the empty brace-enclosed default initializer with the correct type, because it will be deduced to be the same as the type of the first argument due to the std::vector constructor requiring that.

There is an additional solution. It is the most powerful solution and hence maybe a little bit to complicated in the beginning.

With that can avoid the usage of std::istringstream and directly convert the string into tokens using std::sregex_token_iterator. Very simple to use. And the result is a one liner for splitting the original string:

```<code>std::vector<std::string> token2(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});
</code>```

So, modern C++ has a build in functionality which is exactly designed for the purpose of tokenizing strings. It is called std::sregex_token_iterator. What is this thing?

As it name says, it is an iterator. It will iterate over a string (hence the 's' in its name) and return the split up tokens. The tokens will be matched again a regular expression. Or, natively, the delimiter will be matched and the rest will be seen as token and returned. This will be controlled via the last flag in its constructor.

Let's have a look at this constructor:

```<code>token2(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});
</code>```

The first parameter is, where it should start in the source string, the 2nd parameter is the end position, up to which the iterator should work. The last parameter is:

1, if you want to have a positive match for the regex

-1, will return everything that not matches the regex

And last but not least the regex itself. Please read in the net abot regex'es. There are tons of pages available.

Please see a demo for all 3 solutions here:

```<code>#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <sstream>
#include <iterator>
#include <algorithm>

/// Split string into tokens
int main() {

    // White space separated tokens in a string
    const std::string line{ "Token1 Token2 Token3 Token4" };

    // Solution 1: Use extractor operator ----------------------------------

    // Here, we will store the result
    std::string subString1{}, subString2{}, subString3{}, subString4{};

    // Put the line into an istringstream for easier extraction
    std::istringstream iss1(line);
    iss1 >> subString1 >> subString2 >> subString3 >> subString4;

    // Show result
    std::cout << "\nSolution 1:  Use inserter operator\n- Data: -\n" << subString1 << "\n"
        << subString2 << "\n" << subString3 << "\n" << subString4 << "\n";

    // Solution 2: Use istream_iterator ----------------------------------
    std::istringstream iss2(line);
    std::vector token(std::istream_iterator<std::string>(iss2), {});

    // Show result
    std::cout << "\nSolution 2:  Use istream_iterator\n- Data: -\n";
    std::copy(token.begin(), token.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

    // Solution 3: Use std::sregex_token_iterator ----------------------------------
    const std::regex re(" ");

    std::vector<std::string> token2(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});

    // Show result
    std::cout << "\nSolution 3:  Use sregex_token_iterator\n- Data: -\n";
    std::copy(token2.begin(), token2.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}
</code>```

So, now the answer on how you could read you text file.

It is essential to create the correct data structures. Then, overwrite the inserter and extractor operator and put the above functionality in it.

Please see the below demo example. Of course there are many other possible solutions:

```<code>#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>

struct ItemAndPrice {
    // Data
    std::string item{};
    unsigned int price{};

    // Extractor
    friend std::istream& operator >> (std::istream& is, ItemAndPrice& iap) {

        // Read a complete line from the stream and check, if that worked
        if (std::string line{}; std::getline(is, line)) {

            // Read the item and price from that line and check, if that worked
            if (std::istringstream iss(line); !(iss >> iap.item >> iap.price))

                // There was an error, while reading item and price. Set failbit of input stream
                is.setf(std::ios::failbit);
        }
        return is;
    }

    // Inserter
    friend std::ostream& operator << (std::ostream& os, const ItemAndPrice& iap) {
        // Simple output of our internal data
        return os << iap.item << " " << iap.price;
    }
};

struct MarketPrice {
    // Data
    std::vector<ItemAndPrice> marketPriceData{};
    size_t numberOfElements() const { return marketPriceData.size(); }
    unsigned int weight{};

    // Extractor
    friend std::istream& operator >> (std::istream& is, MarketPrice& mp) {

        // Read a complete line from the stream and check, if that worked
        if (std::string line{}; std::getline(is, line)) {

            size_t numberOfEntries{};
            // Read the number of following entries and the weigth from that line and check, if that worked
            if (std::istringstream iss(line); (iss >> numberOfEntries >> mp.weight)) {

                mp.marketPriceData.clear();
                // Now copy the numberOfEntries next lines into our vector
                std::copy_n(std::istream_iterator<ItemAndPrice>(is), numberOfEntries, std::back_inserter(mp.marketPriceData));
            }
            else {
                // There was an error, while reading number of following entries and the weigth. Set failbit of input stream
                is.setf(std::ios::failbit);
            }
        }
        return is;
    };

    // Inserter
    friend std::ostream& operator << (std::ostream& os, const MarketPrice& mp) {

        // Simple output of our internal data
        os << "\nNumber of Elements: " << mp.numberOfElements() << "   Weight: " << mp.weight << "\n";

        // Now copy all marekt price data to output stream
        if (os) std::copy(mp.marketPriceData.begin(), mp.marketPriceData.end(), std::ostream_iterator<ItemAndPrice>(os, "\n"));

        return os;
    }
};

// For this example I do not use argv and argc and file streams.
// This, because on Stackoverflow, I do not have files on Stackoverflow
// So, I put the file data in an istringstream. But for the below example,
// there is no difference between a file stream or a string stream

std::istringstream sourceFile{R"(2 300
abc12 130
bcd22 456
3 400
abfg12 230
bcpd22 46
abfrg2 13)"};

int main() {

    // Here we will store all the resulting data
    // So, read the complete source file, parse the data and store result in vector
    std::vector mp(std::istream_iterator<MarketPrice>(sourceFile), {});

    // Now, all data are in mp. You may work with that now

    // Show result on display
    std::copy(mp.begin(), mp.end(), std::ostream_iterator<MarketPrice>(std::cout, "\n"));

    return 0;
}
</code>```

Title: How do I parse this file in cpp?

Body:
I want to parse a file with the following content:

2 300
abc12 130
bcd22 456
3 400
abfg12 230
bcpd22 46
abfrg2 13

Here, 2 is the number of lines, 300 is the weight.

Each line has a string and a number(price). Same with 3 and 400.

I need to store 130, 456 in an array.

Currently, I am reading the file and each line is processed as std::string. I need help to progress further.

Code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//void processString(string line);
void process2(string line);

int main(int argc, char ** argv) {
    cout << "You have entered " << argc <<
        " arguments:" << "\n";

    for (int i = 1; i < argc; ++i)
        cout << argv[i] << "\n";

    //2, 4 are the file names

    //Reading file - market price file
    string line;
    ifstream myfile(argv[2]);
    if (myfile.is_open()) {
        while (getline(myfile, line)) {
            //  cout << line << '\n';
        }
        myfile.close();
    } else cout << "Unable to open market price file";

    //Reading file - price list file
    string line_;
    ifstream myfile2(argv[4]);
    int c = 1;
    if (myfile2.is_open()) {
        while (getline(myfile2, line_)) {
            // processString(line_);
            process2(line_);
        }
        myfile2.close();
    } else cout << "Unable to open price lists file";

    //processString(line_);
    return 0;
}

void process2(string line) {

    string word = "";

    for (auto x: line) {
        if (x == ' ') {
            word += " ";
        } else {
            word = word + x;
        }
    }
    cout << word << endl;
}

Is there a split function like in Java, so I can split and store everything as tokens?

Body:
You have 2 questions in your post:

How do I parse this file in cpp?

Is there a split function like in Java, so I can split and store everything as tokens?

I will answer both questions and show a demo example.

Let's start with splitting a string into tokens. There are several possibilities. We start with the easy ones.

Since the tokens in your string are delimited by a whitespace, we can take advantage of the functionality of the extractor operator (>>). This will read data from an input stream, up to a whitespace and then converts this read data into the specified variable. You know that this operation can be chained.

Then for the example string

    const std::string line{ "Token1 Token2 Token3 Token4" };

you can simply put that into a std::istringstream and then extract the variables from the stream:

    std::istringstream iss1(line);
    iss1 >> subString1 >> subString2 >> subString3 >> subString4;

The disadvantage is that you need to write a lot of stuff and you have to know the number of elements in the string.

We can overcome this problem with using a vector as the taget data store and fill it with its range constructor. The vectors range constructor takes a begin and and end interator and copies the data into it.

As iterator we use the std::istream_iterator. This will, in simple terms, call the extractor operator (>>) until all data is consumed. Whatever number of data we will have.

This will then look like the below:

    std::istringstream iss2(line);
    std::vector token(std::istream_iterator<std::string>(iss2), {});

This may look complicated, but is not. We define a variable "token" of type std::vector. We use its range constructor.

And, we can define the std::vector without template argument. The compiler can deduce the argument from the given function parameters. This feature is called CTAD ("class template argument deduction", C++17 required).

Additionally, you can see that I do not use the "end()"-iterator explicitely.

This iterator will be constructed from the empty brace-enclosed default initializer with the correct type, because it will be deduced to be the same as the type of the first argument due to the std::vector constructor requiring that.

There is an additional solution. It is the most powerful solution and hence maybe a little bit to complicated in the beginning.

With that can avoid the usage of std::istringstream and directly convert the string into tokens using std::sregex_token_iterator. Very simple to use. And the result is a one liner for splitting the original string:

std::vector<std::string> token2(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});

So, modern C++ has a build in functionality which is exactly designed for the purpose of tokenizing strings. It is called std::sregex_token_iterator. What is this thing?

As it name says, it is an iterator. It will iterate over a string (hence the 's' in its name) and return the split up tokens. The tokens will be matched again a regular expression. Or, natively, the delimiter will be matched and the rest will be seen as token and returned. This will be controlled via the last flag in its constructor.

Let's have a look at this constructor:

token2(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});

The first parameter is, where it should start in the source string, the 2nd parameter is the end position, up to which the iterator should work. The last parameter is:

1, if you want to have a positive match for the regex

-1, will return everything that not matches the regex

And last but not least the regex itself. Please read in the net abot regex'es. There are tons of pages available.

Please see a demo for all 3 solutions here:

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <sstream>
#include <iterator>
#include <algorithm>

/// Split string into tokens
int main() {

    // White space separated tokens in a string
    const std::string line{ "Token1 Token2 Token3 Token4" };

    // Solution 1: Use extractor operator ----------------------------------

    // Here, we will store the result
    std::string subString1{}, subString2{}, subString3{}, subString4{};

    // Put the line into an istringstream for easier extraction
    std::istringstream iss1(line);
    iss1 >> subString1 >> subString2 >> subString3 >> subString4;

    // Show result
    std::cout << "\nSolution 1:  Use inserter operator\n- Data: -\n" << subString1 << "\n"
        << subString2 << "\n" << subString3 << "\n" << subString4 << "\n";

    // Solution 2: Use istream_iterator ----------------------------------
    std::istringstream iss2(line);
    std::vector token(std::istream_iterator<std::string>(iss2), {});

    // Show result
    std::cout << "\nSolution 2:  Use istream_iterator\n- Data: -\n";
    std::copy(token.begin(), token.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

    // Solution 3: Use std::sregex_token_iterator ----------------------------------
    const std::regex re(" ");

    std::vector<std::string> token2(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {});

    // Show result
    std::cout << "\nSolution 3:  Use sregex_token_iterator\n- Data: -\n";
    std::copy(token2.begin(), token2.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}

So, now the answer on how you could read you text file.

It is essential to create the correct data structures. Then, overwrite the inserter and extractor operator and put the above functionality in it.

Please see the below demo example. Of course there are many other possible solutions:

#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>

struct ItemAndPrice {
    // Data
    std::string item{};
    unsigned int price{};

    // Extractor
    friend std::istream& operator >> (std::istream& is, ItemAndPrice& iap) {

        // Read a complete line from the stream and check, if that worked
        if (std::string line{}; std::getline(is, line)) {

            // Read the item and price from that line and check, if that worked
            if (std::istringstream iss(line); !(iss >> iap.item >> iap.price))

                // There was an error, while reading item and price. Set failbit of input stream
                is.setf(std::ios::failbit);
        }
        return is;
    }

    // Inserter
    friend std::ostream& operator << (std::ostream& os, const ItemAndPrice& iap) {
        // Simple output of our internal data
        return os << iap.item << " " << iap.price;
    }
};

struct MarketPrice {
    // Data
    std::vector<ItemAndPrice> marketPriceData{};
    size_t numberOfElements() const { return marketPriceData.size(); }
    unsigned int weight{};

    // Extractor
    friend std::istream& operator >> (std::istream& is, MarketPrice& mp) {

        // Read a complete line from the stream and check, if that worked
        if (std::string line{}; std::getline(is, line)) {

            size_t numberOfEntries{};
            // Read the number of following entries and the weigth from that line and check, if that worked
            if (std::istringstream iss(line); (iss >> numberOfEntries >> mp.weight)) {

                mp.marketPriceData.clear();
                // Now copy the numberOfEntries next lines into our vector
                std::copy_n(std::istream_iterator<ItemAndPrice>(is), numberOfEntries, std::back_inserter(mp.marketPriceData));
            }
            else {
                // There was an error, while reading number of following entries and the weigth. Set failbit of input stream
                is.setf(std::ios::failbit);
            }
        }
        return is;
    };

    // Inserter
    friend std::ostream& operator << (std::ostream& os, const MarketPrice& mp) {

        // Simple output of our internal data
        os << "\nNumber of Elements: " << mp.numberOfElements() << "   Weight: " << mp.weight << "\n";

        // Now copy all marekt price data to output stream
        if (os) std::copy(mp.marketPriceData.begin(), mp.marketPriceData.end(), std::ostream_iterator<ItemAndPrice>(os, "\n"));

        return os;
    }
};

// For this example I do not use argv and argc and file streams.
// This, because on Stackoverflow, I do not have files on Stackoverflow
// So, I put the file data in an istringstream. But for the below example,
// there is no difference between a file stream or a string stream

std::istringstream sourceFile{R"(2 300
abc12 130
bcd22 456
3 400
abfg12 230
bcpd22 46
abfrg2 13)"};

int main() {

    // Here we will store all the resulting data
    // So, read the complete source file, parse the data and store result in vector
    std::vector mp(std::istream_iterator<MarketPrice>(sourceFile), {});

    // Now, all data are in mp. You may work with that now

    // Show result on display
    std::copy(mp.begin(), mp.end(), std::ostream_iterator<MarketPrice>(std::cout, "\n"));

    return 0;
}