问:
Not able to figure out issue in jest code coverage
I have below file in my nestjs.

```<code>import { extname } from 'path';
import { diskStorage } from 'multer';
import { v4 as uuid } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';

export const multerConfig = {
    dest: process.env.UPLOAD_LOCATION,
};

export const multerOptions = {
    limits: {
        fileSize: +process.env.MAX_FILE_SIZE,
    },
    fileFilter: (_req: any, file: any, cb: any) => {
        if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
            cb(null, true);
        } else {
            cb(
                new HttpException(
                    `Unsupported file type ${extname(file.originalname)}`,
                    HttpStatus.BAD_REQUEST
                ),
                false
            );
        }
    },
    storage: diskStorage({
        destination: multerConfig.dest,
        filename: (_req: any, file: any, cb: any) => {
            cb(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
};
</code>```

I wrote below test cases for it.

```<code>import { Readable } from 'stream';
import { multerConfig, multerOptions } from './multer.config';

describe('Multer Configuration ', () => {
    const mockFile: Express.Multer.File = {
        filename: '',
        fieldname: '',
        originalname: '',
        encoding: '',
        mimetype: '',
        size: 1,
        stream: new Readable(),
        destination: '',
        path: '',
        buffer: Buffer.from('', 'utf8'),
    };
    it('should define destination', () => {
        expect(multerConfig).toBeDefined();
        expect(multerConfig.dest).toBe(process.env.UPLOAD_LOCATION);
    });

    it('should define multer upload options', async () => {
        expect(multerOptions).toBeDefined();
        expect(multerOptions.fileFilter).toBeDefined();
        expect(multerOptions.storage).toBeTruthy();
        expect(multerOptions.limits).toBeTruthy();

        const cb = jest.fn();
        multerOptions.fileFilter({}, mockFile, cb);
        expect(cb).toHaveBeenCalled();
        expect(cb).toHaveBeenCalledTimes(1);
        expect(cb()).toBeFalsy();
    });

    afterAll(() => {
        jest.resetAllMocks();
    });
});
</code>```

Both the test cases are successful but when I check code coverage then it is showing only 50% .It is showing line 16 and 31 not covered.

Line 16 is

```<code> cb(null, true); it comes inside the `if` block
</code>```

and line 31 is

```<code> cb(null, `${uuid()}${extname(file.originalname)}`);
</code>```

Could you please help me how can I cover this part? I am really struggling.
Do I need to additional test case or I need to modify the existing test case?

Edit 1:-

```<code> const fileType = 'jpg';

    it('should define filetype', async () => {
        const cb = jest.fn();
        process.env.FILE_TYPE = 'jpg';
        multerOptions.fileFilter({}, mockFile, cb);
        expect(cb).toHaveBeenCalled();
        expect(cb).toHaveBeenCalledTimes(1);
        expect(cb()).toBeFalsy();
    });
</code>```

Test case getting success. but coverage and lines are still same

答:
Your first not covered part of the code comes from the fact that you use pattern matching on the mime type.

if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
            cb(null, true);
}
```
<p>So you need to create a test that creates a mock file with one of those mime types.</p>
<p>For example, something like below. Although, in a good test setup, you probably would want to test all those extensions as a test case. Maybe with some sort of table driven test approach.</p>
<pre class="lang-js prettyprint-override"><code>const mockFile: Express.Multer.File = {
        mimetype: 'jpg',
        // other stuff
};
</code>```

It seems that in your test, the function always goes into the else block, which raises an HTTP Exception.

Your second issue is that you don't use options.storage, in your tests. And you also provide the options to something that would make the function get called.

Potentially, you can call it like below in your test.

const upload = multer(multerOptions).single('somefile');
```
<p>If you don't want to do that, you could move the callback into a named function and assign it.</p>
```export function filename(_req: any, file: any, cb: any) {
    cb(null, `${uuid()}${extname(file.originalname)}`);
}

export const multerOptions = {
    storage: diskStorage({
        destination: multerConfig.dest,
        filename,
    }),
}
```
<p>Then you can test the filename function on its own in your test setup.</p>
<p>Or you find a way to call the filename function on the storage object on its own. I don't know <code>multer</code>, so I cannot tell if it is possible. You would need to consult the documentation.</p>
<p>In total this might look like this.</p>
```import { extname } from 'path';
import { diskStorage } from 'multer';
import { v4 as uuid } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';

export const multerConfig = {
    dest: process.env.UPLOAD_LOCATION,
};

export function filename(_req: any, file: any, cb: any) {
            cb(null, `${uuid()}${extname(file.originalname)}`);
};

export const multerOptions = {
    limits: {
        fileSize: +process.env.MAX_FILE_SIZE,
    },
    fileFilter: (_req: any, file: any, cb: any) => {
        if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
            cb(null, true);
        } else {
            cb(
                new HttpException(
                    `Unsupported file type ${extname(file.originalname)}`,
                    HttpStatus.BAD_REQUEST
                ),
                false
            );
        }
    },
    storage: diskStorage({
        destination: multerConfig.dest,
        filename,
    }),
};
```
<p>And then in your test like this.</p>
```import { Readable } from 'stream';
import { multerConfig, multerOptions, filename } from './multer.config';

describe('Multer Configuration ', () => {
    const mockFile: Express.Multer.File = {
        filename: 'foo.jpg', // give it a name
        fieldname: '',
        originalname: '',
        encoding: 'utf8',
        mimetype: 'jpg', // give it a mime type
        size: 1,
        stream: new Readable(),
        destination: '',
        path: '',
        buffer: Buffer.from('', 'utf8'),
    };
    it('should define destination', () => {
        expect(multerConfig).toBeDefined();
        expect(multerConfig.dest).toBe(process.env.UPLOAD_LOCATION);
    });

    it('should define multer upload options', async () => {
        expect(multerOptions).toBeDefined();
        expect(multerOptions.fileFilter).toBeDefined();
        expect(multerOptions.storage).toBeTruthy();
        expect(multerOptions.limits).toBeTruthy();
    });

    // test the filter
    it('should filter the file based on mimetype', () => {
        const cb = jest.fn();
        multerOptions.fileFilter({}, mockFile, cb);
        // do something with the callback
    });

    // test the filename
    it('should create the proper filename', () => {
        const cb = jest.fn();
        filename({}, mockfile, cb)
        // do something with the callback
    });

    afterAll(() => {
        jest.resetAllMocks();
    });
});
```

I am not sure how to use jest or what you actually want to test. But like this, the line should get covered. But coverage doesn't mean much in that sense. The tests like this are not good. You should work out what precisely you want to test. This is just to show you wants roughly required.

Body:
I have below file in my nestjs.

import { extname } from 'path';
import { diskStorage } from 'multer';
import { v4 as uuid } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';

export const multerConfig = {
    dest: process.env.UPLOAD_LOCATION,
};

export const multerOptions = {
    limits: {
        fileSize: +process.env.MAX_FILE_SIZE,
    },
    fileFilter: (_req: any, file: any, cb: any) => {
        if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
            cb(null, true);
        } else {
            cb(
                new HttpException(
                    `Unsupported file type ${extname(file.originalname)}`,
                    HttpStatus.BAD_REQUEST
                ),
                false
            );
        }
    },
    storage: diskStorage({
        destination: multerConfig.dest,
        filename: (_req: any, file: any, cb: any) => {
            cb(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
};

I wrote below test cases for it.

import { Readable } from 'stream';
import { multerConfig, multerOptions } from './multer.config';

describe('Multer Configuration ', () => {
    const mockFile: Express.Multer.File = {
        filename: '',
        fieldname: '',
        originalname: '',
        encoding: '',
        mimetype: '',
        size: 1,
        stream: new Readable(),
        destination: '',
        path: '',
        buffer: Buffer.from('', 'utf8'),
    };
    it('should define destination', () => {
        expect(multerConfig).toBeDefined();
        expect(multerConfig.dest).toBe(process.env.UPLOAD_LOCATION);
    });

    it('should define multer upload options', async () => {
        expect(multerOptions).toBeDefined();
        expect(multerOptions.fileFilter).toBeDefined();
        expect(multerOptions.storage).toBeTruthy();
        expect(multerOptions.limits).toBeTruthy();

        const cb = jest.fn();
        multerOptions.fileFilter({}, mockFile, cb);
        expect(cb).toHaveBeenCalled();
        expect(cb).toHaveBeenCalledTimes(1);
        expect(cb()).toBeFalsy();
    });

    afterAll(() => {
        jest.resetAllMocks();
    });
});

Both the test cases are successful but when I check code coverage then it is showing only 50% .It is showing line 16 and 31 not covered.

Line 16 is

 cb(null, true); it comes inside the `if` block

and line 31 is

 cb(null, `${uuid()}${extname(file.originalname)}`);

Could you please help me how can I cover this part? I am really struggling.
Do I need to additional test case or I need to modify the existing test case?

Edit 1:-

 const fileType = 'jpg';

    it('should define filetype', async () => {
        const cb = jest.fn();
        process.env.FILE_TYPE = 'jpg';
        multerOptions.fileFilter({}, mockFile, cb);
        expect(cb).toHaveBeenCalled();
        expect(cb).toHaveBeenCalledTimes(1);
        expect(cb()).toBeFalsy();
    });

Test case getting success. but coverage and lines are still same

Body:
Your first not covered part of the code comes from the fact that you use pattern matching on the mime type.

if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
            cb(null, true);
}

So you need to create a test that creates a mock file with one of those mime types.

For example, something like below. Although, in a good test setup, you probably would want to test all those extensions as a test case. Maybe with some sort of table driven test approach.

const mockFile: Express.Multer.File = {
        mimetype: 'jpg',
        // other stuff
};

It seems that in your test, the function always goes into the else block, which raises an HTTP Exception.

Your second issue is that you don't use options.storage, in your tests. And you also provide the options to something that would make the function get called.

Potentially, you can call it like below in your test.

const upload = multer(multerOptions).single('somefile');

If you don't want to do that, you could move the callback into a named function and assign it.

export function filename(_req: any, file: any, cb: any) {
    cb(null, `${uuid()}${extname(file.originalname)}`);
}

export const multerOptions = {
    storage: diskStorage({
        destination: multerConfig.dest,
        filename,
    }),
}

Then you can test the filename function on its own in your test setup.

Or you find a way to call the filename function on the storage object on its own. I don't know multer, so I cannot tell if it is possible. You would need to consult the documentation.

In total this might look like this.

import { extname } from 'path';
import { diskStorage } from 'multer';
import { v4 as uuid } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';

export const multerConfig = {
    dest: process.env.UPLOAD_LOCATION,
};

export function filename(_req: any, file: any, cb: any) {
            cb(null, `${uuid()}${extname(file.originalname)}`);
};

export const multerOptions = {
    limits: {
        fileSize: +process.env.MAX_FILE_SIZE,
    },
    fileFilter: (_req: any, file: any, cb: any) => {
        if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
            cb(null, true);
        } else {
            cb(
                new HttpException(
                    `Unsupported file type ${extname(file.originalname)}`,
                    HttpStatus.BAD_REQUEST
                ),
                false
            );
        }
    },
    storage: diskStorage({
        destination: multerConfig.dest,
        filename,
    }),
};

And then in your test like this.

import { Readable } from 'stream';
import { multerConfig, multerOptions, filename } from './multer.config';

describe('Multer Configuration ', () => {
    const mockFile: Express.Multer.File = {
        filename: 'foo.jpg', // give it a name
        fieldname: '',
        originalname: '',
        encoding: 'utf8',
        mimetype: 'jpg', // give it a mime type
        size: 1,
        stream: new Readable(),
        destination: '',
        path: '',
        buffer: Buffer.from('', 'utf8'),
    };
    it('should define destination', () => {
        expect(multerConfig).toBeDefined();
        expect(multerConfig.dest).toBe(process.env.UPLOAD_LOCATION);
    });

    it('should define multer upload options', async () => {
        expect(multerOptions).toBeDefined();
        expect(multerOptions.fileFilter).toBeDefined();
        expect(multerOptions.storage).toBeTruthy();
        expect(multerOptions.limits).toBeTruthy();
    });

    // test the filter
    it('should filter the file based on mimetype', () => {
        const cb = jest.fn();
        multerOptions.fileFilter({}, mockFile, cb);
        // do something with the callback
    });

    // test the filename
    it('should create the proper filename', () => {
        const cb = jest.fn();
        filename({}, mockfile, cb)
        // do something with the callback
    });

    afterAll(() => {
        jest.resetAllMocks();
    });
});

I am not sure how to use jest or what you actually want to test. But like this, the line should get covered. But coverage doesn't mean much in that sense. The tests like this are not good. You should work out what precisely you want to test. This is just to show you wants roughly required.


来源: stackexchange

问:
Installing of solartherm
I am using this guideline to install solartherm: https://github.com/SolarTherm/SolarTherm/wiki/Running-SolarTherm-on-Windows-%28MSYS2%29
I reach the point where I need to install Dakota and I get this error:</p>
```<code>-bash: unzip: command not found
cp: cannot stat 'dakota-6.14.0.Windows.x64/*': No such file or director
</code>```

答:
The first error message there is telling you that unzip does not exist.  That command comes from a file (/usr/bin/unzip.exe) that is provided by an MSYS2 package named unzip.  So you need to install that package by running pacman -S unzip and then try again.

Note that the wiki page you linked to already told you to install the unzip package so I recommend that you go back to the beginning of the instructions and double check all of them to make sure you are on the right track.  Pay attention to any error messages you receive along the way.

ContentLicense: CC BY-SA 4.0

Title: Installing of solartherm

Body:
I am using this guideline to install solartherm: https://github.com/SolarTherm/SolarTherm/wiki/Running-SolarTherm-on-Windows-%28MSYS2%29
I reach the point where I need to install Dakota and I get this error:

-bash: unzip: command not found
cp: cannot stat 'dakota-6.14.0.Windows.x64/*': No such file or director


问:
STM32F0, ST-link v2, OpenOCD 0.9.0: open failed
I'm using Launchpad's gcc-arm-none-eabi 4.9-2015q2 to compile for an STM32F0, and now I'd like to debug using arm-none-eabi-gdb from that collection. My ST-Link v2 is part of a Nucleo F411RE board, with external hardware (the STM32F0 target) attached. Flashing the F0 works fine, so I conclude that my SWD connections are good.

Now I want to start OpenOCD, but it fails:

```<code>$ openocd -f interface/stlink-v2.cfg -f target/stm32f0x.cfg
Open On-Chip Debugger 0.9.0 (2015-07-26-16:02)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select <transport>'.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Error: open failed
in procedure 'init'
in procedure 'ocd_bouncer'
</code>```

What might be wrong here?

I also couldn't establish a connection using st-util, which reported timeouts and in the end always crashed with a segmentation fault.

答:
ID error related to OPENOCD failed:

fix-1:

Modify Stm32f1x.cfg file to set _CPUTAPID 0x2ba01477 from set _CPUTAPID 0x1ba01477

before: set _CPUTAPID 0x2ba01477

after   : set _CPUTAPID 0x1ba01477

fix-2(if not resolved):

modify stlink.cfg ,stlink-v2.cfg and stlink-v2-1.cfg file,add extra command like below

hla_vid_pid 0x0483 0x374B 0

Any Power reset issue during dubug run:

debug configuration -> debugger tab -> show generation option --> changed setting to software reset

ContentLicense: CC BY-SA 3.0

Body:
I'm using Launchpad's gcc-arm-none-eabi 4.9-2015q2 to compile for an STM32F0, and now I'd like to debug using arm-none-eabi-gdb from that collection. My ST-Link v2 is part of a Nucleo F411RE board, with external hardware (the STM32F0 target) attached. Flashing the F0 works fine, so I conclude that my SWD connections are good.

Now I want to start OpenOCD, but it fails:

$ openocd -f interface/stlink-v2.cfg -f target/stm32f0x.cfg
Open On-Chip Debugger 0.9.0 (2015-07-26-16:02)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select <transport>'.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Error: open failed
in procedure 'init'
in procedure 'ocd_bouncer'

What might be wrong here?

I also couldn't establish a connection using st-util, which reported timeouts and in the end always crashed with a segmentation fault.


问:
How to outer-join two CSV files, using shell script?
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"
```
<p><strong>file2.csv</strong></p>
<pre class="lang-none prettyprint-override"><code>label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"
</code>```

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"
```
<p>Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:</p>
```awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv
```

