问:
'Operand should contain 1 column(s)' error when inserting two tables into one in MySQL
I want to insert two different tables into one as per the below illustration:

I've tried several ways like:

```<code>INSERT INTO com_short
    (category_id, media_folder_id, gallery_folder_id, status, important,
    bgPositioning, published_at, published_by, created_at, modified_at,title,
    slug, body, featured_image_file_id)

SELECT (SELECT com_post.id, category_id, media_folder_id, gallery_folder_id,
               status, important, bgPositioning, published_at, published_by,
               com_post.created_at, com_post.modified_at
        FROM com_post
            INNER JOIN com_post_translation ON com_post.id = com_post_translation.post_id
        WHERE com_post_translation.post_id = com_post.id
        ),

        (SELECT title, slug, body,featured_image_file_id
        FROM com_post_translation
        WHERE com_post.id = com_post_translation.post_id
        );
</code>```

But it shows an error as follows:

What am I missing?

答:
Reason of the error: you can not select more than one column in the subquery:

```<code>SELECT (SELECT com_post.id, category_id, media_folder_id, gallery_folder_id,
               status, important, bgPositioning, published_at, published_by,
               com_post.created_at, com_post.modified_at
        FROM com_post
            INNER JOIN com_post_translation ON com_post.id = com_post_translation.post_id
        WHERE com_post_translation.post_id = com_post.id
        ),

        (SELECT title, slug, body,featured_image_file_id
        FROM com_post_translation
        WHERE com_post.id = com_post_translation.post_id
        );
</code>```

Simple explanation :

This will produce error:

```<code>select (select '1', '2');
</code>```

This will not:

```<code>select (select '1');
</code>```

Check the demo

What would be the way to do it withot errors:

```<code>INSERT INTO com_short (category_id --1
                       , media_folder_id --2
                       , gallery_folder_id --3
                       , status --4
                       , important --5
                       , bgPositioning --6
                       , published_at --7
                       , published_by --8
                       , created_at --9
                       , modified_at --10
                       , title --11
                       , slug --12
                       , body --13
                       , featured_image_file_id) --14
SELECT cpt.category_id --1
       , cpt.media_folder_id --2
       , cpt.gallery_folder_id --3
       , cpt.status --4
       , cpt.important --5
       , cpt.bgPositioning --6
       , cpt.published_at --7
       , cpt.published_by --8
       , com_post.created_at --9
       , com_post.modified_at --10
       , cpt.title --11
       , cpt.slug --12
       , cpt.body --13
       , cpt.featured_image_file_id --14
FROM com_post
INNER JOIN com_post_translation cpt ON com_post.id = cpt .post_id
</code>```

Note: This is just an example, I can not know for sure from your question what do you want to do....

Additional info:

cpt is alias for the table com_post_translation (It makes your code "lighter" and easyer to read).

When you join two tables with ON keyword there is no need to repeat that condition in the where clause.

Body:
I want to insert two different tables into one as per the below illustration:

I've tried several ways like:

INSERT INTO com_short
    (category_id, media_folder_id, gallery_folder_id, status, important,
    bgPositioning, published_at, published_by, created_at, modified_at,title,
    slug, body, featured_image_file_id)

SELECT (SELECT com_post.id, category_id, media_folder_id, gallery_folder_id,
               status, important, bgPositioning, published_at, published_by,
               com_post.created_at, com_post.modified_at
        FROM com_post
            INNER JOIN com_post_translation ON com_post.id = com_post_translation.post_id
        WHERE com_post_translation.post_id = com_post.id
        ),

        (SELECT title, slug, body,featured_image_file_id
        FROM com_post_translation
        WHERE com_post.id = com_post_translation.post_id
        );

But it shows an error as follows:

What am I missing?

Body:
Reason of the error: you can not select more than one column in the subquery:

SELECT (SELECT com_post.id, category_id, media_folder_id, gallery_folder_id,
               status, important, bgPositioning, published_at, published_by,
               com_post.created_at, com_post.modified_at
        FROM com_post
            INNER JOIN com_post_translation ON com_post.id = com_post_translation.post_id
        WHERE com_post_translation.post_id = com_post.id
        ),

        (SELECT title, slug, body,featured_image_file_id
        FROM com_post_translation
        WHERE com_post.id = com_post_translation.post_id
        );

Simple explanation :

This will produce error:

select (select '1', '2');

This will not:

select (select '1');

Check the demo

What would be the way to do it withot errors:

INSERT INTO com_short (category_id --1
                       , media_folder_id --2
                       , gallery_folder_id --3
                       , status --4
                       , important --5
                       , bgPositioning --6
                       , published_at --7
                       , published_by --8
                       , created_at --9
                       , modified_at --10
                       , title --11
                       , slug --12
                       , body --13
                       , featured_image_file_id) --14
SELECT cpt.category_id --1
       , cpt.media_folder_id --2
       , cpt.gallery_folder_id --3
       , cpt.status --4
       , cpt.important --5
       , cpt.bgPositioning --6
       , cpt.published_at --7
       , cpt.published_by --8
       , com_post.created_at --9
       , com_post.modified_at --10
       , cpt.title --11
       , cpt.slug --12
       , cpt.body --13
       , cpt.featured_image_file_id --14
FROM com_post
INNER JOIN com_post_translation cpt ON com_post.id = cpt .post_id

Note: This is just an example, I can not know for sure from your question what do you want to do....

Additional info:

cpt is alias for the table com_post_translation (It makes your code "lighter" and easyer to read).

When you join two tables with ON keyword there is no need to repeat that condition in the where clause.


来源: stackexchange

问:
Looking for a _working_ simple example of Electron v8 and TypeScript
Forgive the simplicity of my plaintiff question, I'm close to my wits end.

I am looking for a working simple example of Electron v8 and TypeScript. It needn't include WebPack, Babel, React or anything else. Nothing I have found seems to work with Electron v8.

Update

My prior statement remind me of Macbeth's line it is a tale
Told by an idiot, full of sound and fury, Signifying nothing, so let's state the problem in detail this time.

The stock Electron & Typescript example does not demonstrate the following:

Using import for Node modules within the renderer process

Using import for my own application modules within the renderer process.

Attempting to do so got no errors from tsc but provoked a runtime error

```<code>ReferenceError: exports is not defined[Learn More]
exports.__esModule = true
</code>```

Using require instead of import, especially for classes like EventEmitter upset VS Code which warned

```<code>'EventEmitter' refers to a value, but is being used as a type here.ts(2749)
</code>```

... so that's a backward step.

Setting target in tsconfig.json to ES2018 means I can use ES6 modules and the import syntax for my own modules, though it needs a .js suffix to work.

```<code>import {blah} from './MyModule.js'` // Shouldn't need that suffix!
</code>```

VS Code gives the impression that I can import Node modules, but it still fails at runtime.

```<code>Uncaught TypeError: Failed to resolve module specifier "events". Relative references must start with either "/", "./", or "../".
</code>```

答:
You'll require four things: package.json, tsconfig.json, index.ts and index.html.

I've based my example on a Electron tutorial and a blog post on working with Electron and TypeScript.

The package.json needs to bring in Electron and TypeScript dependencies, trigger the TypeScript build and start Electron.

```<code>{
  "name": "electron-ts",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "prestart": "tsc",
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "8.0.1",
    "typescript": "3.7.5"
  }
}
</code>```

The prestart script compiles the TypeScript and start runs Electron using the project as the application directory. I don't know the minimum version of TypeScript needed but it's 3 something.

The tsconfig.json needs to set some compiler options and identify what to build when running tsc.

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": ["node_modules"]
}

</code>```

This will compile any TypeScript files it finds outside of node_modules and generate the JavaScript alongside them.

The index.ts needs to create a browser window and load the landing page.

```<code>import { app, BrowserWindow } from 'electron';

function createWindow () {
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });
  win.loadFile('index.html');
}

app.allowRendererProcessReuse = true;
app.whenReady().then(createWindow);
</code>```

This is some boilerplate code for starting Electron, all the types are infered.

Finaly the index.html needs to display something you can recognise.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>
</code>```

This will display the versions of node, Chrome and Electron.

With these files in the same directory, running npm start should compile the TypeScript and start the Electron application.

ContentLicense: CC BY-SA 4.0

Body:
Forgive the simplicity of my plaintiff question, I'm close to my wits end.

I am looking for a working simple example of Electron v8 and TypeScript. It needn't include WebPack, Babel, React or anything else. Nothing I have found seems to work with Electron v8.

Update

My prior statement remind me of Macbeth's line it is a tale
Told by an idiot, full of sound and fury, Signifying nothing, so let's state the problem in detail this time.

The stock Electron & Typescript example does not demonstrate the following:

Using import for Node modules within the renderer process

Using import for my own application modules within the renderer process.

Attempting to do so got no errors from tsc but provoked a runtime error

ReferenceError: exports is not defined[Learn More]
exports.__esModule = true

Using require instead of import, especially for classes like EventEmitter upset VS Code which warned

'EventEmitter' refers to a value, but is being used as a type here.ts(2749)

... so that's a backward step.

Setting target in tsconfig.json to ES2018 means I can use ES6 modules and the import syntax for my own modules, though it needs a .js suffix to work.

import {blah} from './MyModule.js'` // Shouldn't need that suffix!