答:
Since your question was titled with "how to do ... in a shell script?" and not necessarily with awk, I'm going to recommend GoCSV, a command-line tool with several sub-commands for processing CSVs (delimited files).

It doesn't have a single command that can accomplish what you need, but you can compose a number of commands to get the correct result.

The core of this solution is the join command which can perform inner (default), left, right, and outer joins; you want an outer join to keep the non-overlapping elements:

gocsv join -c 'label' -outer file1.csv file2.csv > joined.csv
echo 'Joined'
gocsv view joined.csv
```
<pre class="lang-none prettyprint-override"><code>Joined
+-------+--------+-------+--------+
| label | Part-A | label | Part-B |
+-------+--------+-------+--------+
| ABC   | 2      |       |        |
+-------+--------+-------+--------+
| XYZ   | 3      | XYZ   | 4      |
+-------+--------+-------+--------+
| PQR   | 6      | PQR   | 6      |
+-------+--------+-------+--------+
|       |        | LMN   | 8      |
+-------+--------+-------+--------+
|       |        | EFG   | 1      |
+-------+--------+-------+--------+
</code>```

The data-part is correct, but it'll take some work to get the columns correct, and to get the NA values in there.

Here's a complete pipeline:

gocsv join -c 'label' -outer file1.csv file2.csv \
| gocsv rename -c 1 -names 'Label_A' \
| gocsv rename -c 3 -names 'Label_B' \
| gocsv add -name 'label' -t '{{ list .Label_A .Label_B | compact | first }}' \
| gocsv select -c 'label','Part-A','Part-B' \
| gocsv replace -c 'Part-A','Part-B' -regex '^$' -repl 'NA' \
| gocsv sort -c 'label' \
> final.csv

echo 'Final'
gocsv view final.csv
```
<p>which gets us the correct, final, file:</p>
<pre class="lang-none prettyprint-override"><code>Final pipeline
+-------+--------+--------+
| label | Part-A | Part-B |
+-------+--------+--------+
| ABC   | 2      | NA     |
+-------+--------+--------+
| EFG   | NA     | 1      |
+-------+--------+--------+
| LMN   | NA     | 8      |
+-------+--------+--------+
| PQR   | 6      | 6      |
+-------+--------+--------+
| XYZ   | 3      | 4      |
+-------+--------+--------+
</code>```

There's a lot going on in that pipeline, the high points are:

Merge the the two label fields

| gocsv rename -c 1 -names 'Label_A' \
| gocsv rename -c 3 -names 'Label_B' \
| gocsv add -name 'label' -t '{{ list .Label_A .Label_B | compact | first }}' \
```
<p><strong>Pare-down to just the 3 columns you want</strong></p>
<pre class="lang-none prettyprint-override"><code>| gocsv select -c 'label','Part-A','Part-B' \
</code>```

Add the NA values and sort by label

| gocsv replace -c 'Part-A','Part-B' -regex '^$' -repl 'NA' \
| gocsv sort -c 'label' \
```

I've made a step-by-step explanation at this Gist.

Body:
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"

file2.csv

label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"

Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:

awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv

Body:
Since your question was titled with "how to do ... in a shell script?" and not necessarily with awk, I'm going to recommend GoCSV, a command-line tool with several sub-commands for processing CSVs (delimited files).

It doesn't have a single command that can accomplish what you need, but you can compose a number of commands to get the correct result.

The core of this solution is the join command which can perform inner (default), left, right, and outer joins; you want an outer join to keep the non-overlapping elements:

gocsv join -c 'label' -outer file1.csv file2.csv > joined.csv
echo 'Joined'
gocsv view joined.csv

Joined
+-------+--------+-------+--------+
| label | Part-A | label | Part-B |
+-------+--------+-------+--------+
| ABC   | 2      |       |        |
+-------+--------+-------+--------+
| XYZ   | 3      | XYZ   | 4      |
+-------+--------+-------+--------+
| PQR   | 6      | PQR   | 6      |
+-------+--------+-------+--------+
|       |        | LMN   | 8      |
+-------+--------+-------+--------+
|       |        | EFG   | 1      |
+-------+--------+-------+--------+

The data-part is correct, but it'll take some work to get the columns correct, and to get the NA values in there.

Here's a complete pipeline:

gocsv join -c 'label' -outer file1.csv file2.csv \
| gocsv rename -c 1 -names 'Label_A' \
| gocsv rename -c 3 -names 'Label_B' \
| gocsv add -name 'label' -t '{{ list .Label_A .Label_B | compact | first }}' \
| gocsv select -c 'label','Part-A','Part-B' \
| gocsv replace -c 'Part-A','Part-B' -regex '^$' -repl 'NA' \
| gocsv sort -c 'label' \
> final.csv

echo 'Final'
gocsv view final.csv

which gets us the correct, final, file:

Final pipeline
+-------+--------+--------+
| label | Part-A | Part-B |
+-------+--------+--------+
| ABC   | 2      | NA     |
+-------+--------+--------+
| EFG   | NA     | 1      |
+-------+--------+--------+
| LMN   | NA     | 8      |
+-------+--------+--------+
| PQR   | 6      | 6      |
+-------+--------+--------+
| XYZ   | 3      | 4      |
+-------+--------+--------+

There's a lot going on in that pipeline, the high points are:

Merge the the two label fields

| gocsv rename -c 1 -names 'Label_A' \
| gocsv rename -c 3 -names 'Label_B' \
| gocsv add -name 'label' -t '{{ list .Label_A .Label_B | compact | first }}' \

Pare-down to just the 3 columns you want

| gocsv select -c 'label','Part-A','Part-B' \

Add the NA values and sort by label

| gocsv replace -c 'Part-A','Part-B' -regex '^$' -repl 'NA' \
| gocsv sort -c 'label' \

I've made a step-by-step explanation at this Gist.


答:
Added microbenchmarks results!

I love dplyr solution by r2evans!

But here's data.table solution:

```<code>library(data.table)

data <- data.frame(

  year = rep(2001, 24),
  qrt = rep(paste0("q", 1:4), each = 6),
  month = sample(c("jan", "jan", "feb", "march",
                   "apr", "june", "june", "july",
                   "aug", "sept", "oct", "jan",
                   "jan", "feb", "march",
                   "apr", "june", "june", "july",
                   "aug", "sept", "oct", "july", "aug"))

)

setDT(data)

data[, row_n := .I, by = .(qrt, month)]
</code>```

Output:

```<code>    year qrt month row_n
 1: 2001  q1   jan     1
 2: 2001  q1   apr     2
 3: 2001  q1  june     3
 4: 2001  q1  sept     4
 5: 2001  q1   jan     5
 6: 2001  q1   oct     6
         ...
20: 2001  q4  july    20
21: 2001  q4  june    21
22: 2001  q4  july    22
23: 2001  q4 march    23
24: 2001  q4   aug    24
</code>```

If you need to arrange any of your columns before further manipulations, you can use setorder function:

```<code>setorder(data, qrt, month)
data[, row_n := .I, by = .(qrt, month)]
</code>```

Then the output will be the following:

```<code>    year qrt month row_n
 1: 2001  q1   aug     1
 2: 2001  q1  july     2
 3: 2001  q1  july     3
 4: 2001  q1  june     4
 5: 2001  q1  sept     5
         ...
19: 2001  q4   aug    19
20: 2001  q4   jan    20
21: 2001  q4  june    21
22: 2001  q4  june    22
23: 2001  q4 march    23
24: 2001  q4   oct    24
</code>```

Benchmarks

Base R function wins! However, it looks not as nice as dplyr or data.table solution.

```<code>mbm <- microbenchmark::microbenchmark(

  base_R = {

    data$rank <- ave(seq_len(nrow(data)), data[, c("year","qrt")], FUN = seq_along)

  },

  r2evans = {

    library(dplyr)
    data %>%
      group_by(year, qrt) %>%
      mutate(rank = row_number()) %>%
      ungroup()

},

  rg4s = {

    library(data.table)
    setDT(data)
    data[, row_n := .I, by = .(qrt, month)]
},

times = 100)
</code>```

Title: How to get row number according to row partitioning in r

Body:
I am trying to give ranknumber according to qtr wise here is the inpt and output

INPUT:-

year   qtr  month   day          salry
2001    q1  jan     1           1000.00
2001    q1  jan     2           1500.00
2001    q1  feb     1           3000.00
2001    q1  feb     2           2100.00
2001    q1  march   1          1000.00
2001    q1  march   2          1200.00
2001    q2  april   1          1300.00
2001    q2  april   2          1900.00
2001    q2  may     1          1000.00
2001    q2  may     2          1800.00
2001    q2  june    1          1600.00
2001    q2  june    2          1900.00
2001    q3  july    1          2000.00
2001    q3  july    2          1800.00
2001    q3  august  1          2100.00
2001    q3  august  2          1500.00
2001    q3  sept    1          1700.00
2001    q3  sept    2          1400.00
2001    q4  oct     1          1300.00
2001    q4  oct     2          1200.00
2001    q4  nov     1          1100.00
2001    q4  nov     2          1700.00
2001    q4  dec     1          1000.00
2001    q4  dec     2          1700.00

OUTPUT:-

year    qtr     month  day  salry      rank
2001    q1      feb     1   3000.00     1
2001    q1      feb     2   2100.00     2
2001    q1      jan     2   1500.00     3
2001    q1      march   2   1200.00     4
2001    q1      jan     1   1000.00     5
2001    q1      march   1   1000.00     6
2001    q2      april   2   1900.00     1
2001    q2      june    2   1900.00     2
2001    q2      may     2   1800.00     3
2001    q2      june    1   1600.00     4
2001    q2      april   1   1300.00     5
2001    q2      may     1   1000.00     6
2001    q3      august  1   2100.00     1
2001    q3      july    1   2000.00     2
2001    q3      july    2   1800.00     3
2001    q3      sept    1   1700.00     4
2001    q3      august  2   1500.00     5
2001    q3      sept    2   1400.00     6
2001    q4      nov     2   1700.00     1
2001    q4      dec     2   1700.00     2
2001    q4      oct     1   1300.00     3
2001    q4      oct     2   1200.00     4
2001    q4      nov     1   1100.00     5
2001    q4      dec     1   1000.00     6

Body:
Added microbenchmarks results!

I love dplyr solution by r2evans!

But here's data.table solution:

library(data.table)

data <- data.frame(

  year = rep(2001, 24),
  qrt = rep(paste0("q", 1:4), each = 6),
  month = sample(c("jan", "jan", "feb", "march",
                   "apr", "june", "june", "july",
                   "aug", "sept", "oct", "jan",
                   "jan", "feb", "march",
                   "apr", "june", "june", "july",
                   "aug", "sept", "oct", "july", "aug"))

)

setDT(data)

data[, row_n := .I, by = .(qrt, month)]

Output:

    year qrt month row_n
 1: 2001  q1   jan     1
 2: 2001  q1   apr     2
 3: 2001  q1  june     3
 4: 2001  q1  sept     4
 5: 2001  q1   jan     5
 6: 2001  q1   oct     6
         ...
20: 2001  q4  july    20
21: 2001  q4  june    21
22: 2001  q4  july    22
23: 2001  q4 march    23
24: 2001  q4   aug    24

If you need to arrange any of your columns before further manipulations, you can use setorder function:

setorder(data, qrt, month)
data[, row_n := .I, by = .(qrt, month)]

Then the output will be the following:

    year qrt month row_n
 1: 2001  q1   aug     1
 2: 2001  q1  july     2
 3: 2001  q1  july     3
 4: 2001  q1  june     4
 5: 2001  q1  sept     5
         ...
19: 2001  q4   aug    19
20: 2001  q4   jan    20
21: 2001  q4  june    21
22: 2001  q4  june    22
23: 2001  q4 march    23
24: 2001  q4   oct    24

Benchmarks

Base R function wins! However, it looks not as nice as dplyr or data.table solution.

mbm <- microbenchmark::microbenchmark(

  base_R = {

    data$rank <- ave(seq_len(nrow(data)), data[, c("year","qrt")], FUN = seq_along)

  },

  r2evans = {

    library(dplyr)
    data %>%
      group_by(year, qrt) %>%
      mutate(rank = row_number()) %>%
      ungroup()

},

  rg4s = {

    library(data.table)
    setDT(data)
    data[, row_n := .I, by = .(qrt, month)]
},

times = 100)


问:
Git prompts for username and password for git push origin master command

Every time I was trying to push the new commits to the master branch through git push origin master command, git was prompting me with credentials. I wanted to convert the url from HTTPS to SSH through these commands:

```<code>$git remote add origin https://github.com/Ananya2001-an/FirstRepository
$git config --global credential.helper store
$git config --global credential.helper cache
</code>```

But now though it is not asking for the credentials, it's still not pushing the commits and instead showing me that Permission to access is denied and I can't read from my remote repository.
Kindly help me with this issue that I am facing right now.

答:
I wanted to convert the url from HTTPS to SSH  ...

OK:

... through these commands:

```<code>$ git remote add origin https://github.com/Ananya2001-an/FirstRepository
$ git config --global credential.helper store
$ git config --global credential.helper cache
</code>```

That won't work at all.  The URL for the remote origin is the last argument to git remote add origin or git remote set-url origin,  and for it to be an ssh remote, it must begin with ssh:// rather than https://.1

The credential.helper setting exists specifically for https:// URLs.  The git config --global command you're using will remove the old global setting and replace it with a new global setting, so the effect of the first such command is completely wiped away by the second one.

Wherever you got these commands, then, has done you a big disservice: they gave you three wrong commands instead of one right one.  On the other hand, if you meant to change the URL from ssh to https—the exact opposite of what you said—they gave you ... well, three wrong commands, still.

Your image (side note: use text, not images; see how to ask) shows that you already have an ssh URL.  We can tell because this:

```<code>git remote add origin https://github.com/Ananya2001-an/FirstRepository
</code>```

gives you an error:

```<code>error: remote origin already exists.
</code>```

Meanwhile, your git push says:

```<code>git@github.com: Permission denied (publickey).
</code>```

and this error occurs only for ssh URLs.

If you wish to change the URL of the existing remote origin, use:

```<code>git remote set-url origin ...
</code>```

(filling in the ... part with the desired URL).

To get your existing ssh URL to work, you should:

verify that you have the correct URL; and

debug your ssh connection to GitHub using ssh -Tv git@github.com.

You can do these steps in either order.

The credential.helper setting (store or cache) is used only for the https:// URLs; you can leave this set to cache if you like, regardless of what you do for the URL.  However, on Windows systems, you might want to use the third-party Git Credential Manager ("GCM").  (I don't use Windows myself and have never used GCM; I use ssh.)

Technically, there are other ways to spell ssh remote URLs for Git, but "what the URL starts with" is a good start.  URLs in general take the form https://host.name/path/to/resource or ftp://host.name/path/to/resource or mailto:user@host.name or ssh://host.name/path/to/resource.  Note the pattern here: we start with the type, like https or ftp or ssh or mailto, then we have a colon :, then we have //host.name for most cases.  Sometimes we have user@host.name, and you might use this with ssh:// URLs.

Body:
Every time I was trying to push the new commits to the master branch through git push origin master command, git was prompting me with credentials. I wanted to convert the url from HTTPS to SSH through these commands:

$git remote add origin https://github.com/Ananya2001-an/FirstRepository
$git config --global credential.helper store
$git config --global credential.helper cache

But now though it is not asking for the credentials, it's still not pushing the commits and instead showing me that Permission to access is denied and I can't read from my remote repository.
Kindly help me with this issue that I am facing right now.

Body:
I wanted to convert the url from HTTPS to SSH  ...

OK:

... through these commands:

$ git remote add origin https://github.com/Ananya2001-an/FirstRepository
$ git config --global credential.helper store
$ git config --global credential.helper cache

That won't work at all.  The URL for the remote origin is the last argument to git remote add origin or git remote set-url origin,  and for it to be an ssh remote, it must begin with ssh:// rather than https://.1

The credential.helper setting exists specifically for https:// URLs.  The git config --global command you're using will remove the old global setting and replace it with a new global setting, so the effect of the first such command is completely wiped away by the second one.

Wherever you got these commands, then, has done you a big disservice: they gave you three wrong commands instead of one right one.  On the other hand, if you meant to change the URL from ssh to https—the exact opposite of what you said—they gave you ... well, three wrong commands, still.

Your image (side note: use text, not images; see how to ask) shows that you already have an ssh URL.  We can tell because this:

git remote add origin https://github.com/Ananya2001-an/FirstRepository

gives you an error:

error: remote origin already exists.

Meanwhile, your git push says:

git@github.com: Permission denied (publickey).

and this error occurs only for ssh URLs.

If you wish to change the URL of the existing remote origin, use:

git remote set-url origin ...

(filling in the ... part with the desired URL).

To get your existing ssh URL to work, you should:

verify that you have the correct URL; and

debug your ssh connection to GitHub using ssh -Tv git@github.com.

You can do these steps in either order.

The credential.helper setting (store or cache) is used only for the https:// URLs; you can leave this set to cache if you like, regardless of what you do for the URL.  However, on Windows systems, you might want to use the third-party Git Credential Manager ("GCM").  (I don't use Windows myself and have never used GCM; I use ssh.)

Technically, there are other ways to spell ssh remote URLs for Git, but "what the URL starts with" is a good start.  URLs in general take the form https://host.name/path/to/resource or ftp://host.name/path/to/resource or mailto:user@host.name or ssh://host.name/path/to/resource.  Note the pattern here: we start with the type, like https or ftp or ssh or mailto, then we have a colon :, then we have //host.name for most cases.  Sometimes we have user@host.name, and you might use this with ssh:// URLs.


问:
How to properly mix sequential steps within parallel execution in an Airflow DAG?
I have an Airflow DAG I am writing where step_1 and step_2 run sequentially, and then in parallel kicked off three additional steps: X, Y, Z. Once those three steps completed, they run a final step, step_3. My DAG was written as:

step_1 >> step_2 >> [X, Y, Z] >> step_3

This worked just fine. However, I realized that X actually has two dependencies, we'll call them A and B, that need to run first. What I wanted to do was have those three - A, B, and X - run sequentially within one parallel lane, alongside Y and Z.

I wrote the DAG wiring as:

step_1 >> step_2 >> [A >> B >> X, Y, Z] >> step_3

This does not seem to have the expected results. I wanted A to be kicked off after step_2 ran, but it appears step_2 is still wired directly to X, with A and B just kind of... unlinked to either step_1 or step_2.

Does anyone know of a way to do this?

I know that I could pull A and B out of parallelism:

step_1 >> step_2 >> A >> B >> [X, Y, Z] >> step_3

But if possible I'd like to figure out a better approach. I have also read about subDAGs, but those seem overwrought for the simple tasks these steps are running.

答:
I'm not sure I fully understand your requested dependencies.
You mentioned that:

```<code>step_1 >> step_2 >> [A, Y, Z]
A >> B >> X >> step_3
Y >> step_3
Z >> step_3
</code>```

Gives you what you want which is:

But you also mentioned that you want A,B to be executed in parallel.
This can be done by using:

```<code>chain(step_1, step_2, [A, B])
[A, B] >> X >> step_3
step_2 >> [Y, Z] >> step_3
</code>```

Example:

Full code:

```<code>from airflow import DAG
from airflow.operators.dummy import DummyOperator
from datetime import datetime
from airflow.models.baseoperator import chain