VS Code gives the impression that I can import Node modules, but it still fails at runtime.

Uncaught TypeError: Failed to resolve module specifier "events". Relative references must start with either "/", "./", or "../".

Body:
You'll require four things: package.json, tsconfig.json, index.ts and index.html.

I've based my example on a Electron tutorial and a blog post on working with Electron and TypeScript.

The package.json needs to bring in Electron and TypeScript dependencies, trigger the TypeScript build and start Electron.

{
  "name": "electron-ts",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "prestart": "tsc",
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "8.0.1",
    "typescript": "3.7.5"
  }
}

The prestart script compiles the TypeScript and start runs Electron using the project as the application directory. I don't know the minimum version of TypeScript needed but it's 3 something.

The tsconfig.json needs to set some compiler options and identify what to build when running tsc.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": ["node_modules"]
}

This will compile any TypeScript files it finds outside of node_modules and generate the JavaScript alongside them.

The index.ts needs to create a browser window and load the landing page.

import { app, BrowserWindow } from 'electron';

function createWindow () {
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });
  win.loadFile('index.html');
}

app.allowRendererProcessReuse = true;
app.whenReady().then(createWindow);

This is some boilerplate code for starting Electron, all the types are infered.

Finaly the index.html needs to display something you can recognise.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

This will display the versions of node, Chrome and Electron.

With these files in the same directory, running npm start should compile the TypeScript and start the Electron application.


问:
How to access generated output file in Docker
I have dockerized my python application. This application connects with Oracle database, pull out 10 rows from a table and then generate excel. I was able to build my image successfully with all dependent libraries and it's also executing fine. Now, I am not sure how to get generated excel file (batchtable.xlsx) in docker.
I am new to docker and would need your suggestion. I have checked output without storing records into excel and it's coming fine on console, so there is no code issue.

Dockerfile

```<code>FROM python:3.7.4-slim-buster

RUN apt-get update && apt-get install -y libaio1 wget unzip

WORKDIR /opt/oracle
COPY File.py /opt/oracle

RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \
    unzip instantclient-basiclite-linuxx64.zip && rm -f instantclient-basiclite-linuxx64.zip && \
    cd /opt/oracle/instantclient* && rm -f *jdbc* *occi* *mysql* *README *jar uidrvci genezi adrci && \
    echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf && ldconfig

RUN python -m pip install --upgrade pip
RUN python -m pip install cx_Oracle
RUN python -m pip install pandas
RUN python -m pip install openpyxl

CMD [ "python", "/opt/oracle/File.py" ]
</code>```

File.py

```<code>import cx_Oracle
import pandas as pd

#creating database connection
dsn_tns = cx_Oracle.makedsn('dev-tr01.com', '1222', service_name='ast041.com')
conn = cx_Oracle.connect(user=r'usr', password='3451', dsn=dsn_tns)
c = conn.cursor()

query ='SELECT * FROM Employee WHERE ROWNUM <10'
result = pd.read_sql(query, con=conn)
result.to_excel("batchtable.xlsx")

conn.close()
</code>```

答:
You can access your data by mounting a volume into your container e.g.

```<code>docker run -ti -v $(pwd):/data IMAGE
</code>```

https://docs.docker.com/storage/volumes/#start-a-container-with-a-volume

Body:
I have dockerized my python application. This application connects with Oracle database, pull out 10 rows from a table and then generate excel. I was able to build my image successfully with all dependent libraries and it's also executing fine. Now, I am not sure how to get generated excel file (batchtable.xlsx) in docker.
I am new to docker and would need your suggestion. I have checked output without storing records into excel and it's coming fine on console, so there is no code issue.

Dockerfile

FROM python:3.7.4-slim-buster

RUN apt-get update && apt-get install -y libaio1 wget unzip

WORKDIR /opt/oracle
COPY File.py /opt/oracle

RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \
    unzip instantclient-basiclite-linuxx64.zip && rm -f instantclient-basiclite-linuxx64.zip && \
    cd /opt/oracle/instantclient* && rm -f *jdbc* *occi* *mysql* *README *jar uidrvci genezi adrci && \
    echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf && ldconfig

RUN python -m pip install --upgrade pip
RUN python -m pip install cx_Oracle
RUN python -m pip install pandas
RUN python -m pip install openpyxl

CMD [ "python", "/opt/oracle/File.py" ]

File.py

import cx_Oracle
import pandas as pd

#creating database connection
dsn_tns = cx_Oracle.makedsn('dev-tr01.com', '1222', service_name='ast041.com')
conn = cx_Oracle.connect(user=r'usr', password='3451', dsn=dsn_tns)
c = conn.cursor()

query ='SELECT * FROM Employee WHERE ROWNUM <10'
result = pd.read_sql(query, con=conn)
result.to_excel("batchtable.xlsx")

conn.close()

Body:
You can access your data by mounting a volume into your container e.g.

docker run -ti -v $(pwd):/data IMAGE

https://docs.docker.com/storage/volumes/#start-a-container-with-a-volume


问:
CakePHP find list with related model conditions
I'm trying to get a list of IDs (a la find('list')), but can't figure out how to do it with related model conditions.

My associations are:
Product hasAndBelongsToMany Category
Product belongsTo Manufacturer

I want to find a list of product IDs that are in a list of category IDs and have a certain manufacturer seo_url. I've tried tons of contains with conditions, conditions referencing other models, even tried using find('all') to see if my conditions would work, but couldn't get anything.

I managed to get one with Product->query(), but it's not in the format of a list. I could cycle through the array and grab IDs or whatever, but it feels awfully un-Cakey. I want to make sure Cake still does all its security checks on my queries and whatever other automagic it does. Here's the query I got working:

```<code>$all_results = $return['Category']['all_results'] = $this->Product->query('
    SELECT `Product`.`id`
        FROM `categories_products` as `CategoriesProduct`
        JOIN `products` as `Product` ON (`CategoriesProduct`.`product_id` = `Product`.`id`)
        JOIN `manufacturers` as `Manufacturer` ON (`Product`.`manufacturer_id` = `Manufacturer`.`id` AND `Manufacturer`.`seo_url` = \''.$manufacturer.'\')
        WHERE `CategoriesProduct`.`category_id` IN ('.implode(',', $search_categories).')
');
</code>```

this returns

```<code>[all_results] => Array
    (
         [0] => Array
            (
                [Product] => Array
                    (
                        [id] => 101787
                    )

            )

        [1] => Array
            (
                [Product] => Array
                    (
                        [id] => 100781
                    )

            )

        [2] => Array
            (
                [Product] => Array
                    (
                        [id] => 101887
                    )

            )

        [3] => Array
            (
                [Product] => Array
                    (
                        [id] => 101888
                    )

            )

    )
</code>```

Note: $search_categories is the list of category ID's (ie: array(12,42,24,5))

答:
The problem with your wanted result is, that Cake won't give you back a stripped result array if you use conditions on your related models.

This happens because Cake will only use these conditions on your related model and give you back the results with conditions being true on your related models.

If you want get back products with only specific Category you need to query through the Category-Model as this gives you the possibility to use the conditions on your Products. This could look something like this:

```<code>$this->Category->find('all', array('conditions' => array('Category.id' => 2));
</code>```

This will give you back only the wanted Category and its associated Products.
However, this is not very satisfying if you want a list, because you would have to manually do the conversion.

I would rather take a look at the Linkable Plugin which should give you exactly your wanted functionality as it extends Cake in using joins as you did in your query. This makes it possible on getting results with conditions on your related models.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a list of IDs (a la find('list')), but can't figure out how to do it with related model conditions.

My associations are:
Product hasAndBelongsToMany Category
Product belongsTo Manufacturer

I want to find a list of product IDs that are in a list of category IDs and have a certain manufacturer seo_url. I've tried tons of contains with conditions, conditions referencing other models, even tried using find('all') to see if my conditions would work, but couldn't get anything.

I managed to get one with Product->query(), but it's not in the format of a list. I could cycle through the array and grab IDs or whatever, but it feels awfully un-Cakey. I want to make sure Cake still does all its security checks on my queries and whatever other automagic it does. Here's the query I got working:

$all_results = $return['Category']['all_results'] = $this->Product->query('
    SELECT `Product`.`id`
        FROM `categories_products` as `CategoriesProduct`
        JOIN `products` as `Product` ON (`CategoriesProduct`.`product_id` = `Product`.`id`)
        JOIN `manufacturers` as `Manufacturer` ON (`Product`.`manufacturer_id` = `Manufacturer`.`id` AND `Manufacturer`.`seo_url` = \''.$manufacturer.'\')
        WHERE `CategoriesProduct`.`category_id` IN ('.implode(',', $search_categories).')
');

this returns

[all_results] => Array
    (
         [0] => Array
            (
                [Product] => Array
                    (
                        [id] => 101787
                    )

            )

        [1] => Array
            (
                [Product] => Array
                    (
                        [id] => 100781
                    )

            )

        [2] => Array
            (
                [Product] => Array
                    (
                        [id] => 101887
                    )

            )

        [3] => Array
            (
                [Product] => Array
                    (
                        [id] => 101888
                    )

            )

    )

Note: $search_categories is the list of category ID's (ie: array(12,42,24,5))

Body:
The problem with your wanted result is, that Cake won't give you back a stripped result array if you use conditions on your related models.

This happens because Cake will only use these conditions on your related model and give you back the results with conditions being true on your related models.

If you want get back products with only specific Category you need to query through the Category-Model as this gives you the possibility to use the conditions on your Products. This could look something like this:

$this->Category->find('all', array('conditions' => array('Category.id' => 2));

This will give you back only the wanted Category and its associated Products.
However, this is not very satisfying if you want a list, because you would have to manually do the conversion.

I would rather take a look at the Linkable Plugin which should give you exactly your wanted functionality as it extends Cake in using joins as you did in your query. This makes it possible on getting results with conditions on your related models.


问:
detecting difference between two different taken images for the same view
I am taking  pictures for a paper with big dots and trying to detect the added dots in the next pic.

For example in the shown two pics I should be able to identify the 16 added dots.

I tried to use compare_ssim from scikit to detect them but It didn't get any dots because the two images aren't perfectly aligned.

After that I tried to align the images following this tutorial
before compare_ssim but it detected all the dots as changes in the two images besides that it detected other changes in the background as shown in the image below.

The code used and the test images are in this folder

答:
I solved this problem by :

Detecting the paper in the image paper before and after using ORB detector.

After that applying Image alignment as in the tutorial to the cropped images.

comparing the cropped Images using compare_ssim.

detecting the new added holes by using BLOB detector on the result of step no. 3


问:
How to calculate the time spent when using got?
Example code:

```<code>const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}
</code>```

I wonder if there is a better way?

答:
You may use a 3rd Party statman-stopwatch to easily record the total time.

Example

```<code>const got = require('got');
const Stopwatch = require('statman-stopwatch');
async function timeSpent (){
    const sw = new Stopwatch();
    sw.start();
    await got('***');
    sw.stop();
    const delta = sw.read();
  return delta;
}
</code>```

Body:
Example code:

const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}

I wonder if there is a better way?

Body:
You may use a 3rd Party statman-stopwatch to easily record the total time.

Example

const got = require('got');
const Stopwatch = require('statman-stopwatch');
async function timeSpent (){
    const sw = new Stopwatch();
    sw.start();
    await got('***');
    sw.stop();
    const delta = sw.read();
  return delta;
}


问:
rsync does not work in Visual Studio 2019
I have created a simple CMake project from the template provided in visual studio 2019. It connects to remote Linux server and errors out while copying a file using "rsync" with the following error.

```<code>Could not start the 'rsync' command on the remote host, please install it using your system package manager. Please see https://aka.ms/AA23jat for troubleshooting.
</code>```

The log shows the error details as following.

```<code>23:03:25.2045083 [Error, Thread 88]    liblinux.IO.Rsync: liblinux.IO.RsyncException: Could not create daemon configuration file on remote device ---> liblinux.IO.RsyncException: echo config error:  and error output: Unmatched ".
</code>```

Please note: rsync is installed on the remote Linux server and tested it with and without ssh its working.

When I tried to test rsync which is provided by Visual Studio under "C:\Apps\VS2019Pro\Common7\IDE\VC\Linux\bin\rsync\rsync.exe" to sync/copy a file to remote linux server it fails with following error.

```<code>dup() in/out/err failed
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.3]
</code>```

Any help on this will be appreciated.

答:
Rsync speaks the rsync protocol, which is a client server protocol.
The client you are using needs to talk to a server, which is the rsync binary on the remote server, which doesn't seem to be here.

The message is pretty clear:

```<code>Could not start the 'rsync' command on the remote host, please install it using your system package manager. Please see https://aka.ms/AA23jat for troubleshooting.
</code>```

You really need to have rsync on your remote server.

Body:
I have created a simple CMake project from the template provided in visual studio 2019. It connects to remote Linux server and errors out while copying a file using "rsync" with the following error.

Could not start the 'rsync' command on the remote host, please install it using your system package manager. Please see https://aka.ms/AA23jat for troubleshooting.

The log shows the error details as following.

23:03:25.2045083 [Error, Thread 88]    liblinux.IO.Rsync: liblinux.IO.RsyncException: Could not create daemon configuration file on remote device ---> liblinux.IO.RsyncException: echo config error:  and error output: Unmatched ".

Please note: rsync is installed on the remote Linux server and tested it with and without ssh its working.

When I tried to test rsync which is provided by Visual Studio under "C:\Apps\VS2019Pro\Common7\IDE\VC\Linux\bin\rsync\rsync.exe" to sync/copy a file to remote linux server it fails with following error.

dup() in/out/err failed
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.3]

Any help on this will be appreciated.

Body:
Rsync speaks the rsync protocol, which is a client server protocol.
The client you are using needs to talk to a server, which is the rsync binary on the remote server, which doesn't seem to be here.

The message is pretty clear:

Could not start the 'rsync' command on the remote host, please install it using your system package manager. Please see https://aka.ms/AA23jat for troubleshooting.

You really need to have rsync on your remote server.


问:
Spacy - making smaller size of library
Is it possible to make smaller size of this lib?
Currently in python.36/site-packages/spacy lang is 380MiB folder, where I see a lot of unused languages by me. I use only en, and is it possible to install with pip somehow spacy and load to this folder only needed language?</p>

答:
There's some nice work being done to get the size of Spacy down for serverless deployments like AWS Lambda:
https://github.com/ryfeus/lambda-packs

In addition to trimming down the repository, they also move the language models to S3 to limit the size requirements of the package.

Also see here for a python script to prune the languages:
https://gist.github.com/jshhrrsn/5377b9dd282ef51f5564f1347a7d5aef

Title: Spacy - making smaller size of library


问:
How to add model attribute fields by monkey patching?
I know already how to add (include, prepend) methods into the class. But how to add attributes? For example i would like to patch core model by adding it has_one field, how am I supposed to do it? Thanks in advance.

E.x

```<code>  class Project < ActiveRecord::Base
  include Redmine::SafeAttributes
  include Redmine::NestedSet::ProjectNestedSet

  # Specific overridden Activities
  has_many :time_entry_activities
  has_many :memberships, :class_name => 'Member', :inverse_of => :project
  # Memberships of active users only
  has_many :members,
           lambda { joins(:principal).where(:users => {:type => 'User', :status => Principal::STATUS_ACTIVE}) }
</code>```

I'd like to add one more has_many / has_one field not editing this class - which is in projects core, but as monkey patching -> include one more has_many from plugin directory

答:
Found a solution.

```<code>def self.included(base) # :nodoc:
    base.class_eval do
      unloadable
      has_many :project_descriptions
    end
  end
  Project.send(:include, Module::Patches::ProjectPatch)
</code>```

Adding fields to class, base here stands for included class, class_eval is evaluated in the context of that class.
More info on class_eval, instance_eval on
https://www.jimmycuadra.com/posts/metaprogramming-ruby-class-eval-and-instance-eval/

Body:
I know already how to add (include, prepend) methods into the class. But how to add attributes? For example i would like to patch core model by adding it has_one field, how am I supposed to do it? Thanks in advance.

E.x

  class Project < ActiveRecord::Base
  include Redmine::SafeAttributes
  include Redmine::NestedSet::ProjectNestedSet

  # Specific overridden Activities
  has_many :time_entry_activities
  has_many :memberships, :class_name => 'Member', :inverse_of => :project
  # Memberships of active users only
  has_many :members,
           lambda { joins(:principal).where(:users => {:type => 'User', :status => Principal::STATUS_ACTIVE}) }

I'd like to add one more has_many / has_one field not editing this class - which is in projects core, but as monkey patching -> include one more has_many from plugin directory

Body:
Found a solution.

def self.included(base) # :nodoc:
    base.class_eval do
      unloadable
      has_many :project_descriptions
    end
  end
  Project.send(:include, Module::Patches::ProjectPatch)

Adding fields to class, base here stands for included class, class_eval is evaluated in the context of that class.
More info on class_eval, instance_eval on
https://www.jimmycuadra.com/posts/metaprogramming-ruby-class-eval-and-instance-eval/


问:
How to split a heat map or a draw a boundary with specific range?
I have a expression matrix containing three groups. I need to draw or split the heat-map with specific range of column.

```<code>Total number of colums: 151 where 1st column is gene ids
Group1: 2:40
Group2: 41:80
Group3: 81:151
</code>```

I searched for splitting the heatmap and I got some hits like this.
But they are based on specific clusters.
I need to give my range as (2:40, 41:80, 81:151) for splitting or making boundary for the heatmap

答:
Something like this

```<code>library(pheatmap)
mat = cbind(genes=1:100,
matrix(rnorm(150*100,mean = rep(1:3,c(39*100,40*100,71*100))),ncol=150))
colnames(mat)[2:ncol(mat)] = paste0("col",1:150)
</code>```

You need to know how many are in each group, from what you provided, i counted this:

Group1: 39 Group2: 40 Group3: 71

So you need to make a data.frame that has the same row names as your matrix, and tell it which is group1,2 etc.

```<code>DF = data.frame(Groups=rep(c("Group1","Group2","Group3"),c(39,40,71)))
rownames(DF) = colnames(mat)[2:ncol(mat)]
</code>```

Then we plot, mat[,-1] means excluding the first column, you need to specify where to insert the gap, and for your example it is at 39,79 and 80 because we excluded the first column:

```<code>pheatmap(mat[,-1],cluster_cols=FALSE,
annotation_col=DF,gaps_col = cumsum(c(39,40,71)))
</code>```

Body:
I have a expression matrix containing three groups. I need to draw or split the heat-map with specific range of column.

Total number of colums: 151 where 1st column is gene ids
Group1: 2:40
Group2: 41:80
Group3: 81:151

I searched for splitting the heatmap and I got some hits like this.
But they are based on specific clusters.
I need to give my range as (2:40, 41:80, 81:151) for splitting or making boundary for the heatmap

Body:
Something like this

library(pheatmap)
mat = cbind(genes=1:100,
matrix(rnorm(150*100,mean = rep(1:3,c(39*100,40*100,71*100))),ncol=150))
colnames(mat)[2:ncol(mat)] = paste0("col",1:150)

You need to know how many are in each group, from what you provided, i counted this:

Group1: 39 Group2: 40 Group3: 71

So you need to make a data.frame that has the same row names as your matrix, and tell it which is group1,2 etc.

DF = data.frame(Groups=rep(c("Group1","Group2","Group3"),c(39,40,71)))
rownames(DF) = colnames(mat)[2:ncol(mat)]

Then we plot, mat[,-1] means excluding the first column, you need to specify where to insert the gap, and for your example it is at 39,79 and 80 because we excluded the first column:

pheatmap(mat[,-1],cluster_cols=FALSE,
annotation_col=DF,gaps_col = cumsum(c(39,40,71)))


问:
How to create a PHP dropdown list that allows you to select multiple options?
This is the basis for the code I'm using, drawing options from a database but no matter how I alter this code I will only let me select 1 option or return an error.</p>

```<code><select name="sargentid" id="fieldsargentid" class="form-control">

<?php foreach ($sargent as $sargent) { echo "<option value='" . $sargent->getID() .
"'>$sargent</option>"; }?>

</select>
</code>```

答:
A drop-down list that allows multiple selections using the multiple attribute:

```<code><select id="animals" name="animal" multiple>
  <option value="cat">Cat</option>
  <option value="dog">Dog</option>
  <option value="mouse">Mouse</option>
  <option value="lion">Lion</option>
</select>
</code>```

Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.

Demo: https://jsfiddle.net/prk6c9q7/

Body:
This is the basis for the code I'm using, drawing options from a database but no matter how I alter this code I will only let me select 1 option or return an error.

<select name="sargentid" id="fieldsargentid" class="form-control">

<?php foreach ($sargent as $sargent) { echo "<option value='" . $sargent->getID() .
"'>$sargent</option>"; }?>

</select>

Body:
A drop-down list that allows multiple selections using the multiple attribute:

<select id="animals" name="animal" multiple>
  <option value="cat">Cat</option>
  <option value="dog">Dog</option>
  <option value="mouse">Mouse</option>
  <option value="lion">Lion</option>
</select>

Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.

Demo: https://jsfiddle.net/prk6c9q7/


问:
How to get last access time of application in WebSphere Liberty Server 19.0.0.11
Am developing application in Java 8, JSF, Maven. Build application as war and deploying it in WebSphere Liberty Server 19.0.0.11. I got requirement to get application last access time.? Is there any way to get this detail.?</p>

答: You could probably write a filter that would intercept all requests to the app and update variable that would hold last access , or return that variable value if you would query for that. </p>


问:
Hiding multiple tag with same name or class
I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class. </p>

```<code>Element.hide('indicate')
</code>```

<p>But, the above line only satisfy to hide the first element only. "indicate" is the id. </p>

答: Having the same id for two elements isn't supported in HTML, so there's no methods in Javascript to handle it. No matter what framework you're using.</p>

Body:
I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class.

Element.hide('indicate')

But, the above line only satisfy to hide the first element only. "indicate" is the id.


问:
Reusing Fragment in multiple tabs
i will try my best to explain.
Lets say there are 3 tabs in my app.
Right now

Tab 1 inflates fragment 1,

Tab 2 inflates fragment 2,

Tab 3 inflates fragment 3.

I don't want to use three fragments because the code is being fully reused in all 3 except 1 function i.e populatelist
what I planned on doing was just using fragment 1 with three different functions and implement a logic to check

if tab 1, run populatelist1

if tab 2, run populatelist2

if tab 3,run populatelist3

I managed to do it by using viewpage . addOnPageChangeListener, This works but the problem is it is slowing down the app since list only gets populated when user clicks on the tab. Its not prepopulated like having 3 different fragments.

so I want to know is there a way to get Tab position and prepopulated the list on those positions? This way whether user switches to tab 2 or not the list will be present there just like it is when we have 3 different fragments.

答:
you just need to use one ViewModel for all fragments.
its simple and best practice.</p>

Title: Reusing Fragment in multiple tabs


问:
pyomo constraint express ranged inequality expressions
I'm noob w pyomo. I'd like to do this:

```<code>for w in ww:
    model.constraints.add(
        100 >= sum(8 * model.w[w, d, s] for d in dd for s in ss) >= 50
    )
</code>```

instead I'd tried this way:

```<code>for w in ww:
    model.constraints.add(
        100 >= sum(8 * model.w[w, d, s] for d in dd for s in ss)
    )

for w in ww:
    model.constraints.add(
        50 <= sum(8 * model.w[w, d, s] for d in dd for s in ss)
    )
</code>```

but It didn't work. It

```<code>WARNING: Loading a SolverResults object with a warning status into
    model=unknown;
        message from solver=<undefined>
</code>```

I'm missing something, can u tell me what?

答:
Solved. I found

```<code>WARNING: Loading a SolverResults object with a warning status into
    model=unknown;
        message from solver=<undefined>
</code>```

because the model is infeasible.

Body:
I'm noob w pyomo. I'd like to do this:

for w in ww:
    model.constraints.add(
        100 >= sum(8 * model.w[w, d, s] for d in dd for s in ss) >= 50
    )

instead I'd tried this way:

for w in ww:
    model.constraints.add(
        100 >= sum(8 * model.w[w, d, s] for d in dd for s in ss)
    )

for w in ww:
    model.constraints.add(
        50 <= sum(8 * model.w[w, d, s] for d in dd for s in ss)
    )

but It didn't work. It

WARNING: Loading a SolverResults object with a warning status into
    model=unknown;
        message from solver=<undefined>

I'm missing something, can u tell me what?

Body:
Solved. I found

WARNING: Loading a SolverResults object with a warning status into
    model=unknown;
        message from solver=<undefined>

because the model is infeasible.


问:
STL container with a specific type as a generic argument
Is there any way that I can make a function which takes a container with a specific type (lets say std::string) as a parameter

```<code>void foo(const std::container<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}
</code>```

and call it for every type of stl container as input? like above?

```<code>std::set<std::string> strset;
std::vector<std::string> strvec;
std::list<std::string> strlist;

foo(strset);
foo(strvec);
foo(strlist);
</code>```

答:
You can make foo a function template taking a template template parameter for the container type.

e.g.

```<code>template<template<typename...> typename C>
void foo(const C<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}
</code>```

LIVE

Body:
Is there any way that I can make a function which takes a container with a specific type (lets say std::string) as a parameter

void foo(const std::container<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}

and call it for every type of stl container as input? like above?

std::set<std::string> strset;
std::vector<std::string> strvec;
std::list<std::string> strlist;

foo(strset);
foo(strvec);
foo(strlist);

Body:
You can make foo a function template taking a template template parameter for the container type.

e.g.

template<template<typename...> typename C>
void foo(const C<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}

LIVE


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答: In addition to adding it to the path (which will fix your problem), you may want to download make and dbg, which are also on the development path but not checked by default. Make sure to select "keep" as the overall install options so it doesn't re-download everything. </p>

ContentLicense: CC BY-SA 2.5

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: Jack BeNimble


问:
Is there a Javascript support library for html5 file API and upload?
until now I was using flash based swfupload and its swfupload.js which provides users with callbacks from flash and a possibility to set it up.

I was wondering if there is anything like this for HTML5 File API. I'm asking before I make it from scratch myself. I don't want to reinvent a wheel when there might be a good library out there already.

答:
I use valums file uploader. This uploads using ajax by default and provides a fallback (hidden iframe) if the browser doesn't support ajax uploads.

http://valums.com/ajax-upload/

The complete upload widget uses the File API for drag-and-drop support.


问:
Permission Issue on Bulk Insert in Azure SQL Server
User is getting below error while running bulk insert command in Azure SQL Server. I am using Azure SQL Server and not SQL Sever. Most of the commands related to Bulk Insert grant permission is not working in Azure SQL Server.

Error

```<code>You do not have permission to use the bulk load statement.
</code>```

Commands Tried in Azure SQL Server to Add User

```<code>EXEC sp_addrolemember 'db_ddladmin', 'testuser';

ALTER SERVER ROLE [bulkadmin] ADD MEMBER testuser

GRANT ADMINISTER BULK OPERATIONS TO testuser
</code>```

Error

```<code>Msg 40520, Level 16, State 1, Line 5
Securable class 'server' not supported in this version of SQL Server.
</code>```

Your help is highly appreciated.

答:
```<code>GRANT CONTROL to testuser
</code>```

nothing else is needed, just this to be executed in content DB (not master)

full steps

in Master

```<code>CREATE LOGIN login1 WITH password='1231!#ASDF!a';
</code>```

in content DB

```<code>CREATE USER user1 FROM LOGIN login1;

GRANT CONTROL to user1; --(this is for bulk to work)
</code>```

Body:
User is getting below error while running bulk insert command in Azure SQL Server. I am using Azure SQL Server and not SQL Sever. Most of the commands related to Bulk Insert grant permission is not working in Azure SQL Server.

Error

You do not have permission to use the bulk load statement.

Commands Tried in Azure SQL Server to Add User

EXEC sp_addrolemember 'db_ddladmin', 'testuser';

ALTER SERVER ROLE [bulkadmin] ADD MEMBER testuser

GRANT ADMINISTER BULK OPERATIONS TO testuser

Error

Msg 40520, Level 16, State 1, Line 5
Securable class 'server' not supported in this version of SQL Server.

Your help is highly appreciated.

Body:
GRANT CONTROL to testuser

nothing else is needed, just this to be executed in content DB (not master)

full steps

in Master

CREATE LOGIN login1 WITH password='1231!#ASDF!a';

in content DB

CREATE USER user1 FROM LOGIN login1;

GRANT CONTROL to user1; --(this is for bulk to work)


问:
javasript in angular 8
There's a solution on js -

codepen.io/skovtun/pen/VwLvXPB

Can't make an analog for Angular8+.

I need the center block to have a fixed width (1200px), and it is evaluated and compressed by the left, right and both sidebars immediately when they are opened. They should not overlap with the content.

答:
I seen content overlapping when closing sidebars. May be you want to stop overlapping during open and close sidebar. It can be fixed by css. You can use transition in <code>.wrapper</code> class. see bellow code: </p>

```<code>.wrapper{
  height: 100%;
  transition:all .25s;
}
</code>```

Title: javasript in angular 8

Body:
I seen content overlapping when closing sidebars. May be you want to stop overlapping during open and close sidebar. It can be fixed by css. You can use transition in .wrapper class. see bellow code:

.wrapper{
  height: 100%;
  transition:all .25s;
}


问:
useEffect hook is running in loop and hanging the application
What I am building here is a simple todo application using hooks
with two input fields and one submit button. On submit I am saving the content of the inputs in an array and storing it in async storage. Using retrieve function I am fetching the values and displaying it below in a view component in list form.

```<code>useEffect(() => {
  // AsyncStorage.clear();
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem("user");
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};
</code>```

Removing the data element from the useEffect, doesn't update the component and the current value updated in the array is not displayed. It does get displayed only after another text is added in the array and the same goes on for the future addition to the data. But the app doesn't hang for sure.

Thanks for any help

答:
Your useEffect hook will run any time data is changed. (As it is in the dependency list).

However, inside your useEffect you call retrieveData which calls setData(value);.

This will update data. Which in turn, will trigger useEffect again.

If you are wanting to just call retrieveData once on startup, you can empty the dependency list and it will act like componentDidMount.

Body:
What I am building here is a simple todo application using hooks
with two input fields and one submit button. On submit I am saving the content of the inputs in an array and storing it in async storage. Using retrieve function I am fetching the values and displaying it below in a view component in list form.

useEffect(() => {
  // AsyncStorage.clear();
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem("user");
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};

Removing the data element from the useEffect, doesn't update the component and the current value updated in the array is not displayed. It does get displayed only after another text is added in the array and the same goes on for the future addition to the data. But the app doesn't hang for sure.

Thanks for any help


问:
After installing react navigation 5.x app is getting crashed all the time
I have installed "npm install @react-navigation/native" and all the dependencies with it "npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view". After installation when I build the app and , its building successfully but getting crashed after installing on my phone.

when I uninstall the dependency react-native-safe-area-context, app is running but it suppose to be needed to use react navigation.

I am using windows machine, testing on my android phone.

package.json

```<code>{
"name": "Money",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@react-native-community/masked-view": "^0.1.6",
"@react-navigation/bottom-tabs": "^5.0.5",
"@react-navigation/drawer": "^5.0.5",
"@react-navigation/native": "^5.0.5",
"@react-navigation/stack": "^5.0.5",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-screens": "^2.0.0-beta.7",
"react-native-vector-icons": "^6.6.0"
},
"devDependencies": {
"@babel/core": "^7.6.2",
"@babel/runtime": "^7.6.2",
"@react-native-community/eslint-config": "^0.0.5",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"jest": "^24.9.0",
"metro-react-native-babel-preset": "^0.56.0",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
}
}
</code>```

答:
Solved this issue by doing this work around.

Can confirm, crashing immediately after launch on Android, no problems on iOS.
It seems there is a Java class missing.

java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/swiperefreshlayout/widget/SwipeRefreshLayout;

Add the following dependencies to app/build.gradle to avoid this error:

implementation 'androidx.appcompat:appcompat:1.2.0-alpha02'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha03'

Check this link

Body:
I have installed "npm install @react-navigation/native" and all the dependencies with it "npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view". After installation when I build the app and , its building successfully but getting crashed after installing on my phone.

when I uninstall the dependency react-native-safe-area-context, app is running but it suppose to be needed to use react navigation.

I am using windows machine, testing on my android phone.

package.json

{
"name": "Money",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@react-native-community/masked-view": "^0.1.6",
"@react-navigation/bottom-tabs": "^5.0.5",
"@react-navigation/drawer": "^5.0.5",
"@react-navigation/native": "^5.0.5",
"@react-navigation/stack": "^5.0.5",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-screens": "^2.0.0-beta.7",
"react-native-vector-icons": "^6.6.0"
},
"devDependencies": {
"@babel/core": "^7.6.2",
"@babel/runtime": "^7.6.2",
"@react-native-community/eslint-config": "^0.0.5",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"jest": "^24.9.0",
"metro-react-native-babel-preset": "^0.56.0",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
}
}


问:
Does as3isolib depth sort automatically?
I have built an isometric plane and isometric plane contains 64 grass object and one box object that move on click.

A MouseEvent.CLICK handler is attached to each grass object.
I have drawn grass and box using as3isolib. Both are as3isolib objects.

When the user clicks at any of the grass object that is anywhere on the plane, the box moves to that position but I can not understand if each time new index value is returned for the grass and box objects ?

```<code>public function OverOnEachTile(evt:ProxyEvent):void

{

var targetGrassObject:IsoSprite = evt.target as IsoSprite;

scene.getChildIndex(targetGrassObject) // returns different value for same tile or grass object

scene.getChildIndex(isoBox1); // returns different value for same single box instance of type isoBox

}
</code>```

答: Yes Z-Sorting is done automatically.</p>

Body:
I have built an isometric plane and isometric plane contains 64 grass object and one box object that move on click.

A MouseEvent.CLICK handler is attached to each grass object.
I have drawn grass and box using as3isolib. Both are as3isolib objects.

When the user clicks at any of the grass object that is anywhere on the plane, the box moves to that position but I can not understand if each time new index value is returned for the grass and box objects ?

public function OverOnEachTile(evt:ProxyEvent):void

{

var targetGrassObject:IsoSprite = evt.target as IsoSprite;

scene.getChildIndex(targetGrassObject) // returns different value for same tile or grass object

scene.getChildIndex(isoBox1); // returns different value for same single box instance of type isoBox

}

Body: Yes Z-Sorting is done automatically.


问:
Can we run our webpack (UI) build just like that in an browser without any server?
I have a reactjs setup with webpack dev server, and a webpack build. Can I run the build file which is bundle.js in browser directly? When we make a build and deploy it on cloud, what happens and how our application runs?

答: You can use Lite Server to deploy build files locally </p>


答:
You are passing [data] as second argument to useEffect which is dependency list.

That is the reason it is looping infinite. change it to [], it will run only once.

```<code>useEffect(() => {
    // AsyncStorage.clear();
    retrieveData();
  }, [data]);
</code>```

Title: useEffect hook is running in loop and hanging the application

Body:
You are passing [data] as second argument to useEffect which is dependency list.

That is the reason it is looping infinite. change it to [], it will run only once.

useEffect(() => {
    // AsyncStorage.clear();
    retrieveData();
  }, [data]);


答:
```<code><select name="sargentid" id="fieldsargentid" class="form-control" multiple=multiple>
    <?php

    foreach($sargent as $sargentKey => $sargentList){
      $values = $sargentList['NameofTheRowInTable'];
      ?>
        <options value = <?php echo $values; ?> ><?php echo $values;?></options>
      <?php
    }
    ?>
</select>
</code>```

Title: How to create a PHP dropdown list that allows you to select multiple options?


问:
Is creating a lot of UIViews in UIViewController a good practice for storyboards? Does it have any impact on application like memory?
Today I heard about new approach of design views in storyboard

Lets consider one page contain image , label and button now out storyboard as follow

1] our one UIViewController divides in three part i.e 3 UIViews for 3 components like one UIView for image