with DAG(
    "stackoverflow_question",
    start_date=datetime(2021, 6, 7),
    schedule_interval=None,
) as dag:

    step_1 = DummyOperator(task_id='step_1')
    step_2 = DummyOperator(task_id='step_2')
    step_3 = DummyOperator(task_id='step_3')

    A = DummyOperator(task_id='A')
    B = DummyOperator(task_id='B')
    X = DummyOperator(task_id='X')
    Y = DummyOperator(task_id='Y')
    Z = DummyOperator(task_id='Z')

    chain(step_1, step_2, [A, B])
    [A, B] >> X >> step_3
    step_2 >> [Y, Z] >> step_3
</code>```

Body:
I'm not sure I fully understand your requested dependencies.
You mentioned that:

step_1 >> step_2 >> [A, Y, Z]
A >> B >> X >> step_3
Y >> step_3
Z >> step_3

Gives you what you want which is:

But you also mentioned that you want A,B to be executed in parallel.
This can be done by using:

chain(step_1, step_2, [A, B])
[A, B] >> X >> step_3
step_2 >> [Y, Z] >> step_3

Example:

Full code:

from airflow import DAG
from airflow.operators.dummy import DummyOperator
from datetime import datetime
from airflow.models.baseoperator import chain

with DAG(
    "stackoverflow_question",
    start_date=datetime(2021, 6, 7),
    schedule_interval=None,
) as dag:

    step_1 = DummyOperator(task_id='step_1')
    step_2 = DummyOperator(task_id='step_2')
    step_3 = DummyOperator(task_id='step_3')

    A = DummyOperator(task_id='A')
    B = DummyOperator(task_id='B')
    X = DummyOperator(task_id='X')
    Y = DummyOperator(task_id='Y')
    Z = DummyOperator(task_id='Z')

    chain(step_1, step_2, [A, B])
    [A, B] >> X >> step_3
    step_2 >> [Y, Z] >> step_3


问:
Run three regression models based on a label
Im trying to run three different regressions based on the data i was provided with. The idea is to understand how sweetness is linked to bitterness, but that for the three different of ciders we have: {dry, semidry, sweet}.

What i had in mind was to first make a scatter plot with all the x values, regardless of the kind of cider we have, and then make three different regression models, based on three different 'sliced' panda df, x_dry, x_semidry and x_sweet.

I get an error line 20, saying that im essentially multiplying an int with a numpy array. So to start solving my problem, i tried to list(myarray). However the error persists. Can someone point me in the right direction here?

the error i get:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-138-fa4209c61f04> in <module>
     20     return slope*i + intercept
     21
---> 22 mymodeldry = list(map(myfunc, x_dry))
     23 mymodelsemidry = list(map(myfunc, x_semidry))
     24 mymodelsweet = list(map(myfunc, x_sweet))

<ipython-input-138-fa4209c61f04> in myfunc(i)
     18
     19 def myfunc(i):
---> 20     return slope*i + intercept
     21
     22 mymodeldry = list(map(myfunc, x_dry))

TypeError: can't multiply sequence by non-int of type 'numpy.float64'
</code>```

My code

```<code># d) Represent the sweet flavor according to the bitter flavor and add the regression line, for each type of cider.
x = list(ciderdf["Sweetness"])

x_dry = ciderdf[ciderdf["Type"]=="Dry"]
x_dry = list(x_dry[["Sweetness"]])

x_semidry = ciderdf[ciderdf["Type"]=="Semi-dry"]
x_semidry = list(x_semidry[["Sweetness"]])

x_sweet = ciderdf[ciderdf["Type"]=="Sweet"]
x_sweet = list(x_sweet[["Sweetness"]])

y = list(ciderdf["Bitterness"])

slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(i):
    return slope*i + intercept

mymodeldry = list(map(myfunc, x_dry))
mymodelsemidry = list(map(myfunc, x_semidry))
mymodelsweet = list(map(myfunc, x_sweet))

plt.scatter(x,y)
plt.plot(x, mymodeldry, mymodelsemidry, mymodelsweet)
plt.show()
</code>```

答:
The error is in x_dry = list(x_dry[["Sweetness"]]). When you do this, you return x_dry = ['Sweetness'].

So in the map function you are essentially multiplying a float slope with a string, which raises the TypeError: can't multiply sequence by non-int of type 'numpy.float64'.

Do this instead: x_dry = x_dry["Sweetness"].tolist().

```<code>df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
x_dry = df["a"].tolist()
print(x_dry)

def myfunc(i):
    return 3.14*i + 2.56

mymodeldry = list(map(myfunc, x_dry))
print(mymodeldry)
</code>```

Output:

```<code>[1, 2, 3]
[5.7, 8.84, 11.98]
</code>```

Body:
Im trying to run three different regressions based on the data i was provided with. The idea is to understand how sweetness is linked to bitterness, but that for the three different of ciders we have: {dry, semidry, sweet}.

What i had in mind was to first make a scatter plot with all the x values, regardless of the kind of cider we have, and then make three different regression models, based on three different 'sliced' panda df, x_dry, x_semidry and x_sweet.

I get an error line 20, saying that im essentially multiplying an int with a numpy array. So to start solving my problem, i tried to list(myarray). However the error persists. Can someone point me in the right direction here?

the error i get:

TypeError                                 Traceback (most recent call last)
<ipython-input-138-fa4209c61f04> in <module>
     20     return slope*i + intercept
     21
---> 22 mymodeldry = list(map(myfunc, x_dry))
     23 mymodelsemidry = list(map(myfunc, x_semidry))
     24 mymodelsweet = list(map(myfunc, x_sweet))

<ipython-input-138-fa4209c61f04> in myfunc(i)
     18
     19 def myfunc(i):
---> 20     return slope*i + intercept
     21
     22 mymodeldry = list(map(myfunc, x_dry))

TypeError: can't multiply sequence by non-int of type 'numpy.float64'

My code

# d) Represent the sweet flavor according to the bitter flavor and add the regression line, for each type of cider.
x = list(ciderdf["Sweetness"])

x_dry = ciderdf[ciderdf["Type"]=="Dry"]
x_dry = list(x_dry[["Sweetness"]])

x_semidry = ciderdf[ciderdf["Type"]=="Semi-dry"]
x_semidry = list(x_semidry[["Sweetness"]])

x_sweet = ciderdf[ciderdf["Type"]=="Sweet"]
x_sweet = list(x_sweet[["Sweetness"]])

y = list(ciderdf["Bitterness"])

slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)
slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(i):
    return slope*i + intercept

mymodeldry = list(map(myfunc, x_dry))
mymodelsemidry = list(map(myfunc, x_semidry))
mymodelsweet = list(map(myfunc, x_sweet))

plt.scatter(x,y)
plt.plot(x, mymodeldry, mymodelsemidry, mymodelsweet)
plt.show()

Body:
The error is in x_dry = list(x_dry[["Sweetness"]]). When you do this, you return x_dry = ['Sweetness'].

So in the map function you are essentially multiplying a float slope with a string, which raises the TypeError: can't multiply sequence by non-int of type 'numpy.float64'.

Do this instead: x_dry = x_dry["Sweetness"].tolist().

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
x_dry = df["a"].tolist()
print(x_dry)

def myfunc(i):
    return 3.14*i + 2.56

mymodeldry = list(map(myfunc, x_dry))
print(mymodeldry)

Output:

[1, 2, 3]
[5.7, 8.84, 11.98]


问:
R: Delete ID if any of the rows within ID contain specific strings (or multiple partial strings) in longitudinal format?
I would like to delete ID in any row that contains certain strings (A or D) within ID.
Here is my data frame:

```<code>id   time   dx
1     1     C
1     2     B
2     1     A
2     2     C
2     3     B
3     1     D
</code>```

I would like the following:

```<code>id    time  dx
 1     1     C
 1     2     B
</code>```

Based on the earlier post regarding this (Delete rows containing specific strings in R), I tried d %>% filter(!grepl('A|D', dx)). However, it only deletes the rows that contain A or D, not the whole IDs. I'd appreciate any help!

##Update: All the below answers worked well for the above post. Thank you all! Note that for this post, I simplified my data frame, and later on, I realized that I actually needed R codes to delete the IDs with certain partial strings (e.g., A or B0) from the following data frame. I was able to achieve this by modifying the first r2evans' answer: d %>% group_by(id) %>% filter(!any(str_detect(dx, "A|B0"))) %>% ungroup(). I have included the note here in case someone needs it. I would appreciate any additional suggestions.

Data frame:

```<code>id time dx
1   1   C01
1   2   B1
2   1   A34
2   2   C01
2   3   B1
3   1   B01X
</code>```

The results I wanted:

```<code>id time dx
1   1   C01
1   2   B1
</code>```

答:
We may use subset in base R

```<code>subset(df1, !id %in% id[dx %in% c("A", "D")])
  id time dx
1  1    1  C
2  1    2  B
</code>```

Or a similar option with filter from dplyr

```<code>library(dplyr)
filter(df1, !id %in% id[dx %in% c("A", "D")])
  id time dx
1  1    1  C
2  1    2  B
</code>```

data

```<code>df1 <- structure(list(id = c(1L, 1L, 2L, 2L, 2L, 3L), time = c(1L, 2L,
1L, 2L, 3L, 1L), dx = c("C", "B", "A", "C", "B", "D")),
class = "data.frame", row.names = c(NA,
-6L))
</code>```

Body:
I would like to delete ID in any row that contains certain strings (A or D) within ID.
Here is my data frame:

id   time   dx
1     1     C
1     2     B
2     1     A
2     2     C
2     3     B
3     1     D

I would like the following:

id    time  dx
 1     1     C
 1     2     B

Based on the earlier post regarding this (Delete rows containing specific strings in R), I tried d %>% filter(!grepl('A|D', dx)). However, it only deletes the rows that contain A or D, not the whole IDs. I'd appreciate any help!

##Update: All the below answers worked well for the above post. Thank you all! Note that for this post, I simplified my data frame, and later on, I realized that I actually needed R codes to delete the IDs with certain partial strings (e.g., A or B0) from the following data frame. I was able to achieve this by modifying the first r2evans' answer: d %>% group_by(id) %>% filter(!any(str_detect(dx, "A|B0"))) %>% ungroup(). I have included the note here in case someone needs it. I would appreciate any additional suggestions.

Data frame:

id time dx
1   1   C01
1   2   B1
2   1   A34
2   2   C01
2   3   B1
3   1   B01X

The results I wanted:

id time dx
1   1   C01
1   2   B1

Body:
We may use subset in base R

subset(df1, !id %in% id[dx %in% c("A", "D")])
  id time dx
1  1    1  C
2  1    2  B

Or a similar option with filter from dplyr

library(dplyr)
filter(df1, !id %in% id[dx %in% c("A", "D")])
  id time dx
1  1    1  C
2  1    2  B

data

df1 <- structure(list(id = c(1L, 1L, 2L, 2L, 2L, 3L), time = c(1L, 2L,
1L, 2L, 3L, 1L), dx = c("C", "B", "A", "C", "B", "D")),
class = "data.frame", row.names = c(NA,
-6L))


问:
How to move a doom element to the mouse position in a second regardless of their positions on the screen
https://codepen.io/DraguLL/pen/gOXmJgo hello everyone, how to change the code so that the square moves to the mouse position in exactly one second, no matter where it is and where the mouse position is

    const myElement = document.getElementById('cir');
let x = 0;
let y = 0;

let xMouse = 0;
let yMouse = 0;

window.addEventListener('mousemove', e => {
  xMouse = e.clientX;
  yMouse = e.clientY;
});

setInterval(() => {
      if (xMouse === x && yMouse === y) {
          x = xMouse;
          y = yMouse;
      } else {
        if (xMouse > x) {
         x++;
        } else {
           x--;
        }
        if (yMouse > y) {
         y++;
        } else {
           y--;
        }
      }

      myElement.style.top = y + 'px';
      myElement.style.left = x + 'px';
  }, 1);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cir {
  position: fixed;
  background: red;
  top: 10px;
  left: 10px;
  width: 10px;
  height: 10px;
}</code>```

```

答:
You can use setTimeout and then use CSS transition to make that smooth effect of red dot moving.

const myElement = document.getElementById('cir');
let x = 0;
let y = 0;

let xMouse = 0;
let yMouse = 0;
let timer;
window.addEventListener('mousemove', e => {
  xMouse = e.clientX;
  yMouse = e.clientY;
  clearTimeout(timer);
  timer = setTimeout(mouseMove, 1000);
});