2] for keep image responsive take another UIView and keep imageView inside that and then set constraints and keep wight and height of imageView aspect ratio.

 3] I given different colour for different UIViews for understanding
final hierarchy is as below

So as per screenshot you can see view are more responsive and changes made in one UIView is not reflect is another one and our hierarchy of view are maintained .

Finally come to the questions

1] is this approach correct?

2] is there any impact of this much UIView views on application in terms of memory and performance?

答:
I tried this method a lot and I realise this approach solve lot of problems of setting constraints. This approach is similar as Bootstrsp . We are going to divide hole screen by UIViews and Finally put our main design views in it. Till now I don't know what is bad impact of this approach in application in terms of memory and speed. That I will explain in future.

Thanks a lot.


问:
How to prevent CSS from displaying the ::after content on a new line?
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Foo
Bar</code>```

The problem is that the result looks something like this:

```<code>Foo, Baz
, Bar
</code>```

答:
This is what you are looking for, I guess:

HTML:

```<code><a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>
</code>```

CSS :

```<code>a:after {
content: ', \00a0';
display: inline-block;
}

a {
 text-decoration: none;
}
</code>```

Text decoration has to be given to a not to a::after

Body:
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}

Foo
Bar

The problem is that the result looks something like this:

Foo, Baz
, Bar

Body:
This is what you are looking for, I guess:

HTML:

<a href="foo.com">Foo</a>
<a href="bar.com">Bar</a>

CSS :

a:after {
content: ', \00a0';
display: inline-block;
}

a {
 text-decoration: none;
}

Text decoration has to be given to a not to a::after


问:
What is a practical use of objects as keys within JS Map dataype?
I've recently been reading into Javascript's Map datatype (NOT the map() array method).
MDN Reference

I've read and followed various tutorials/articles showing the similarities and differences between Maps, Arrays and 'standard' Objects. One unique property of Maps is that you can use any datatype as a key, including an Object.

There are many examples out there, such as this one from Tania Rascia

```<code>// Create an object
const objAsKey = { foo: 'bar' }