function mouseMove() {

          x = xMouse;
          y = yMouse;
      myElement.style.transition = "1s ease";
      myElement.style.top = y + 'px';
      myElement.style.left = x + 'px';

  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cir {
  position: fixed;
  background: red;
  top: 10px;
  left: 10px;
  width: 10px;
  height: 10px;
}</code>```

```

Body:
https://codepen.io/DraguLL/pen/gOXmJgo hello everyone, how to change the code so that the square moves to the mouse position in exactly one second, no matter where it is and where the mouse position is

    const myElement = document.getElementById('cir');
let x = 0;
let y = 0;

let xMouse = 0;
let yMouse = 0;

window.addEventListener('mousemove', e => {
  xMouse = e.clientX;
  yMouse = e.clientY;
});

setInterval(() => {
      if (xMouse === x && yMouse === y) {
          x = xMouse;
          y = yMouse;
      } else {
        if (xMouse > x) {
         x++;
        } else {
           x--;
        }
        if (yMouse > y) {
         y++;
        } else {
           y--;
        }
      }

      myElement.style.top = y + 'px';
      myElement.style.left = x + 'px';
  }, 1);

.cir {
  position: fixed;
  background: red;
  top: 10px;
  left: 10px;
  width: 10px;
  height: 10px;
}

Body:
You can use setTimeout and then use CSS transition to make that smooth effect of red dot moving.

const myElement = document.getElementById('cir');
let x = 0;
let y = 0;

let xMouse = 0;
let yMouse = 0;
let timer;
window.addEventListener('mousemove', e => {
  xMouse = e.clientX;
  yMouse = e.clientY;
  clearTimeout(timer);
  timer = setTimeout(mouseMove, 1000);
});

function mouseMove() {

          x = xMouse;
          y = yMouse;
      myElement.style.transition = "1s ease";
      myElement.style.top = y + 'px';
      myElement.style.left = x + 'px';

  }

.cir {
  position: fixed;
  background: red;
  top: 10px;
  left: 10px;
  width: 10px;
  height: 10px;
}

<div class ="cir" id = "cir"></div>


问:
Having problem with IncreaseItem function
My result is seeing item.acf.count as string and not as number. How can I convert this to number?

Here is the function below.

```<code>increaseItem = (id) => {
    const { cart } = this.state;
    cart.forEach(item => {
        if (item.id === id) {
            item.acf.count += 1

        }
    })
    this.setState({
        cart:cart
    })
}
</code>```

答:
My result is seeing item.acf.count as string and not as number. please
how can I convert is to number

You should ensure that the initial item.acf.count state is a number type so this count: item.acf.count + 1 operation works correctly and returns a number type. So long as your state updaters maintain the state invariant of item.acf.count being a number it should work as expected.

Additionally, the increaseItem handler is mutating the cart state and not creating new array/object references.

```<code>increaseItem = (id) => {
  const { cart } = this.state; // <-- cart is reference to cart state
  cart.forEach(item => {
    if (item.id === id) {
      item.acf.count += 1; // <-- mutation!
    }
  });
  this.setState({
    cart: cart // <-- cart state reference back into state
  })
}
</code>```

You should instead shallow copy the cart and then also shallow copy the cart item (any any other nested properties) you want to update. I also suggest using a functional state update so you are correctly updating from the previous state and not any state value closed over in increaseItem callback scope.

```<code>increaseItem = (id) => {
  this.setState(prevState => ({
    cart: prevState.cart.map(item => item.id === id
      ? {
        ...item,
        acf: {
          ...item.acf,
          count: item.acf.count + 1
        }
      }
      : item),
  }));
}
</code>```

Body:
My result is seeing item.acf.count as string and not as number. How can I convert this to number?

Here is the function below.

increaseItem = (id) => {
    const { cart } = this.state;
    cart.forEach(item => {
        if (item.id === id) {
            item.acf.count += 1

        }
    })
    this.setState({
        cart:cart
    })
}

Body:
My result is seeing item.acf.count as string and not as number. please
how can I convert is to number

You should ensure that the initial item.acf.count state is a number type so this count: item.acf.count + 1 operation works correctly and returns a number type. So long as your state updaters maintain the state invariant of item.acf.count being a number it should work as expected.

Additionally, the increaseItem handler is mutating the cart state and not creating new array/object references.

increaseItem = (id) => {
  const { cart } = this.state; // <-- cart is reference to cart state
  cart.forEach(item => {
    if (item.id === id) {
      item.acf.count += 1; // <-- mutation!
    }
  });
  this.setState({
    cart: cart // <-- cart state reference back into state
  })
}

You should instead shallow copy the cart and then also shallow copy the cart item (any any other nested properties) you want to update. I also suggest using a functional state update so you are correctly updating from the previous state and not any state value closed over in increaseItem callback scope.

increaseItem = (id) => {
  this.setState(prevState => ({
    cart: prevState.cart.map(item => item.id === id
      ? {
        ...item,
        acf: {
          ...item.acf,
          count: item.acf.count + 1
        }
      }
      : item),
  }));
}


问:
starting access with parameters doesn't work if an other database is opened
hopefully there is anybody who can solve my problem.
I would start an access db using a link (with /x macro or /cmd para) at the desktop. All is fine if access isn't running but if access is open (working at two database projects) neither /x macro nor /cmd para will work.

I've tried also /runtime with /x and /cmd but no change against the above.

autoexec macro will work fine

so many thanks in advance
ralph

答:
I just encountered this problem too, and I found that apart from including the path to msaccess.exe there is also another way to make it work.

That is to change the file extension of the access file you open with command line parameters from .accdb to .accdr (which is a way to simulate access runtime). If you do that then the command line parameters will be read properly even if there is already another access file open.

(You must of course change the extension both on the real file and the referring text inside the batch file.)


问:
Google DynDNS with FritzBox
I know thats not the kind of question that are commonly asked in here, but I don't know where to ask instead.

I want to setup DynDNS with my FritzBox 6600 Cable, but i always got an 500 - notfqdn (not full qualified domain name) Error. (I know FritzBox is not the best solution avaiable... but this is what i have to work with).

According to this guide i set up the DynDNS config in the FritzBox and used the username and password from the configured DynDNS and the update url domains.google.com/nic/update with the dyndns domain. The config in the FritzBox looks like the following:

```<code>Update-URL: domains.google.com/nic/update
Domainname (Domain-Name): something.my-domain.de
Benutzername (Username): my_username
Kennwort (Password): my_password
</code>```

I don't know what's the problem. Some testing with other configuration shows that a random user and password give the same 500 error.
Do anybody know how the request of the FritzBox looks like and how the parameters are parsed?

答:
You need to change the URL into following syntax</p>
```<code>https://username:password@domains.google.com/nic/update?hostname=subdomain.yourdomain.com
</code>```

Title: Google DynDNS with FritzBox

Body:
I know thats not the kind of question that are commonly asked in here, but I don't know where to ask instead.

I want to setup DynDNS with my FritzBox 6600 Cable, but i always got an 500 - notfqdn (not full qualified domain name) Error. (I know FritzBox is not the best solution avaiable... but this is what i have to work with).

According to this guide i set up the DynDNS config in the FritzBox and used the username and password from the configured DynDNS and the update url domains.google.com/nic/update with the dyndns domain. The config in the FritzBox looks like the following:

Update-URL: domains.google.com/nic/update
Domainname (Domain-Name): something.my-domain.de
Benutzername (Username): my_username
Kennwort (Password): my_password

I don't know what's the problem. Some testing with other configuration shows that a random user and password give the same 500 error.
Do anybody know how the request of the FritzBox looks like and how the parameters are parsed?

Body:
You need to change the URL into following syntax

https://username:password@domains.google.com/nic/update?hostname=subdomain.yourdomain.com


问:
Split data frame string column into multiple columns
I'd like to take data of the form

```<code>before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
  attr          type
1    1   foo_and_bar
2   30 foo_and_bar_2
3    4   foo_and_bar
4    6 foo_and_bar_2
</code>```

and use split() on the column "type" from above to get something like this:

```<code>  attr type_1 type_2
1    1    foo    bar
2   30    foo  bar_2
3    4    foo    bar
4    6    foo  bar_2
</code>```

I came up with something unbelievably complex involving some form of apply that worked, but I've since misplaced that. It seemed far too complicated to be the best way. I can use strsplit as below, but then unclear how to get that back into 2 columns in the data frame.

```<code>> strsplit(as.character(before$type),'_and_')
[[1]]
[1] "foo" "bar"

[[2]]
[1] "foo"   "bar_2"

[[3]]
[1] "foo" "bar"

[[4]]
[1] "foo"   "bar_2"
</code>```

Thanks for any pointers. I've not quite groked R lists just yet.

答:
Surprisingly, another tidyverse solution is still missing - you can also use tidyr::extract, with a regex.

library(tidyr)
before <- data.frame(attr = c(1, 30, 4, 6), type = c("foo_and_bar", "foo_and_bar_2"))

## regex - getting all characters except an underscore till the first underscore,
## inspired by Akrun https://stackoverflow.com/a/49752920/7941188

extract(before, col = type, into = paste0("type", 1:2), regex = "(^[^_]*)_(.*)")
#>   attr type1     type2
#> 1    1   foo   and_bar
#> 2   30   foo and_bar_2
#> 3    4   foo   and_bar
#> 4    6   foo and_bar_2
```

Body:
I'd like to take data of the form

before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
  attr          type
1    1   foo_and_bar
2   30 foo_and_bar_2
3    4   foo_and_bar
4    6 foo_and_bar_2

and use split() on the column "type" from above to get something like this:

  attr type_1 type_2
1    1    foo    bar
2   30    foo  bar_2
3    4    foo    bar
4    6    foo  bar_2

I came up with something unbelievably complex involving some form of apply that worked, but I've since misplaced that. It seemed far too complicated to be the best way. I can use strsplit as below, but then unclear how to get that back into 2 columns in the data frame.

> strsplit(as.character(before$type),'_and_')
[[1]]
[1] "foo" "bar"

[[2]]
[1] "foo"   "bar_2"

[[3]]
[1] "foo" "bar"

[[4]]
[1] "foo"   "bar_2"

Thanks for any pointers. I've not quite groked R lists just yet.


问:
Call a function in it self?
I saw an example online that looks like this:

```<code> def DecimalToBinary(num):

      if num >= 1:
         DecimalToBinary(num // 2)
      print(num % 2, end = '')

print(DecimalToBinary(12))
</code>```

I'll be happy if someone explain it to me.

答: This is called recursion. There is no problem as long as there is a break condition, in other words the calls to itself stop at some point. Otherwise you have an infinite loop.

Title: Call a function in it self?

Body:
I saw an example online that looks like this:

 def DecimalToBinary(num):

      if num >= 1:
         DecimalToBinary(num // 2)
      print(num % 2, end = '')

print(DecimalToBinary(12))

I'll be happy if someone explain it to me.


问:
npm run build with parcel throws an error
Installed node, ran npm init to create package.json, installed parcel. running the server with npx parcel index.html runs the server. Then I changed "scripts" to "start": "parcel index.html" in package.json, and run npm run start, it also runs the server without a problem. And then I added to "scripts" "build": "parcel build index.html" and run npm run build. But this does not work...
I get the error below...

```<code>> vjezba-17@1.0.0 build
> parcel build index.html

× Build failed.

@parcel/namer-default: Target "main" declares an output file path of "index.js" which does not match the compiled bundle type "html".

  C:\Users\ijevr\Desktop\JavaScript\vjezba 17\package.json:4:11
    3 |   "version": "1.0.0",
  > 4 |   "main": "index.js",
  >   |           ^^^^^^^^^^ Did you mean "index.html"?
    5 |   "scripts": {
    6 |     "start": "parcel index.html",

  ℹ Try changing the file extension of "main" in package.json.
</code>```

Of course, changing the main to index.html states that the file should be a .js file... index.js is what the npm init created in the package.json. In my folder, my main js file is named script.js, and it was named like this before I ran npm init. However changing the main to script.js also does not help, I get the same error as stated here...

I don't know what to do to npm build it...

答:
I didn't find a fix, but I found out that with Parcel 2 the build process changed.
Works now.

Script should look like this:

```<code>"start": "parcel",
"build": "parcel build"
</code>```

and main and source like this:

"main": "dist/index.js", //with dist being the path of the build

"source": "src/script.js", //and src the path of our project

Body:
Installed node, ran npm init to create package.json, installed parcel. running the server with npx parcel index.html runs the server. Then I changed "scripts" to "start": "parcel index.html" in package.json, and run npm run start, it also runs the server without a problem. And then I added to "scripts" "build": "parcel build index.html" and run npm run build. But this does not work...
I get the error below...

> vjezba-17@1.0.0 build
> parcel build index.html

× Build failed.

@parcel/namer-default: Target "main" declares an output file path of "index.js" which does not match the compiled bundle type "html".

  C:\Users\ijevr\Desktop\JavaScript\vjezba 17\package.json:4:11
    3 |   "version": "1.0.0",
  > 4 |   "main": "index.js",
  >   |           ^^^^^^^^^^ Did you mean "index.html"?
    5 |   "scripts": {
    6 |     "start": "parcel index.html",

  ℹ Try changing the file extension of "main" in package.json.

Of course, changing the main to index.html states that the file should be a .js file... index.js is what the npm init created in the package.json. In my folder, my main js file is named script.js, and it was named like this before I ran npm init. However changing the main to script.js also does not help, I get the same error as stated here...

I don't know what to do to npm build it...

Body:
I didn't find a fix, but I found out that with Parcel 2 the build process changed.
Works now.

Script should look like this:

"start": "parcel",
"build": "parcel build"

and main and source like this:

"main": "dist/index.js", //with dist being the path of the build

"source": "src/script.js", //and src the path of our project


问:
Custom Home button in Orbeon Form Builder Summary page
I have a task to change the behavior of 'Home' button in Form Builder Summary page.

When user click home button, it will navigate to the website that I want (example here: https://google.com)

Ref: https://doc.orbeon.com/configuration/properties/form-builder#action-buttons-on-the-form-builder-summary-page

I tried this code below but it didn't work. It still back to Form Runner Summary page.

```<code>*properties-local.xml

<property as="xs:string" name="oxf.fr.summary.process.home.orbeon.builder">
        navigate(uri = "https://google.com")
</property>
</code>```

答:
Currently that URL is not configurable. The only thing you can do is omit the Home button.

It would be nice to able to do that and I added RFE #5214.

Body:
I have a task to change the behavior of 'Home' button in Form Builder Summary page.

When user click home button, it will navigate to the website that I want (example here: https://google.com)

Ref: https://doc.orbeon.com/configuration/properties/form-builder#action-buttons-on-the-form-builder-summary-page

I tried this code below but it didn't work. It still back to Form Runner Summary page.

*properties-local.xml

<property as="xs:string" name="oxf.fr.summary.process.home.orbeon.builder">
        navigate(uri = "https://google.com")
</property>


问:
Add a NSXPCConnection as a key to a NSMutableDictionary
Edit:

I solved this problem by adding the process identifier that is exposed from the NSXPCConnection class as that is unique per connection as the key.

Problem:

I'm facing a problem where I need to store a key-value pair in a NSMutableDictionary (where an object of type NSXPCConnection is stored as the key). But I'm unable to do so as NSXPCConnection does not conform to NSCopying.

This is my code:

```<code>- (void)addDataToDict:(MyClass *)obj Connection:(NSXPCConnection *)connection
{
    assert(obj);

    LogInfo("Assert success");

    if([_dict objectForKey:connection])
    {
        LogError("Connection already in dictionary, abort");
        return;
    }
    else
        LogInfo("Adding connection to dict");

    NSObject<NSCopying> *key = connection;

    [_dict setObject:obj forKey:key];
}

</code>```

But this throws the following warning:

```<code>Incompatible pointer types initializing 'NSObject<NSCopying> *' with an expression of type 'NSXPCConnection *'
</code>```

and the following error during runtime:

```<code>-[NSXPCConnection copyWithZone:]: unrecognized selector sent to instance 0x127a4b0d0
</code>```

Any suggestions on how I can do this better are welcome!

答:
Although you've already solved this for your specific use-case by using a different key type, one alternative is to use an NSMapTable, which behaves very much like NSDictionary but allows you to have different semantics for keys and values.

Specifically, for this use-case, a +strongToStrongObjectsMapTable would be appropriate as it retains keys instead of copying them, allowing you to key by non-NSCopying objects like NSXPCConnection.

Body:
Edit:

I solved this problem by adding the process identifier that is exposed from the NSXPCConnection class as that is unique per connection as the key.

Problem:

I'm facing a problem where I need to store a key-value pair in a NSMutableDictionary (where an object of type NSXPCConnection is stored as the key). But I'm unable to do so as NSXPCConnection does not conform to NSCopying.

This is my code:

- (void)addDataToDict:(MyClass *)obj Connection:(NSXPCConnection *)connection
{
    assert(obj);

    LogInfo("Assert success");

    if([_dict objectForKey:connection])
    {
        LogError("Connection already in dictionary, abort");
        return;
    }
    else
        LogInfo("Adding connection to dict");

    NSObject<NSCopying> *key = connection;

    [_dict setObject:obj forKey:key];
}

But this throws the following warning:

Incompatible pointer types initializing 'NSObject<NSCopying> *' with an expression of type 'NSXPCConnection *'

and the following error during runtime:

-[NSXPCConnection copyWithZone:]: unrecognized selector sent to instance 0x127a4b0d0

Any suggestions on how I can do this better are welcome!


问:
ansible read parameter value from file
I have a file that looks similarly:

```<code># some comment
foo/variable1 = value1
bar/variable2 = value2
</code>```

etc..

I have been trying to come up with an ansible logic to look up one particular variable of interest from this file.
For example if I need to get value2 assigned to myvar in ansible.

tried lineinfile first something like this:

```<code>- name: taskname
  lineinfile:
    path: /path/to/file
    regexp: '^bar/variable2.*$'
    line: dummy
  register: myvar
  check_mode: yes
</code>```

didn't work. I also tried to escape the / character in the regexp pattern but that wasn't the problem. Then I tried lookup ini file something like:

```<code>vars:
  myvar: "{{ lookup('ini', 'bar/variable2 file=/path/to/file') }}"
</code>```

but the file doesn't have sections so this fails too.

I tried using regex_search too in different ways but I just can't seem to have it working. I'd appreciate if somebody can help me. I wish lookup ini file would have a version where the section is optional. There are some parameter files that follow very similar format except they don't have sections in them.

答:
There is no ini parser available IMHO. Neither the module ini_file nor the lookup ini plugin (see shell> ansible-doc -t lookup ini) can read the whole ini file.

But, you can parse it on your own. For example

    - set_fact:
        myvars: "{{ myvars|d({})|combine({_key: _val}) }}"
      loop: "{{ lookup('file', 'data.ini').split('\n') }}"
      when: item is match('(?!\s*#).*=.*')
      vars:
        _arr: "{{ item.split('=') }}"
        _key: "{{ _arr.0|trim|regex_replace('[^\\w]', '_') }}"
        _val: "{{ _arr.1|trim }}"
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>  myvars:
    bar_variable2: value2
    foo_variable1: value1
</code>```

Notes:

Potential sections (e.g. [defaults]) will be ignored

Names of the variables will be fixed. See Creating valid variable names.

If you don't want to change the names of the variables remove the regex_replace filter from the expression. The rules of valid Ansible variables' names do not apply to dictionary keys.

Title: ansible read parameter value from file

Body:
I have a file that looks similarly:

# some comment
foo/variable1 = value1
bar/variable2 = value2

etc..

I have been trying to come up with an ansible logic to look up one particular variable of interest from this file.
For example if I need to get value2 assigned to myvar in ansible.

tried lineinfile first something like this:

- name: taskname
  lineinfile:
    path: /path/to/file
    regexp: '^bar/variable2.*$'
    line: dummy
  register: myvar
  check_mode: yes

didn't work. I also tried to escape the / character in the regexp pattern but that wasn't the problem. Then I tried lookup ini file something like:

vars:
  myvar: "{{ lookup('ini', 'bar/variable2 file=/path/to/file') }}"

but the file doesn't have sections so this fails too.

I tried using regex_search too in different ways but I just can't seem to have it working. I'd appreciate if somebody can help me. I wish lookup ini file would have a version where the section is optional. There are some parameter files that follow very similar format except they don't have sections in them.

Body:
There is no ini parser available IMHO. Neither the module ini_file nor the lookup ini plugin (see shell> ansible-doc -t lookup ini) can read the whole ini file.

But, you can parse it on your own. For example

    - set_fact:
        myvars: "{{ myvars|d({})|combine({_key: _val}) }}"
      loop: "{{ lookup('file', 'data.ini').split('\n') }}"
      when: item is match('(?!\s*#).*=.*')
      vars:
        _arr: "{{ item.split('=') }}"
        _key: "{{ _arr.0|trim|regex_replace('[^\\w]', '_') }}"
        _val: "{{ _arr.1|trim }}"

gives

  myvars:
    bar_variable2: value2
    foo_variable1: value1

Notes:

Potential sections (e.g. [defaults]) will be ignored

Names of the variables will be fixed. See Creating valid variable names.

If you don't want to change the names of the variables remove the regex_replace filter from the expression. The rules of valid Ansible variables' names do not apply to dictionary keys.


问:
Find in Entity Framework multiple OR parameters
Suppose I have a product in my database with the description “white shirt size 50”.

The search parameter would be “shirt 50”. I have a more complex query in which I add several “OR”s and I can't get them to work.

I get the following error:

The LINQ expression

'DbSet()
.Where(p => p.IdTienda == __request_IdTienda_0)
.Join(
inner: DbSet(),
outerKeySelector: p => p.IdArticulo,
innerKeySelector: a => a.Id,
resultSelector: (p, a) => new TransparentIdentifier<Publicacion, Articulo>(
Outer = p,
Inner = a
))
.Where(ti => __arrayrequest_1
.Any(s => ti.Outer.Descripcion.Contains(s)) || ti.Outer.Codigo == __request_Filtro_SearchText_2 || ti.Inner.Codigo == __request_Filtro_SearchText_2 || ti.Inner.CodigoUniversal == __request_Filtro_SearchText_2 || ti.Inner.CodigoUniversalBulto == __request_Filtro_SearchText_2)'

could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

My code so far is the following:

```<code>var arrayrequest = request.Filtro.SearchText.Split().ToList();

var query = from publicacion in _dbContext.Publicaciones.Where(p => p.IdTienda == request.IdTienda)
            join articulo in _dbContext.Articulos
                 on publicacion.IdArticulo equals articulo.Id
            where
                arrayrequest.Any(s => publicacion.Descripcion.Contains(s))
                                 || publicacion.Codigo == request.Filtro.SearchText
                                 || articulo.Codigo == request.Filtro.SearchText
                                 || articulo.CodigoUniversal == request.Filtro.SearchText
                                 || articulo.CodigoUniversalBulto == request.Filtro.SearchText
            select publicacion;

var publicaciones = await query
                          .Include(p => p.Articulo)
                          .Include(p => p.TributoPublicacion)
                          .ToArrayAsync();
</code>```

The error occurs in the section

```<code>arrayrequest.Any(s => publicacion.Descripcion.Contains(s))`
</code>```

I use Entity Framework Core 5 - any help is welcome

答:
Don't want to repeat myself, but it is good to show how it can be solved.

EF do not supports complex predicates with local collections and here you need to build expression tree dynamically. This answer has GetItemsPredicate function which helps in building needed condition.

Then you can rewrite your query in this way:

var arrayrequest = request.Filtro.SearchText.Split().ToList();

var query = from publicacion in _dbContext.Publicaciones.Where(p => p.IdTienda == request.IdTienda)
            join articulo in _dbContext.Articulos
                 on publicacion.IdArticulo equals articulo.Id
            select publicacion;

var descriptionPredicate = query.GetItemsPredicate(arrayrequest, (publicacion, s) => publicacion.Descripcion.Contains(s));

Expression<Func<Publicacion, bool>> otherPredicate = publicacion => publicacion.Codigo == request.Filtro.SearchText
                                 || articulo.Codigo == request.Filtro.SearchText
                                 || articulo.CodigoUniversal == request.Filtro.SearchText
                                 || articulo.CodigoUniversalBulto == request.Filtro.SearchText;

query = query.Where(descriptionPredicate.CombineOr(otherPredicate)));

var publicaciones = await query
    .Include(p => p.Articulo)
    .Include(p => p.TributoPublicacion)
    .ToArrayAsync();
```

Body:
Suppose I have a product in my database with the description “white shirt size 50”.

The search parameter would be “shirt 50”. I have a more complex query in which I add several “OR”s and I can't get them to work.

I get the following error:

The LINQ expression

'DbSet()
.Where(p => p.IdTienda == __request_IdTienda_0)
.Join(
inner: DbSet(),
outerKeySelector: p => p.IdArticulo,
innerKeySelector: a => a.Id,
resultSelector: (p, a) => new TransparentIdentifier<Publicacion, Articulo>(
Outer = p,
Inner = a
))
.Where(ti => __arrayrequest_1
.Any(s => ti.Outer.Descripcion.Contains(s)) || ti.Outer.Codigo == __request_Filtro_SearchText_2 || ti.Inner.Codigo == __request_Filtro_SearchText_2 || ti.Inner.CodigoUniversal == __request_Filtro_SearchText_2 || ti.Inner.CodigoUniversalBulto == __request_Filtro_SearchText_2)'

could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

My code so far is the following:

var arrayrequest = request.Filtro.SearchText.Split().ToList();

var query = from publicacion in _dbContext.Publicaciones.Where(p => p.IdTienda == request.IdTienda)
            join articulo in _dbContext.Articulos
                 on publicacion.IdArticulo equals articulo.Id
            where
                arrayrequest.Any(s => publicacion.Descripcion.Contains(s))
                                 || publicacion.Codigo == request.Filtro.SearchText
                                 || articulo.Codigo == request.Filtro.SearchText
                                 || articulo.CodigoUniversal == request.Filtro.SearchText
                                 || articulo.CodigoUniversalBulto == request.Filtro.SearchText
            select publicacion;

var publicaciones = await query
                          .Include(p => p.Articulo)
                          .Include(p => p.TributoPublicacion)
                          .ToArrayAsync();

The error occurs in the section

arrayrequest.Any(s => publicacion.Descripcion.Contains(s))`

I use Entity Framework Core 5 - any help is welcome


问:
Vue/Webpack/Typescript - How to use jQuery Plugin
I want to use the jQuery Plugin chosen in my vue.js/Webpack with TypeScript application.

I read that it it's best to wrap the plugin in a custom Vue component.

I installed the NPM packages:

```<code>npm install jquery --save
npm install @types/jquery --save
npm install chosen-js --save
npm install @types/chosen-js --save
</code>```

My component:

```<code><template>
    <select>
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
</template>

<script lang="ts">
    import { Component, Prop, Vue } from "vue-property-decorator";
    import $ from 'jquery';
    import 'chosen-js';

    @Component
    export default class ChosenSelect extends Vue{
        @Prop()options!:string;
        @Prop()value!:string;

        mounted() {
            let vm = this;
            let el = $(vm.$el);
            console.log(el);
        }
    }
</script>
</code>```

Without import 'chosen-js' jQuery is working - when I'm using the component in another component I get a console output.

With import 'chosen-js' I only get Uncaught ReferenceError: jQuery is not defined from the chosen library.

What is the right way to import both - jQuery and chosen-js and use it in a vue Typescript component.

答:
Put this in the main.ts file and it will be available inside the components.</p>
```<code>declare global {
    interface Window { $: any; }
}
window.$ = require('jquery')
</code>```

Body:
I want to use the jQuery Plugin chosen in my vue.js/Webpack with TypeScript application.

I read that it it's best to wrap the plugin in a custom Vue component.

I installed the NPM packages:

npm install jquery --save
npm install @types/jquery --save
npm install chosen-js --save
npm install @types/chosen-js --save

My component:

<template>
    <select>
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
</template>

Without import 'chosen-js' jQuery is working - when I'm using the component in another component I get a console output.

With import 'chosen-js' I only get Uncaught ReferenceError: jQuery is not defined from the chosen library.

What is the right way to import both - jQuery and chosen-js and use it in a vue Typescript component.

Body:
Put this in the main.ts file and it will be available inside the components.

declare global {
    interface Window { $: any; }
}
window.$ = require('jquery')


问:
Break line when string reaches X characters
I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.

function getName(name) {
      let newName = name
      for (let i = 0; i < name.length; i += 1) {
        if (i % 35 === 0) {
          newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
        }
      }
      return newName
}

console.log(getName("Please note that popular names below"))```
</div>
</div>
</p>
<p>Eg output:</p>
```Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow
```

What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.

答:
If you want to break a string to certain length without cutting off any word, following code can help you:</p>
```<code>const name = "YOUR_STRING";
const maxLen = 35; // you can play with this number to get desired result.

let result = name.substr(0, maxLen);
result = result.substr(0, Math.min(result.length, result.lastIndexOf(" ")));
</code>```

Body:
I created this function below to calculate when a string (name) reaches more than 35 characters then it break a line.

function getName(name) {
      let newName = name
      for (let i = 0; i < name.length; i += 1) {
        if (i % 35 === 0) {
          newName = `${newName.substr(0, i)}\n${newName.substr(i)}`
        }
      }
      return newName
}

console.log(getName("Please note that popular names below"))

Eg output:

Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow

What I want is to instead of break a line of these two last characters "ow", I put "below" in the next line.

Body:
If you want to break a string to certain length without cutting off any word, following code can help you:

const name = "YOUR_STRING";
const maxLen = 35; // you can play with this number to get desired result.

let result = name.substr(0, maxLen);
result = result.substr(0, Math.min(result.length, result.lastIndexOf(" ")));


问:
Adapter Android Studio Button
I have an adapter with a button inside and I don't really know ho to do something when I presse the button.
It's an order app and in the the basket I have a delete button to delete a dish.
Do you have a solution ?</p>

答:
Maybe you can find the solution here:
https://stackoverflow.com/a/37846430/

Instead of implementing the View.OnClickListener in the ExampleClickViewHolder, you should be fine with simply setting an onClickListener to your button and call the mOnEntryClickListener.onEntryClick in it.

For a more reliable answer, please add some details on your current code.

Title: Adapter Android Studio Button


问:
Word with special characters match via preg_match in php
Suppose I have a string like:

```<code>$str ="Model number is FM223-56/89.";
</code>```

And I want match the model number only in this string via preg_match.
I am doing it like:

```<code>$model ="FM223-56/89.";

$pattern = '/\b'.$model.'\b/';
echo preg_match($pattern, $str);
</code>```

But no luck, I want to search word that can have .-,'/" in it, Is it possible to search via preg_match?

There is no fixed pattern.

答:
Two issues:

Believe it or not . is not a word boundary \b

You are using / as a delimiter but there is a / in your pattern

So either use a different delimiter:

```<code>$pattern = "~\b".$model."~";
</code>```

Or better, escape the variable and specify your delimiter:

```<code>$pattern = '/'.preg_quote($model, '/').'/';
</code>```

Body:
Suppose I have a string like:

$str ="Model number is FM223-56/89.";

And I want match the model number only in this string via preg_match.
I am doing it like:

$model ="FM223-56/89.";

$pattern = '/\b'.$model.'\b/';
echo preg_match($pattern, $str);

But no luck, I want to search word that can have .-,'/" in it, Is it possible to search via preg_match?

There is no fixed pattern.

Body:
Two issues:

Believe it or not . is not a word boundary \b

You are using / as a delimiter but there is a / in your pattern

So either use a different delimiter:

$pattern = "~\b".$model."~";

Or better, escape the variable and specify your delimiter:

$pattern = '/'.preg_quote($model, '/').'/';


问:
webpack : Uncaught ReferenceError: require is not defined
This error comes when in webpack target = node but i have done target=web(default)

also i am not loading reactjs externally

this error comes on loading app in browser

what i am doing wrong ?

In Console

File

webpack.config.js

```<code>const HtmlWebpackPlugin = require('html-webpack-plugin');
const nodeExternals = require('webpack-node-externals');

const config = {
    target: 'web',
    externals: [nodeExternals()],
    entry: './src/index.js',
    output: {
        filename: '[name].bundle.js',
        path: __dirname + '/build'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },
            {
                test: /\.(png|svg|jpe?g|gif)$/,
                use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[path][name].[ext]'
                        }
                    }
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: ['file-loader']
            }
        ]
    },
    devtool: 'inline-source-map',
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Instarem.com'
        })
    ]
};

module.exports = config;
</code>```

.babelrc using

babel-preset-env

```<code>{
    "presets": [
        "react",
        [
            "env",
            {
                "targets": {
                    "browsers": ["last 2 versions"]
                },
                "debug": true,
                "modules": "commonjs"
            }
        ]
    ],
    "plugins": [
        "transform-object-rest-spread",
        "transform-class-properties"
    ]
}
</code>```

thanks :)

I found Clue

In facebook's create react app generator bundle it shows

```<code>module.exports = __webpack_require__(/*! ./lib/React */ "./node_modules/react/lib/React.js");
</code>```

but in my case it shows only

```<code>module.exports = require("react");
</code>```

答:
I encountered this problem a few minutes ago. This usually happens when you mix up the target property for the bundle in webpack.config file. E.g. if you are creating a bundle for React the target should be target: 'web' and should not include anything relating to node like 'async-node' or 'node'.

```<code>const reactConfig = {
   name: 'React Bundle',
   target: 'web',
   ...
}
</code>```

Body:
This error comes when in webpack target = node but i have done target=web(default)

also i am not loading reactjs externally

this error comes on loading app in browser

what i am doing wrong ?

In Console

File

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const nodeExternals = require('webpack-node-externals');

const config = {
    target: 'web',
    externals: [nodeExternals()],
    entry: './src/index.js',
    output: {
        filename: '[name].bundle.js',
        path: __dirname + '/build'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },
            {
                test: /\.(png|svg|jpe?g|gif)$/,
                use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[path][name].[ext]'
                        }
                    }
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: ['file-loader']
            }
        ]
    },
    devtool: 'inline-source-map',
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Instarem.com'
        })
    ]
};