const map = new Map()

// Set this object as the key of a Map
map.set(objAsKey, 'What will happen?')
</code>```

Here's the console output:

```<code>key: {foo: "bar"}
value: "What will happen?"
</code>```

What I'm asking is, what is a benefit of this possibility?
Why would I ever need to use an object as a key?

答:
From my tweets on the subject:

Say you have an object (like a DOM element) that you want to associate some data with, but you don't want to modify the object to add the data directly to it. So you use a Map with the object as key and your associated data as value.

typically, you'd want to use a WeakMap for this, so that if the original object goes away (garbage collected) the data is also released.

but a reason to use map instead of weakmap is that map is iterable and weakmap isn't.

so if you're willing to trade out that you need to do more manual work to manage the map entries (for cleaner garbage collection), then you get the ability to enumerate all the entries of the map, which can be useful in certain cases.

Body:
I've recently been reading into Javascript's Map datatype (NOT the map() array method).
MDN Reference

I've read and followed various tutorials/articles showing the similarities and differences between Maps, Arrays and 'standard' Objects. One unique property of Maps is that you can use any datatype as a key, including an Object.

There are many examples out there, such as this one from Tania Rascia

// Create an object
const objAsKey = { foo: 'bar' }

const map = new Map()

// Set this object as the key of a Map
map.set(objAsKey, 'What will happen?')

Here's the console output:

key: {foo: "bar"}
value: "What will happen?"

What I'm asking is, what is a benefit of this possibility?
Why would I ever need to use an object as a key?


问:
Min / Max validation - Vuetify
I need to make sure that only numbers between 5,000 and 50,000 can be entered. I'm currently using the following code,

```<code>rules: {
     required: value => !!value || 'Required.',
     loanMin: value => value <= 5000 || 'Loan should be above £5000',
     loanMax: value => value >= 50000 || 'Max should not be above £50,000',
}
</code>```

With the rules applied to the field as follows:

```<code><v-text-field
  height="5"
  :rules="[rules.loanMin, rules.loanMaxMax, rules.required]"
  editable
  v-model="sliderLoan"
  @change="principleLogger(sliderLoan)"
  persistent-hint
  outline
  label="Loan Amount"
  type="number"