module.exports = config;

.babelrc using

babel-preset-env

{
    "presets": [
        "react",
        [
            "env",
            {
                "targets": {
                    "browsers": ["last 2 versions"]
                },
                "debug": true,
                "modules": "commonjs"
            }
        ]
    ],
    "plugins": [
        "transform-object-rest-spread",
        "transform-class-properties"
    ]
}

thanks :)

I found Clue

In facebook's create react app generator bundle it shows

module.exports = __webpack_require__(/*! ./lib/React */ "./node_modules/react/lib/React.js");

but in my case it shows only

module.exports = require("react");

Body:
I encountered this problem a few minutes ago. This usually happens when you mix up the target property for the bundle in webpack.config file. E.g. if you are creating a bundle for React the target should be target: 'web' and should not include anything relating to node like 'async-node' or 'node'.

const reactConfig = {
   name: 'React Bundle',
   target: 'web',
   ...
}


问:
Best database for inserting records
What would be the best DB for Inserting records at a very high rate.

The DB will have only one table and the Application is very simple. Insert a row into the DB and commit it but the insertion rate will be very high.

Targetting about 5000 Row Insert per second.

Any of the very expensive DB's like Oracle\SQLServer are out of option.

Also what are the technologies for taking a DB Backup and will it be possible to create one DB from the older backed up DB's ?