></v-text-field>

</code>```

How to apply multiple rules to one field?

答:
I replied this question in this SO page.

just pass v-model variable as second parameter to your rule.

```<code><template>
  <v-input :rules=[rules.min(20, field1), rules.max(200, field1)] v-model="field1" />
</template>

<script>
  data() {
    rules: {
      min(min, v) {
        return (v || '').length >= min || `Value must be at least ${min}`;
      },

      max(max, v) {
        return (v || '').length <= max || `Value may not be greater than ${max}.`;
      }
    }
  }
</script>
</code>```

Title: Min / Max validation - Vuetify

Body:
I need to make sure that only numbers between 5,000 and 50,000 can be entered. I'm currently using the following code,

rules: {
     required: value => !!value || 'Required.',
     loanMin: value => value <= 5000 || 'Loan should be above £5000',
     loanMax: value => value >= 50000 || 'Max should not be above £50,000',
}

With the rules applied to the field as follows:

<v-text-field
  height="5"
  :rules="[rules.loanMin, rules.loanMaxMax, rules.required]"
  editable
  v-model="sliderLoan"
  @change="principleLogger(sliderLoan)"
  persistent-hint
  outline
  label="Loan Amount"
  type="number"
></v-text-field>

How to apply multiple rules to one field?

Body:
I replied this question in this SO page.

just pass v-model variable as second parameter to your rule.

<template>
  <v-input :rules=[rules.min(20, field1), rules.max(200, field1)] v-model="field1" />
</template>

<script>
  data() {
    rules: {
      min(min, v) {
        return (v || '').length >= min || `Value must be at least ${min}`;
      },

      max(max, v) {
        return (v || '').length <= max || `Value may not be greater than ${max}.`;
      }
    }
  }
</script>


问:
Visual Studio indentation of function arguments
Visual Studio 2010 indents the following C++ code as:

```<code> if (Foo(arg1,
     arg2))
 {
 }
</code>```

Is there a way to change Visual Studio formatting rules to indent the code as below:

```<code> if (Foo(arg1,
         arg2))
 {
 }
</code>```

答:
I think this is a duplicate of Automatic indentation of arguments list on multiple lines in Visual Studio. In which I provided an answer for Visual Studio 2017.

Under menu Tools → Options → Text editor → C/C++ → Formatting → Indentation → "Within parentheses, align new lines when I type them".

Choose the option "Align contents to opening parentheses.

Body:
Visual Studio 2010 indents the following C++ code as:

 if (Foo(arg1,
     arg2))
 {
 }

Is there a way to change Visual Studio formatting rules to indent the code as below:

 if (Foo(arg1,
         arg2))
 {
 }


问:
Sharing data between android users
I'm having trouble understanding the top level of abstraction of this problem.

The Problem:
Users A and B download application X. A wants to send application-specific data to B. How does user A link with B?

My incredibly messy solution:
 - User A clicks a button on the application that opens up a list of contacts. user A selects user B from the list. User B's email address was stored in A's address book. Application creates a sort of "share ID"  and sends it to user B via that email address. User B's application gets that ID from the mail, then User A and B use the share ID to connect to a server and share between each other via the sserver.

There must be a better way? The two problems are:
1. It shouldn't need a server (should it? could it be free?)
2. There must be better ways of the users connecting to each other than sending ID's or links etc by gmail.

This solution should be so so simple, but I can't get my head round it. If this question is not sufficient to get a good answer, please please tell me what I need to do to get into the way of thinking about how mobile users can interract with each other as simply as possible, with as few clicks as possible, (Mobile 2.0 or whatever the modern day thing is!)

For example: A mother and a child have an android smart phone. They each download the "ChildLeash" app. Child wishes to configure the app to send updates to Mother, so that Mother can keep track of Child's location and so on. The problem is some how Child needs to tell the app what location Mother is at for the data to be sent to. What is a user-friendly way for Child to Identify Mother's phone? (Mother's IP address? Phone number? Email address? OpenIDs? NFC/Bluetooth?) So that it can then communicate?

答:
Usually this sort of interaction would require a server. Which you've kind of faked using email as your medium.

It might be worth looking into peer to peer libraries such as JXTA. There's an android port here: http://code.google.com/p/peerdroid/

EDIT: I just came across this: http://android-developers.blogspot.com/2010/05/android-cloud-to-device-messaging.html Which looks like exactly what you're after.

Title: Sharing data between android users


问:
SQL stored proc using where in statement
I am trying to inserting data from a table to another table. But I need using multiple specific IDs in where clause. And, I need to define these IDs while running the proc. The query is below,

```<code>CREATE PROCEDURE insert_hh
@id int
AS
BEGIN
SET IDENTITY_INSERT test_HH ON
INSERT INTO test_HH
(ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection)
SELECT ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection
FROM HH
WHERE ID IN ((@id))
SET IDENTITY_INSERT test_HH OFF
END
</code>```

For now, I can insert only one ID for each time. Can you help me to insert multiple IDs in the same proc?
Thanks.

答:
For multiple value change @Id parameter of stored procedure to VARCHAR with desired length.</p>

```<code>CREATE PROCEDURE insert_hh
@id varchar(max)
AS
    SET @Id  = '1,10,20,30'
-- temp table
    DECLARE @Id_tbl TABLE (   Id INT )

    INSERT INTO @Id_tbl
    SELECT
        LTRIM(RTRIM(split.a.value('.', 'NVARCHAR(MAX)'))) AS fqdn
    FROM
        (SELECT
            CAST ('<M>' + REPLACE(@Id, ',', '</M><M>') + '</M>' AS XML) AS data   ) AS a
            CROSS APPLY data.nodes ('/M') AS split(a)

    -- INSERT STATEMENT
    SELECT <Fields> FROM
    <Your Table>
    WHERE
        ID IN (SELECT Id FROM @Id_tbl)
END
GO
</code>```

Body:
I am trying to inserting data from a table to another table. But I need using multiple specific IDs in where clause. And, I need to define these IDs while running the proc. The query is below,

CREATE PROCEDURE insert_hh
@id int
AS
BEGIN
SET IDENTITY_INSERT test_HH ON
INSERT INTO test_HH
(ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection)
SELECT ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection
FROM HH
WHERE ID IN ((@id))
SET IDENTITY_INSERT test_HH OFF
END

For now, I can insert only one ID for each time. Can you help me to insert multiple IDs in the same proc?
Thanks.

Body:
For multiple value change @Id parameter of stored procedure to VARCHAR with desired length.

CREATE PROCEDURE insert_hh
@id varchar(max)
AS
    SET @Id  = '1,10,20,30'
-- temp table
    DECLARE @Id_tbl TABLE (   Id INT )

    INSERT INTO @Id_tbl
    SELECT
        LTRIM(RTRIM(split.a.value('.', 'NVARCHAR(MAX)'))) AS fqdn
    FROM
        (SELECT
            CAST ('<M>' + REPLACE(@Id, ',', '</M><M>') + '</M>' AS XML) AS data   ) AS a
            CROSS APPLY data.nodes ('/M') AS split(a)

    -- INSERT STATEMENT
    SELECT <Fields> FROM
    <Your Table>
    WHERE
        ID IN (SELECT Id FROM @Id_tbl)
END
GO


问:
rename bigquery tablename
How to rename table name in bigquery table?

答: Currently, you can't rename an existing table in google big query. Instead, you can follow the copy process. You may refer the Google documentation</p>

Title: rename bigquery tablename


问:
iOS universal linking: exlude naked domain only
I'm trying to support Universal Links in my iOS app.

I would like the mydomain.com/ url to be excluded from Universal Link support, that is, to always open a webpage when url is tapped from an iOS device.

And I'd like mydomain.com/sometext url to open the linked app if it's installed.

Does anyone know if such requirements can be implemented?

答:
Found a working configuration!

The path value needs to be

"paths": [ "NOT /", "/*" ]


问:
Clean gridPane in JavaFX and maintain the Grid line
I'm trying to make a simple game (it is a school work) in JavaFX and I am trying to clear the panel with the board, and then just repaint it. I have tried a lot of methods, and this one is the only one I found that removes all the pieces of the board (visually) without creating a visual bug that shows a piece that has already been deleted but is still shown.

So I declare the gridPane like this:

```<code>private GridPane gridPecas;

@Override
public void start(Stage primaryStage)
{
    gridPecas = new GridPane();
    gridPecas.setGridLinesVisible(true);

    paintBoard();

    // rest of the code to create and paint the Stage
 }

 private void paintBoard()
 {
    gridPecas.getChildren().clear();
    // Code to fill the board with ImageView and Images of the pieces
 }
</code>```

The problem with this method, is that when the "gridPecas.getChildren().clear();" is called I just loose the grid lines from the GridPanel.

How can I solve this problem?

答:
Valid clear GridPane and restore mainrtain grid lines:</p>

```<code>gridPane.setGridLinesVisible(false);
gridPane.getColumnConstraints().clear();
gridPane.getRowConstraints().clear();
gridPane.getChildren().clear();
gridPane.setGridLinesVisible(true);
</code>```

Body:
I'm trying to make a simple game (it is a school work) in JavaFX and I am trying to clear the panel with the board, and then just repaint it. I have tried a lot of methods, and this one is the only one I found that removes all the pieces of the board (visually) without creating a visual bug that shows a piece that has already been deleted but is still shown.

So I declare the gridPane like this:

private GridPane gridPecas;

@Override
public void start(Stage primaryStage)
{
    gridPecas = new GridPane();
    gridPecas.setGridLinesVisible(true);

    paintBoard();

    // rest of the code to create and paint the Stage
 }

 private void paintBoard()
 {
    gridPecas.getChildren().clear();
    // Code to fill the board with ImageView and Images of the pieces
 }

The problem with this method, is that when the "gridPecas.getChildren().clear();" is called I just loose the grid lines from the GridPanel.

How can I solve this problem?

Body:
Valid clear GridPane and restore mainrtain grid lines:

gridPane.setGridLinesVisible(false);
gridPane.getColumnConstraints().clear();
gridPane.getRowConstraints().clear();
gridPane.getChildren().clear();
gridPane.setGridLinesVisible(true);


问:
How can I dump a list of variables to a file when a server is killed?
I'm in the middle of developing a server and client in java. Each client can send and retrieve messages that are stored in a list of JSON objects. I'm wondering if there is a way that I can dump this list to a file when the server is killed, so that way if the server is crashes or the process is killed, the messages can be recovered when the server starts back up again?

I'm unsure as to whether this is possible and I'm wondering if a better alternative would be to periodically save the data to a file constantly that way it would be kept up to date, but surely this would be more resource intensive?

答: I think you are looking for something like Kafka or AWS SQS.</p>


问:
Change store view automatically for different customer groups in Magento 2
I'm currently using Magento 2.3.2 and I would like to show certain customers a specific store view based on their customer group. (For example a customer in the "General" group would see the default store view, while a customer in the "Platinum" group would see the "Platinum" store view with a slightly different logo and design).

Is there an extension out there that can do this? I can only find ones which restrict the products in the catalog?

Edit 20/02/2020 -

Thanks to Invigorate Systems for the solution. I have now implemented the code as below in the app > code folders:

registration.php file inside GroupSite/SiteSwitch/

```<code><?php
    \Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'GroupSite_SiteSwitch',
    __DIR__
    );