I can't use InMemory capabilities of any DB's as I can't afford a crash of the Application. I need to commit the row as soon as I recieve it.

答: The performance you want is really not that hard to achieve, even on a "traditional" relational DBMS. If you look at the results for unclustered TPC-C (TPC-C is the de-facto standard benchmark for transaction processing) many systems can provide 10 times your requirements in an unclustered system. If you are going for cheap and solid you might want to check out DB2 Express-C. It is limited to two cores and two gigabytes of memory but that should be more than enough to satisfy your needs.</p>

ContentLicense: CC BY-SA 2.5

Title: Best database for inserting records


问:
Nice looking tables in both base R and RStudio notebooks
I want my function to print nice-looking tables, whether it's called from base R or from an RStudio Notebook (.Rmd file). The function should figure out where it's being called from, and adjust the table accordingly. I want the function to be easy to use, and don't want the user to have to specify anything about where the function is being called from.

I can achieve some of this with huxtable, but the user still has to modify the code a little. (I think this would work similarly with kable.)

Here is the function definition:

library(huxtable)

func = function() {
    table = hux(head(iris))
    # Color of table border: white on screen / base R, black in HTML
    color = if(isTRUE(all.equal(getOption('huxtable.print') , huxtable::print_screen))) "white" else "black"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

```
<p>In base R, I can just call the function:</p>
<pre class="lang-r prettyprint-override"><code># Base R
func()
</code>```

But in an RStudio Notebook, I need to make a couple of changes when calling the function, namely:

{r, results="asis"}

options("huxtable.print" = huxtable::print_html)

The call looks like this:

    ```{r, results="asis"}
    # RStudio
    options("huxtable.print" = huxtable::print_html)
    func()
    ```

```

Is there a better solution where the user can call the function the same way in base R and RStudio?

答:
Thanks to @dash2 for giving me the idea. Here is the function that does what I want:

library(huxtable)

func = function() {
    table = hux(head(iris))
    if (guess_knitr_output_format() == "") { # base R
        table = set_all_borders(table, brdr(color = "white"))
        print(table, colnames = FALSE)
    } else { # knitr / RStudio
        table = set_all_borders(table, brdr(color = "black"))
        huxtable:::knit_print.huxtable(table, colnames = FALSE)
    }
}

func()
```

Body:
I want my function to print nice-looking tables, whether it's called from base R or from an RStudio Notebook (.Rmd file). The function should figure out where it's being called from, and adjust the table accordingly. I want the function to be easy to use, and don't want the user to have to specify anything about where the function is being called from.

I can achieve some of this with huxtable, but the user still has to modify the code a little. (I think this would work similarly with kable.)

Here is the function definition:

library(huxtable)

func = function() {
    table = hux(head(iris))
    # Color of table border: white on screen / base R, black in HTML
    color = if(isTRUE(all.equal(getOption('huxtable.print') , huxtable::print_screen))) "white" else "black"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

In base R, I can just call the function:

# Base R
func()

But in an RStudio Notebook, I need to make a couple of changes when calling the function, namely:

{r, results="asis"}

options("huxtable.print" = huxtable::print_html)

The call looks like this:

    ```{r, results="asis"}
    # RStudio
    options("huxtable.print" = huxtable::print_html)
    func()
    ```

Is there a better solution where the user can call the function the same way in base R and RStudio?