</code>```

module.xml file inside GroupSite/SiteSwitch/etc/

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
            <module name="GroupSite_SiteSwitch" setup_version="2.1.1"></module>
</config>
</code>```

events.xml inside GroupSite/SiteSwitch/etc/frontend/

```<code><?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_layout_handles" instance="GroupSite\SiteSwitch\Observer\AddHandles" />
    </event>
</config>
</code>```

AddHandles.php file inside GroupSite/SiteSwitch/Observer

```<code><?php

namespace GroupSite\SiteSwitch\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;

class AddHandles implements ObserverInterface
{
    protected $customerSession;
    protected $_storeManager;
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
        $this->_storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();
         if ($this->customerSession->isLoggedIn())
             {
             $customerGroup = $this->customerSession->getCustomer()->getGroupId();
                if($customerGroup === '5'){
                    $this->_storeManager->setCurrentStore('13'); //Set your desired store ID that you wish to set.
                }
                else{
                    $this->_storeManager->setCurrentStore('1');
                }
             }
    }
}
</code>```

答:
You can do this by using Observers, here's an example module for you. this module will change store ID after customer login to the system.

Create registration.php file inside Vendor/Module/

```<code><?php
    \Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
    );
</code>```

Create module.xml file inside Vendor/Module/etc/

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
            <module name="Vendor_Module" setup_version="2.1.1"></module>
</config>
</code>```

Create events.xml inside Vendor/Module/etc/frontend/

```<code><?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_layout_handles" instance="Vendor\Module\Observer\AddHandles" />
    </event>
</config>
</code>```

Create Handler file for Observer AddHandles.php file inside Vendor/Module/Observer

```<code><?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;

class AddHandles implements ObserverInterface
{
    protected $customerSession;
    protected $_storeManager;
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
        $this->_storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();

        if ($this->customerSession->isLoggedIn())
        {
            /*
            Here you fetch loggedIn Customer Group and add if condition such as
            if(customerGroup == 'ID/Name of group you desire'){
                $this->_storeManager->setCurrentStore('2'); //Set your desired store ID that you wish to set.
            }
            */
            $this->_storeManager->setCurrentStore('2');
        }
    }
}
</code>```

Body:
I'm currently using Magento 2.3.2 and I would like to show certain customers a specific store view based on their customer group. (For example a customer in the "General" group would see the default store view, while a customer in the "Platinum" group would see the "Platinum" store view with a slightly different logo and design).

Is there an extension out there that can do this? I can only find ones which restrict the products in the catalog?

Edit 20/02/2020 -

Thanks to Invigorate Systems for the solution. I have now implemented the code as below in the app > code folders:

registration.php file inside GroupSite/SiteSwitch/

<?php
    \Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'GroupSite_SiteSwitch',
    __DIR__
    );

module.xml file inside GroupSite/SiteSwitch/etc/

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
            <module name="GroupSite_SiteSwitch" setup_version="2.1.1"></module>
</config>

events.xml inside GroupSite/SiteSwitch/etc/frontend/

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_layout_handles" instance="GroupSite\SiteSwitch\Observer\AddHandles" />
    </event>
</config>

AddHandles.php file inside GroupSite/SiteSwitch/Observer

<?php

namespace GroupSite\SiteSwitch\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;

class AddHandles implements ObserverInterface
{
    protected $customerSession;
    protected $_storeManager;
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
        $this->_storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();
         if ($this->customerSession->isLoggedIn())
             {
             $customerGroup = $this->customerSession->getCustomer()->getGroupId();
                if($customerGroup === '5'){
                    $this->_storeManager->setCurrentStore('13'); //Set your desired store ID that you wish to set.
                }
                else{
                    $this->_storeManager->setCurrentStore('1');
                }
             }
    }
}

Body:
You can do this by using Observers, here's an example module for you. this module will change store ID after customer login to the system.

Create registration.php file inside Vendor/Module/

<?php
    \Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
    );

Create module.xml file inside Vendor/Module/etc/

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
            <module name="Vendor_Module" setup_version="2.1.1"></module>
</config>

Create events.xml inside Vendor/Module/etc/frontend/

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_layout_handles" instance="Vendor\Module\Observer\AddHandles" />
    </event>
</config>

Create Handler file for Observer AddHandles.php file inside Vendor/Module/Observer

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;

class AddHandles implements ObserverInterface
{
    protected $customerSession;
    protected $_storeManager;
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
        $this->_storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();

        if ($this->customerSession->isLoggedIn())
        {
            /*
            Here you fetch loggedIn Customer Group and add if condition such as
            if(customerGroup == 'ID/Name of group you desire'){
                $this->_storeManager->setCurrentStore('2'); //Set your desired store ID that you wish to set.
            }
            */
            $this->_storeManager->setCurrentStore('2');
        }
    }
}


问:
How to calculate the time spent when using got?
Example code:

```<code>const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}
</code>```

I wonder if there is a better way?

答:
```<code> let currentDate = moment().format('YYYY/MM/DD HH:mm')
            let dataCalca = moment(dataValue).format('YYYY/MM/DD HH:mm')
            let hours = moment
              .duration(moment(currentDate, 'YYYY/MM/DD HH:mm')
                .diff(moment(dataCalca, 'YYYY/MM/DD HH:mm'))
              ).asHours();
</code>```

So you get the numbers as an hour. You can calculate with that

Body:
Example code:

const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}

I wonder if there is a better way?

Body:
 let currentDate = moment().format('YYYY/MM/DD HH:mm')
            let dataCalca = moment(dataValue).format('YYYY/MM/DD HH:mm')
            let hours = moment
              .duration(moment(currentDate, 'YYYY/MM/DD HH:mm')
                .diff(moment(dataCalca, 'YYYY/MM/DD HH:mm'))
              ).asHours();

So you get the numbers as an hour. You can calculate with that


问:
Create custom column based on condition of how another column value starts with
I have the following dataframe:

Person Number   Error   Department Name Email
Country

CZ  10054609    The identifier 11380151 is used by Veronika Fi...   CZ:Supply Chain Pohořelice 1 Henkel Cosmeticos...   verca.fialova.2001@gmail.com
CZ  10054620    The identifier 11380126 is used by Radmila Val...   CZ:Supply Chain Pohořelice 1 Henkel VAS (CZM63...   rvalova1@seznam.cz
CZ  10054728    The identifier 11805326 is used by Pavel Pecka...   CZ:Supply Chain Pohořelice 3 Levis (CZM630.415...   pavlias000@seznam.cz
CZ  10054699    The identifier 11380232 is used by Sabina Love...   CZ:Supply Chain Pohořelice 3 Marks and Spencer...   s.loveckova@seznam.cz
CZ  10054727    The identifier 11805358 is used by Tereza Holč...   CZ:Supply Chain Pohořelice 3 Levis (CZM630.415...   tholcapko@seznam.cz

I need to create a column named "Error Type" that follows the condition:

If the "Error" column starts with "The Identifier" put the value as "Duplicated"

If the column starts with "The data" put the value as "Transaction"

What would be the best way to solve it?

答:
EDIT:

If there is many different values create dictionary for mapping and set values in loop:

```<code>df=pd.DataFrame({'Error':['The Identifier 1','The Identifier 3','The data dd','another data']})

#add all possible values
mapping = {'The Identifier': 'Duplicated','The data':'Transaction'}

df['Error'] = df['Error'].str.strip()

for k, v in mapping.items():
   df.loc[df['Error'].str.startswith(k), 'new'] = v
print (df)
              Error          new
0  The Identifier 1   Duplicated
1  The Identifier 3   Duplicated
2       The data dd  Transaction
3      another data          NaN
</code>```

Body:
EDIT:

If there is many different values create dictionary for mapping and set values in loop:

df=pd.DataFrame({'Error':['The Identifier 1','The Identifier 3','The data dd','another data']})

#add all possible values
mapping = {'The Identifier': 'Duplicated','The data':'Transaction'}

df['Error'] = df['Error'].str.strip()

for k, v in mapping.items():
   df.loc[df['Error'].str.startswith(k), 'new'] = v
print (df)
              Error          new
0  The Identifier 1   Duplicated
1  The Identifier 3   Duplicated
2       The data dd  Transaction
3      another data          NaN