问:
JSDoc how to add member to type without creating new typedef
Supposedly I have a type called A and B

```<code>/**
 * @typedef A
 * @type {object}
 * @property {String} id this is id A
 * @property {String} name this is name A
 * @property {String} child_id this is id B
 */

/**
 * @typedef B
 * @type {object}
 * @property {String} id this is id A
 * @property {Number} qty this is qty B
 */
</code>```

Is there anyway I can have something like

```<code>{
   id:"a",
   name:"a",
   B:{
     id: "b",
     qty:0
   }
}
</code>```

without rewriting typedef?

I have a function returning Sequelize Object thats why

答:
in the end what I did is using & keyword to intersect

```<code>/**
 * @typedef A
 * @type {object}
 * @property {String} id this is id A
 * @property {String} name this is name A
 * @property {String} child_id this is id B
 */

/**
 * @typedef B
 * @type {object}
 * @property {String} id this is id A
 * @property {Number} qty this is qty B
 */
</code>```

I can say in my definition

```<code>@returns {A & { B : B }}
</code>```

or creating new typedef

```<code>/**
 * @typedef C
 * @type {object}
 * @property {A & {B:B}} B inside A relation
 */
</code>```

Body:
Supposedly I have a type called A and B

/**
 * @typedef A
 * @type {object}
 * @property {String} id this is id A
 * @property {String} name this is name A
 * @property {String} child_id this is id B
 */

/**
 * @typedef B
 * @type {object}
 * @property {String} id this is id A
 * @property {Number} qty this is qty B
 */

Is there anyway I can have something like

{
   id:"a",
   name:"a",
   B:{
     id: "b",
     qty:0
   }
}

without rewriting typedef?

I have a function returning Sequelize Object thats why

Body:
in the end what I did is using & keyword to intersect

/**
 * @typedef A
 * @type {object}
 * @property {String} id this is id A
 * @property {String} name this is name A
 * @property {String} child_id this is id B
 */

/**
 * @typedef B
 * @type {object}
 * @property {String} id this is id A
 * @property {Number} qty this is qty B
 */

I can say in my definition

@returns {A & { B : B }}

or creating new typedef

/**
 * @typedef C
 * @type {object}
 * @property {A & {B:B}} B inside A relation
 */


来源: stackexchange

问:
Finding expired data in aws dynamoDB
I have a requirement where I need to store some data in dynamo-db with a status and a timestamp. Eg. <START, 20180203073000>

Now, above status flips to STOP when I receive a message in SQS. But, to make my system error-proof, I need some mechanism through which I can identify whether a data having START status present in dynamo-db is older than 1 day then set it's status to STOP. So that, it may not wait indefinitly for the message to arrive from SQS.

Is there an aws feature which I can use to achieve this, without polling for data at regular interval ?

答:
Not sure if this will fit your needs, but here is one possibility:

Enable TTL on your DynamoDB table. This will work if your timestamp
data attribute is a Number data type containing time in epoch
format. Once the timestamp expires, the corresponding item is
deleted from the table in the background.

Enable Streams on your DynamoDB table. Items that are deleted by TTL
will be sent to the stream.

Create Trigger that connects DynamoDB stream to Lambda function. In your case the
trigger will receive your entire deleted item.

Modify your record (set 'START' to 'STOP'), remove your timestamp attribute (items with no TTL attribute are not deleted) and re-insert into the table.

This way you will avoid the table scans searching for expired items, but on other side there might be cost associated with lambda execution.

ContentLicense: CC BY-SA 4.0

Title: Finding expired data in aws dynamoDB


问:
How can I stop datatables columns from being responsive?
I'm using this template from Creative-Tim.com.

Here is a link to the file:  drive.google.com/open?id=1EPLpOmM9bNj2-HH-v9rF6HvSoNtTqJtQ

The file is: BS3/examples/new_table.html.

I'm using datatables table and when the browswer window width is descrease, the column headers become responsive where longest table header names appear on top of the sorting arrow, which causes them to look staggered and crooked as not all of them do this because the header names are of different length. How can I keep them all static? I currently have the table set to responsive = false, and have a scrollX bar.

```<code> var table = $('#datatables').DataTable({
     "scrollX": true,
     orderCellsTop: true,
     fixedHeader: true,
     "pageLength": 10,
     responsive: false,
     sDom: 'lrtip'
 });
</code>```

I just want there to be a decent space between columns and for them to stay that way and use scroll for when the page narrows.

答:
After looking at the template I can give you two hints:

a header cell's width is calculated on the go by the plugin, is not rounded and set to something like "74.56px", so for some cells you get the calculated width smaller than it should actually be - the text and the :after don't fit.

changing the font solves the issue

For a quick and dirty fix, and if you would like to keep everything else unchanged - consider change the font to something standard I guess.

Body:
I'm using this template from Creative-Tim.com.

Here is a link to the file:  drive.google.com/open?id=1EPLpOmM9bNj2-HH-v9rF6HvSoNtTqJtQ

The file is: BS3/examples/new_table.html.

I'm using datatables table and when the browswer window width is descrease, the column headers become responsive where longest table header names appear on top of the sorting arrow, which causes them to look staggered and crooked as not all of them do this because the header names are of different length. How can I keep them all static? I currently have the table set to responsive = false, and have a scrollX bar.

 var table = $('#datatables').DataTable({
     "scrollX": true,
     orderCellsTop: true,
     fixedHeader: true,
     "pageLength": 10,
     responsive: false,
     sDom: 'lrtip'
 });

I just want there to be a decent space between columns and for them to stay that way and use scroll for when the page narrows.


问:
Is there a way to see if a value in a 2D array matches any value in another 2D array?
I'm building a battleship game in Javascript and React and I've been stuck on this issue for a while now even after much Googling and StackOverflowing.

Basically my board is a 2D array, with 10 arrays inside of one array. I'm trying to randomly place ships and I'm having difficulties checking if a ship intersects another ship.

Here's what I have for my ships:

```<code>placeShips = () => {
        // Logic to place boats randomly below

        // Checks required before placing a boat:
        // 1. Does the boat go off the board
        // 2. Does the boat overlap another boat
        // 3. If checks above pass then place boat

        let placedPosition = []
        let board = this.state.board.slice()
        let i
        for (i = 0; i < this.state.ships.length; i++) {
            // First randomly select coordinates for where the boat will start
            let xcoord = Math.floor(Math.random() * 10)
            let ycoord = Math.floor(Math.random() * 10)

            // Get positions in array where a boat will be
            let potentialBoat = []
            let newCoords

            let j
            for (j = 0; j < this.state.ships[i].getLength(); j++) {
                newCoords = [xcoord, ycoord + j]
                potentialBoat.push(newCoords)
</code>```

The first for loop repeats for each ship left in my state to place and the second for loop takes a ship's length, gets the intended coordinate ([[0, 1], [0,2]] for a 2 length ship for example) and stores it in the potentialBoat array.

My idea is to use this potentialBoat array and see if there's any [xcoordinate, ycoordinate] that exists already in the placedPosition array and if so, to loop again for the current boat and get new coordinates until they don't intersect.

Is this possible? Or should I rethink my entire implementation? Thanks!

答:
Inside the inner loop, when in the process of creating a ship, consider creating a string representing the coordinates. Eg, for newCoords of 1, 3, create a string 1_3. To validate the location, check to see if that string exists in an array (or Set) of the locations of the validated ships. At the end of the inner loop, once all positions for the length of the ship have been validated, combine the possible-locations into the validated-locations array:

```<code>placeShips = () => {
  const placedPosition = [];
  const board = this.state.board.slice();
  const validatedPositionStrings = []; // <---- Create this array
  for (const ship of this.state.ships) {
    const thisShipLength = ship.getLength();
    tryShip:
    while (true) {
      const thisBoatPossiblePositionStrings = [];
      // Generate ship positions until valid
      const xcoord = Math.floor(Math.random() * 10);
      const ycoord = Math.floor(Math.random() * 10);
      const potentialBoat = [];
      for (let j = 0; j < thisShipLength; j++) {
        // Then check to see if the below position is already in it
        const thisCoordinateString = `${x}_${y}`;
        if (validatedPositionStrings.includes(thisCoordinateString)) {
          // Invalid
          continue tryShip;
        }
        thisBoatPossiblePositionStrings.push(thisCoordinateString);

        // If this point is reached, then this particular coordinate is valid
        // do whatever you need to do:
        const newCoords = [xcoord, ycoord + j];
        potentialBoat.push(newCoords);
      }
      // All positions for ship are valid
      // do something with potentialBoat here?
      // push positions to placedPosition?
      validatedPositionStrings.push(...thisBoatPossiblePositionStrings);
      break;
    }
  }
}
</code>```

It could be made less computationally complex by using a Set instead of an array, but that probably doesn't matter unless there are a very large number of iterations.

It would also be possible to search your array of arrays to see if the position has already been placed, but that would require an unnecessary amount of code IMO.

If possible, you might consider changing your data structure around so that rather than an array of arrays, you have just a single object representing the coordinates, whose values indicate the ship at that position (and possibly other attributes needed for a particular point), eg:

```<code>{
  1_3: { ship: 'destroyer', 'attackedYet': 'false' }
  // ...
</code>```

Such an object would probably be easier to look up and work through than an array of arrays of X-Y pairs.

Body:
I'm building a battleship game in Javascript and React and I've been stuck on this issue for a while now even after much Googling and StackOverflowing.

Basically my board is a 2D array, with 10 arrays inside of one array. I'm trying to randomly place ships and I'm having difficulties checking if a ship intersects another ship.

Here's what I have for my ships:

placeShips = () => {
        // Logic to place boats randomly below

        // Checks required before placing a boat:
        // 1. Does the boat go off the board
        // 2. Does the boat overlap another boat
        // 3. If checks above pass then place boat

        let placedPosition = []
        let board = this.state.board.slice()
        let i
        for (i = 0; i < this.state.ships.length; i++) {
            // First randomly select coordinates for where the boat will start
            let xcoord = Math.floor(Math.random() * 10)
            let ycoord = Math.floor(Math.random() * 10)

            // Get positions in array where a boat will be
            let potentialBoat = []
            let newCoords

            let j
            for (j = 0; j < this.state.ships[i].getLength(); j++) {
                newCoords = [xcoord, ycoord + j]
                potentialBoat.push(newCoords)

The first for loop repeats for each ship left in my state to place and the second for loop takes a ship's length, gets the intended coordinate ([[0, 1], [0,2]] for a 2 length ship for example) and stores it in the potentialBoat array.

My idea is to use this potentialBoat array and see if there's any [xcoordinate, ycoordinate] that exists already in the placedPosition array and if so, to loop again for the current boat and get new coordinates until they don't intersect.

Is this possible? Or should I rethink my entire implementation? Thanks!

Body:
Inside the inner loop, when in the process of creating a ship, consider creating a string representing the coordinates. Eg, for newCoords of 1, 3, create a string 1_3. To validate the location, check to see if that string exists in an array (or Set) of the locations of the validated ships. At the end of the inner loop, once all positions for the length of the ship have been validated, combine the possible-locations into the validated-locations array:

placeShips = () => {
  const placedPosition = [];
  const board = this.state.board.slice();
  const validatedPositionStrings = []; // <---- Create this array
  for (const ship of this.state.ships) {
    const thisShipLength = ship.getLength();
    tryShip:
    while (true) {
      const thisBoatPossiblePositionStrings = [];
      // Generate ship positions until valid
      const xcoord = Math.floor(Math.random() * 10);
      const ycoord = Math.floor(Math.random() * 10);
      const potentialBoat = [];
      for (let j = 0; j < thisShipLength; j++) {
        // Then check to see if the below position is already in it
        const thisCoordinateString = `${x}_${y}`;
        if (validatedPositionStrings.includes(thisCoordinateString)) {
          // Invalid
          continue tryShip;
        }
        thisBoatPossiblePositionStrings.push(thisCoordinateString);

        // If this point is reached, then this particular coordinate is valid
        // do whatever you need to do:
        const newCoords = [xcoord, ycoord + j];
        potentialBoat.push(newCoords);
      }
      // All positions for ship are valid
      // do something with potentialBoat here?
      // push positions to placedPosition?
      validatedPositionStrings.push(...thisBoatPossiblePositionStrings);
      break;
    }
  }
}

It could be made less computationally complex by using a Set instead of an array, but that probably doesn't matter unless there are a very large number of iterations.

It would also be possible to search your array of arrays to see if the position has already been placed, but that would require an unnecessary amount of code IMO.

If possible, you might consider changing your data structure around so that rather than an array of arrays, you have just a single object representing the coordinates, whose values indicate the ship at that position (and possibly other attributes needed for a particular point), eg:

{
  1_3: { ship: 'destroyer', 'attackedYet': 'false' }
  // ...

Such an object would probably be easier to look up and work through than an array of arrays of X-Y pairs.


问:
Shell script mode automatically at each emacs start
Each time when I edit bash script I type a command M-x shell-script-mode. And then I get nice shell code higlighting. How to get it automatically each time I start emacs so I do not have to type the command. When I added (shell-script-mode) to init.el it did not help.

答:
You can set the default major mode to be whatever you want by adding

```<code>(setq-default major-mode 'shell-script-mode)
</code>```

to your init file. That will ensure that any newly created buffer will be in shell-script-mode unless its mode is specified otherwise (e.g. through auto-mode-alist). Whether it's a good idea or not, I don't know: I probably would not want that to be my default setting - but to each her/his own.

Body:
You can set the default major mode to be whatever you want by adding

(setq-default major-mode 'shell-script-mode)

to your init file. That will ensure that any newly created buffer will be in shell-script-mode unless its mode is specified otherwise (e.g. through auto-mode-alist). Whether it's a good idea or not, I don't know: I probably would not want that to be my default setting - but to each her/his own.


问:
How does nodejs load .env files?
path：

```<code>- index.js
- .env.production
- .env.development
</code>```

.env.production

```<code>TOKEN = 'prod'
</code>```

.env.development

```<code>TOKEN = 'dev'
</code>```

index.js

console.log(process.env.TOKEN )
```

<p>My desired effect:</p>

```$ npm run dev
> dev

$ npm run prod
> prod
```

Development environment:

windows10

vscode

答: dotenv   meets    the     needs.

Title: How does nodejs load .env files?

Body:
path：

- index.js
- .env.production
- .env.development

.env.production

TOKEN = 'prod'

.env.development

TOKEN = 'dev'

index.js

console.log(process.env.TOKEN )

My desired effect:

$ npm run dev
> dev

$ npm run prod
> prod

Development environment:

windows10

vscode

Body: dotenv   meets    the     needs.


问:
How to restrict matches to the first 5 lines of an email body using regex in GAS
I'm using the following script which is working correctly to pull 2 fields out of an email body.

This is causing the script execution time to increase significantly due to the amount of content in the body. Is there a way to make this search through only the first 5 lines of the email body?

First lines of e-mail:

Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 15 minutes.
```

<p>Script:</p>

```//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
if (threads && threads.length > 0) {
  var message = threads[0].getMessages()[0];
  // Get the first email message of a threads
  var tmp,
    subject = message.getSubject(),
    content = message.getPlainBody();
  // Get the plain text body of the email message
  // You may also use getRawContent() for parsing HTML

  // Implement Parsing rules using regular expressions
  if (content) {

    tmp = content.match(/Date Tripped:\s*([:\w\s]+)\r?\n/);
    var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

    tmp = content.match(/Business Date:\s([\w\s]+\(\w+\))/);
    var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
  }
}
```

答:
@ggorlen's answer is not precise, to my taste. Let's have a look at regex01

My problem with (?:.*\r?\n){0,5} is this: in english this regex says:

```<code>Take any number of characters (0 or more) ending with a newline.
Do this between 0 and 5 times.
</code>```

Which means any empty string matches. If you would do a global match, there's a lot of those.

So, how could you grab the first 5 lines? Be exact! So something like

```<code>^([^\r\n]+\r?\n){5}
</code>```

See regex101

P.S. @ggorlen mentioned I left the default multiline matching on in regex101, and he's right about that. Your preference may vary: choosing between ignoring messages with less than 5 lines and accepting strings with empty lines depends on your particular case.

P.S.2 I've adapted my wording and disabled the multiline and global settings in regex101 to display my concerns with it.

Body:
I'm using the following script which is working correctly to pull 2 fields out of an email body.

This is causing the script execution time to increase significantly due to the amount of content in the body. Is there a way to make this search through only the first 5 lines of the email body?

First lines of e-mail:

Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 15 minutes.

Script:

//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
if (threads && threads.length > 0) {
  var message = threads[0].getMessages()[0];
  // Get the first email message of a threads
  var tmp,
    subject = message.getSubject(),
    content = message.getPlainBody();
  // Get the plain text body of the email message
  // You may also use getRawContent() for parsing HTML

  // Implement Parsing rules using regular expressions
  if (content) {

    tmp = content.match(/Date Tripped:\s*([:\w\s]+)\r?\n/);
    var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

    tmp = content.match(/Business Date:\s([\w\s]+\(\w+\))/);
    var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
  }
}

Body:
@ggorlen's answer is not precise, to my taste. Let's have a look at regex01

My problem with (?:.*\r?\n){0,5} is this: in english this regex says:

Take any number of characters (0 or more) ending with a newline.
Do this between 0 and 5 times.

Which means any empty string matches. If you would do a global match, there's a lot of those.

So, how could you grab the first 5 lines? Be exact! So something like

^([^\r\n]+\r?\n){5}

See regex101

P.S. @ggorlen mentioned I left the default multiline matching on in regex101, and he's right about that. Your preference may vary: choosing between ignoring messages with less than 5 lines and accepting strings with empty lines depends on your particular case.

P.S.2 I've adapted my wording and disabled the multiline and global settings in regex101 to display my concerns with it.


问:
HMR not working with Laravel Mix in Docker
I am having some problems setting up Hot Module Reloading in Laravel Mix inside a Docker container.

I have the following Dockerfile:

```<code>FROM php:7.4.0-fpm

RUN curl -sL https://deb.nodesource.com/setup_13.x | bash

RUN apt-get update && \
    apt-get install -y -q --no-install-recommends \
    nano apt-utils curl unzip default-mysql-client nodejs build-essential git \
    libcurl4-gnutls-dev libmcrypt-dev libmagickwand-dev \
    libwebp-dev libjpeg-dev libpng-dev libxpm-dev \
    libfreetype6-dev libaio-dev zlib1g-dev libzip-dev && \
    echo 'umask 002' >> /root/.bashrc  && \
    apt-get clean

# Docker PHP Extensions
RUN docker-php-ext-install -j$(nproc) iconv gettext gd mysqli curl pdo pdo_mysql zip && \
    docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ && \
    docker-php-ext-configure curl --with-curl

WORKDIR /var/www/html

COPY . /var/www/html

EXPOSE 80
</code>```

Which I am building using the below docker-compose.yml file.

```<code>  # The Application
  app:
    build:
      context: ./
      dockerfile: app.dockerfile
    working_dir: /var/www/html
    volumes:
      - ./webroot:/var/www/html
    environment:
      - "DB_PORT=3306"
      - "DB_HOST=database"
      - CHOKIDAR_USEPOLLING=true

  # The Web Server
  web:
    build:
      context: ./
      dockerfile: web.dockerfile
    working_dir: /var/www/html
    volumes_from:
      - app
    ports:
      - 80:80
</code>```

In previous Node.js apps, I have copied over the data inside the dockerfile, and mounted the volume in the compose file, however this doesn't seem to be having the same effect with Laravel.

I am seeing the below output in Git Bash, however the web pages are not reloading with changes at all after I run npm run hot inside the container, not even with a manual refresh:

Despite this, npm run watch-poll, which I have used previously, still works as expected.

Typically I see logs in the console from HMR and WDS inside the browser when viewing the application. However in this situation I am not seeing any outputs.

Below I have also included my webpack.mix.js file. I have been messing around with some of the options, such as the port and host, as I know they need to be configured a certain way when running inside a container. Any help would be appreciated as I am struggling to work out where I am going wrong.

```<code>mix.options({
    hmrOptions: {
        host: 'localhost',
        port: '80'
    },
});

mix.webpackConfig({
    mode: "development",
    devtool: "inline-source-map",
    devServer: {
        disableHostCheck: true,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        host: "0.0.0.0",
        port: 80
    },
});
</code>```

Edit:

Error output when running npm run hot after setting both host values to web:

```<code>> @ hot /var/www/html
> cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js

events.js:298
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRNOTAVAIL: address not available 172.25.0.4:80
    at Server.setupListenHandle [as _listen2] (net.js:1292:21)
    at listenInCluster (net.js:1357:12)
    at GetAddrInfoReqWrap.doListen [as callback] (net.js:1496:7)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:69:10)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1336:8)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  code: 'EADDRNOTAVAIL',
  errno: -99,
  syscall: 'listen',
  address: '172.25.0.4',
  port: 80
}
</code>```

答:
the problem is in

```<code>mix.options({
    hmrOptions: {
        host: 'localhost',
        port: '80'
    },
});
</code>```

you can not use localhost since it is refer to your APP container in this case, what should you do is using web instead since compose will resolve the service names for you:

```<code>mix.options({
    hmrOptions: {
        host: 'web',
        port: '80'
    },
});

mix.webpackConfig({
    mode: "development",
    devtool: "inline-source-map",
    devServer: {
        disableHostCheck: true,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        host: "web",
        port: 80
    },
});
</code>```

Body:
I am having some problems setting up Hot Module Reloading in Laravel Mix inside a Docker container.

I have the following Dockerfile:

FROM php:7.4.0-fpm

RUN curl -sL https://deb.nodesource.com/setup_13.x | bash

RUN apt-get update && \
    apt-get install -y -q --no-install-recommends \
    nano apt-utils curl unzip default-mysql-client nodejs build-essential git \
    libcurl4-gnutls-dev libmcrypt-dev libmagickwand-dev \
    libwebp-dev libjpeg-dev libpng-dev libxpm-dev \
    libfreetype6-dev libaio-dev zlib1g-dev libzip-dev && \
    echo 'umask 002' >> /root/.bashrc  && \
    apt-get clean

# Docker PHP Extensions
RUN docker-php-ext-install -j$(nproc) iconv gettext gd mysqli curl pdo pdo_mysql zip && \
    docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ && \
    docker-php-ext-configure curl --with-curl

WORKDIR /var/www/html

COPY . /var/www/html

EXPOSE 80

Which I am building using the below docker-compose.yml file.

  # The Application
  app:
    build:
      context: ./
      dockerfile: app.dockerfile
    working_dir: /var/www/html
    volumes:
      - ./webroot:/var/www/html
    environment:
      - "DB_PORT=3306"
      - "DB_HOST=database"
      - CHOKIDAR_USEPOLLING=true

  # The Web Server
  web:
    build:
      context: ./
      dockerfile: web.dockerfile
    working_dir: /var/www/html
    volumes_from:
      - app
    ports:
      - 80:80

In previous Node.js apps, I have copied over the data inside the dockerfile, and mounted the volume in the compose file, however this doesn't seem to be having the same effect with Laravel.

I am seeing the below output in Git Bash, however the web pages are not reloading with changes at all after I run npm run hot inside the container, not even with a manual refresh:

Despite this, npm run watch-poll, which I have used previously, still works as expected.

Typically I see logs in the console from HMR and WDS inside the browser when viewing the application. However in this situation I am not seeing any outputs.

Below I have also included my webpack.mix.js file. I have been messing around with some of the options, such as the port and host, as I know they need to be configured a certain way when running inside a container. Any help would be appreciated as I am struggling to work out where I am going wrong.

mix.options({
    hmrOptions: {
        host: 'localhost',
        port: '80'
    },
});

mix.webpackConfig({
    mode: "development",
    devtool: "inline-source-map",
    devServer: {
        disableHostCheck: true,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        host: "0.0.0.0",
        port: 80
    },
});

Edit:

Error output when running npm run hot after setting both host values to web:

> @ hot /var/www/html
> cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js

events.js:298
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRNOTAVAIL: address not available 172.25.0.4:80
    at Server.setupListenHandle [as _listen2] (net.js:1292:21)
    at listenInCluster (net.js:1357:12)
    at GetAddrInfoReqWrap.doListen [as callback] (net.js:1496:7)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:69:10)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1336:8)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  code: 'EADDRNOTAVAIL',
  errno: -99,
  syscall: 'listen',
  address: '172.25.0.4',
  port: 80
}

Body:
the problem is in

mix.options({
    hmrOptions: {
        host: 'localhost',
        port: '80'
    },
});

you can not use localhost since it is refer to your APP container in this case, what should you do is using web instead since compose will resolve the service names for you:

mix.options({
    hmrOptions: {
        host: 'web',
        port: '80'
    },
});

mix.webpackConfig({
    mode: "development",
    devtool: "inline-source-map",
    devServer: {
        disableHostCheck: true,
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        host: "web",
        port: 80
    },
});


问:
How to check checkbox array values exist from database PHP Laravel?
I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.

Controller :

```<code>public function edit($id)
{
    $region = Region::find($id);
    $countries = Country::all();
    $country_region = DB::table('regions')
        ->select('countries.id', 'countries.name')
        ->join('country_region', 'regions.id', '=', 'country_region.region_id')
        ->join('countries', 'country_region.country_id', '=', 'countries.id')
        ->where('regions.id', '=', $id)
        ->get();

    $items = array(
        'region' => $region,
        'countries' => $countries,
        'country_region' => $country_region,
    );

    return view('admin.region.edit')->with($items);
}
</code>```

blade

```<code><div class="form-group">
    <label>Choose Country</label>
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>
</div>
</code>```

As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :

```<code>array_keys() expects parameter 1 to be array, object given
</code>```

Database :

Country Region Table :

Region Table :

Country Table :

答:
$country_region is not an array in your controller. It's an Eloquent collection. To change it to array you simply use toArray() on it.

In your controller, replace this:

```<code>$items = array(
            'region' => $region,
            'countries' => $countries,
            'country_region' => $country_region,
    );
</code>```

with this:

```<code>$items = array(
            'region' => $region,
            'countries' => $countries,
            'country_region' => $country_region->toArray(),
    );
</code>```

Body:
I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.

Controller :

public function edit($id)
{
    $region = Region::find($id);
    $countries = Country::all();
    $country_region = DB::table('regions')
        ->select('countries.id', 'countries.name')
        ->join('country_region', 'regions.id', '=', 'country_region.region_id')
        ->join('countries', 'country_region.country_id', '=', 'countries.id')
        ->where('regions.id', '=', $id)
        ->get();

    $items = array(
        'region' => $region,
        'countries' => $countries,
        'country_region' => $country_region,
    );

    return view('admin.region.edit')->with($items);
}

blade

    Choose Country
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>

As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :

array_keys() expects parameter 1 to be array, object given

Database :

Country Region Table :

Region Table :

Country Table :

Body:
$country_region is not an array in your controller. It's an Eloquent collection. To change it to array you simply use toArray() on it.

In your controller, replace this:

$items = array(
            'region' => $region,
            'countries' => $countries,
            'country_region' => $country_region,
    );

with this:

$items = array(
            'region' => $region,
            'countries' => $countries,
            'country_region' => $country_region->toArray(),
    );


问:
configure keeps finding the wrong GLib
My cygwin has glib1.2 and glib2.0 installed. My configure.in contains the following lines:

```<code>AM_PATH_GLIB_2_0(,
[
        AC_DEFINE(HAVE_GLIB)
        LIBS="$LIBS $GLIB_LIBS"
        CFLAGS="$CFLAGS $GLIB_CFLAGS"
], [
        AC_MSG_ERROR([No glib. Bad.  Get it at:  http://www.gtk.org/. ])
])
</code>```

Unfortunately, the GLIB_CONFIG macro contains:

```<code>echo -I${prefix}/include/glib-1.2
</code>```

So whenever I do a ./configure, my makefile returns to this:

```<code>gcc  -g -O2 -I/usr/include/glib-1.2
</code>```

...and then all the code calling 2.x complains. I can fix this with some manual edits to the resulting makefile:

```<code>GLIB_CFLAGS = -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include
GLIB_CONFIG = /usr/bin/glib-config
GLIB_LIBS = -L/usr/lib -lglib-2.0
</code>```

... but avoiding that is why you use autoconf in the first place. Questions:

is there another GLIB_CONFIG that should exist somewhere? should 2.0 have changed this one on install? I poked about in /usr/bin, and that's the only gl* in there.

I'm not sure I understand where in the configure process GLIB_CONFIG being called

答:
I personally would use pkg-config in configure.ac by calling the PKG_CHECK_MODULES macro:

```<code>m4_pattern_forbid([PKG_CHECK_MODULES])dnl
PKG_CHECK_MODULES([GLIB20], [glib-2.0], [], [dnl
  AC_MSG_ERROR([
   +===================================================+
   | Could not find the required glib-2.0 dev package. |
   | Install the glib2-devel or libglib2-dev package   |
   | or from http://www.gtk.org/ directly.             |
   +===================================================+
])
])
</code>```

The m4_pattern_forbid prevents autoreconf from succeeding without the PKG_CHECK_MODULES macro being defined, and you can adapt the error message to your heart's content.

The PKG_CHECK_MODULES macro works for a huge number of libraries, and it clearly defines which API you are looking for. Just check for /usr/lib64/pkgconfig/*.pc files (the exact location for your system might vary).

In your Makefile.am or Makefile-files file, you can then add the GLIB20 flags like

```<code>bin_PROGRAMS  = foo
foo_SOURCES   = foo-main.c
foo_CPPFLAGS  = $(top_srcdir)/include
foo_LDADD     = $(top_builddir)/libfoo.la

foo_CPPFLAGS += $(GLIB20_CFLAGS)
foo_LDADD    += $(GLIB20_LIBS)
</code>```

Title: configure keeps finding the wrong GLib

Body:
My cygwin has glib1.2 and glib2.0 installed. My configure.in contains the following lines:

AM_PATH_GLIB_2_0(,
[
        AC_DEFINE(HAVE_GLIB)
        LIBS="$LIBS $GLIB_LIBS"
        CFLAGS="$CFLAGS $GLIB_CFLAGS"
], [
        AC_MSG_ERROR([No glib. Bad.  Get it at:  http://www.gtk.org/. ])
])

Unfortunately, the GLIB_CONFIG macro contains:

echo -I${prefix}/include/glib-1.2

So whenever I do a ./configure, my makefile returns to this:

gcc  -g -O2 -I/usr/include/glib-1.2

...and then all the code calling 2.x complains. I can fix this with some manual edits to the resulting makefile:

GLIB_CFLAGS = -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include
GLIB_CONFIG = /usr/bin/glib-config
GLIB_LIBS = -L/usr/lib -lglib-2.0

... but avoiding that is why you use autoconf in the first place. Questions:

is there another GLIB_CONFIG that should exist somewhere? should 2.0 have changed this one on install? I poked about in /usr/bin, and that's the only gl* in there.

I'm not sure I understand where in the configure process GLIB_CONFIG being called

Body:
I personally would use pkg-config in configure.ac by calling the PKG_CHECK_MODULES macro:

m4_pattern_forbid([PKG_CHECK_MODULES])dnl
PKG_CHECK_MODULES([GLIB20], [glib-2.0], [], [dnl
  AC_MSG_ERROR([
   +===================================================+
   | Could not find the required glib-2.0 dev package. |
   | Install the glib2-devel or libglib2-dev package   |
   | or from http://www.gtk.org/ directly.             |
   +===================================================+
])
])

The m4_pattern_forbid prevents autoreconf from succeeding without the PKG_CHECK_MODULES macro being defined, and you can adapt the error message to your heart's content.

The PKG_CHECK_MODULES macro works for a huge number of libraries, and it clearly defines which API you are looking for. Just check for /usr/lib64/pkgconfig/*.pc files (the exact location for your system might vary).

In your Makefile.am or Makefile-files file, you can then add the GLIB20 flags like

bin_PROGRAMS  = foo
foo_SOURCES   = foo-main.c
foo_CPPFLAGS  = $(top_srcdir)/include
foo_LDADD     = $(top_builddir)/libfoo.la

foo_CPPFLAGS += $(GLIB20_CFLAGS)
foo_LDADD    += $(GLIB20_LIBS)


问:
Introducing an array to store scores in Java
The question I am working on is:

Write a program that:

asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).

Sample program behavior / output:

How many exams scores do you have to enter? 5

Enter score #1: 95.0

Enter score #2: 92.0

Enter score #3: 68.0

Enter score #4: 72.0

Enter score #5: 70.0

The average score is: 79.4
There are 2 scores larger than the average.

This is my code:

```<code>import java.util.Scanner;

public class testee {

    public static void main(String[] args) {

        int examnum = -1;
        Scanner scan = new Scanner (System.in);

        while (examnum<0) {
            System.out.println("How many exam scores do you have to enter?");

            examnum = scan.nextInt( );
        }

        for (int i=1; i<=examnum; i++) {
            System.out.println("Enter score #" + i + ": ");

            for (int a=1; a<=i; a++) {
                a = scan.nextInt();
            }
        }

    }
}
</code>```

What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.

答:
First prompt looks good however there is one small problem.

Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?

It's always nice to inform the User of any invalid entry.

To place items into an Array you need to declare that array and initialize it to the proper size:

```<code>int[] scoresArray = new int[examnum];
</code>```

Think about this, where do you think this line of code should be placed?

Hint: You need to ensure that the required array size is already properly established.

Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?

Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).

If you want to add an element to your array, where do you think would be a great place in your code to do that?

Hint: int score = scan.nextInt(); scoresArray[i] = score;.

Things to consider:

When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?

Yes, you can nest while loops within a for loop and visa-versa.

Body:
The question I am working on is:

Write a program that:

asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).

Sample program behavior / output:

How many exams scores do you have to enter? 5

Enter score #1: 95.0

Enter score #2: 92.0

Enter score #3: 68.0

Enter score #4: 72.0

Enter score #5: 70.0

The average score is: 79.4
There are 2 scores larger than the average.

This is my code:

import java.util.Scanner;

public class testee {

    public static void main(String[] args) {

        int examnum = -1;
        Scanner scan = new Scanner (System.in);

        while (examnum<0) {
            System.out.println("How many exam scores do you have to enter?");

            examnum = scan.nextInt( );
        }

        for (int i=1; i<=examnum; i++) {
            System.out.println("Enter score #" + i + ": ");

            for (int a=1; a<=i; a++) {
                a = scan.nextInt();
            }
        }

    }
}

What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.

Body:
First prompt looks good however there is one small problem.

Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?

It's always nice to inform the User of any invalid entry.

To place items into an Array you need to declare that array and initialize it to the proper size:

int[] scoresArray = new int[examnum];

Think about this, where do you think this line of code should be placed?

Hint: You need to ensure that the required array size is already properly established.

Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?

Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).

If you want to add an element to your array, where do you think would be a great place in your code to do that?

Hint: int score = scan.nextInt(); scoresArray[i] = score;.

Things to consider:

When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?

Yes, you can nest while loops within a for loop and visa-versa.


问:
How to initialize a LiveData<> object to avoid a NullPointerException when trying to return a single record
I want to pull a single record from my Room database and can do so with a query in my Dao:

```<code>@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
LiveData<Scenario> getScenario(long scenarioId);
</code>```

I only want to be update it in my ViewModel when there is a change:

```<code>final Observer<Scenario> scenarioObserver = new Observer<Scenario>() {
    @Override
    public void onChanged(Scenario scenario) {
        Log.d(TAG, "onChanged: " + scenario.getId());
    }
};
</code>```

When running I get an error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference
</code>```

but I can't initialize it the variable:

```<code>scenario = new LiveData<Scenario>();
</code>```

because I get an error: LiveData is abstract; cannot be abstract.

How do I deal with this situation? How do I initialize the LiveData object?

UPDATE

I get this error from the compiler:

```<code>error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<com.behaviorotg.tokensystem1.model.ScenarioBehaviorTokenLog>).
</code>```

On this line:

```<code>@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
MutableLiveData<Scenario> getScenario (long scenarioId);
</code>```

答:
You don't need to instantiate a live data here, just use the same instance that is returned by the query method.

If you need to instantiate it you can use MutableLiveData, but if you want to pass it from ViewModel to Activity/Fragment expose it as LiveData like this:

```<code> // change it from main thread with set(value) and from other threads with post(value)
private MutableLiveData<Scenario> liveData = MutableLiveData()
// doing this will ensure that your view can't change its vlaue
public LiveData getLiveData() {
    return liveData
}
</code>```

Body:
I want to pull a single record from my Room database and can do so with a query in my Dao:

@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
LiveData<Scenario> getScenario(long scenarioId);

I only want to be update it in my ViewModel when there is a change:

final Observer<Scenario> scenarioObserver = new Observer<Scenario>() {
    @Override
    public void onChanged(Scenario scenario) {
        Log.d(TAG, "onChanged: " + scenario.getId());
    }
};

When running I get an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference

but I can't initialize it the variable:

scenario = new LiveData<Scenario>();

because I get an error: LiveData is abstract; cannot be abstract.

How do I deal with this situation? How do I initialize the LiveData object?

UPDATE

I get this error from the compiler:

error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<com.behaviorotg.tokensystem1.model.ScenarioBehaviorTokenLog>).

On this line:

@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
MutableLiveData<Scenario> getScenario (long scenarioId);

Body:
You don't need to instantiate a live data here, just use the same instance that is returned by the query method.

If you need to instantiate it you can use MutableLiveData, but if you want to pass it from ViewModel to Activity/Fragment expose it as LiveData like this:

 // change it from main thread with set(value) and from other threads with post(value)
private MutableLiveData<Scenario> liveData = MutableLiveData()
// doing this will ensure that your view can't change its vlaue
public LiveData getLiveData() {
    return liveData
}


问:
Upload an Image from SD card to a Lamp Server
I am trying to upload an image from the android device to a LAMP server where i will handle the form through PHP.

i have an image view which has been set with the image path from the SD card

i want to upload this image on click of a button

答:
here's a link that will guide you

http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html

ContentLicense: CC BY-SA 3.0


问:
p5 show div as mouse moves
so I have a div and I want it at first to be covered by a black canvas and then as im moving the mouse clear the black color with shape of an ellipse in order to show the div contents. I just got it working with single pixels but not with the shape of an ellipse. help

```<code>  <div id="mainContent">
  <div> <img id="mainImage" src="tmpfiles/lpz2.jpg"></div>
  </div>
</code>```

my sketch.js

```<code>function setup(){
  var canvas = createCanvas(100,100);
  canvas.id("sketch-container")
  canvas.parent("mainContent");
  background(0);

}
function draw(){
  var transparent = color("#1C00ff00")
  var x = mouseX;
  var y = mouseY;
  set(x,y,transparent);
  updatePixels();
}
</code>```

my css

```<code>/*main content */
#mainContent{
  /* background: #000000; */
  height: 100vh;
  position: relative;
  overflow: hidden;
}
#sketch-container{
position: absolute;
  width: 100% !important;
  height: auto !important;
}
#mainImage{
  width: 100%;
  height: auto;
  position: absolute;
}
</code>```

答:
One way of achieving this is to use blend() and blendMode; blendMode(REMOVE) specifically because it

removes pixels from B with the alpha strength of A,

Where B are the pixels already being displayed (the black background of the canvas) and A are the source pixels (the shapes drawn)

You can create a transparent mask layer to draw on and use a color with some alpha value (in your case completely solid) to make the shapes you want; then use the blend method with the mask layer as a source and REMOVE as the blend mode, like this:

let maskCanvas

function setup(){
  var canvas = createCanvas(100,100);
  canvas.id("sketch-container")
  canvas.parent("mainContent");
  background(0);
  maskCanvas = createGraphics(100, 100)
}

function draw(){
  maskCanvas.fill('red') // Any color will do
  maskCanvas.ellipse(mouseX, mouseY, 10, 5)
  blend(maskCanvas, 0, 0, 100, 100, 0, 0, 100, 100, REMOVE);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*main content */
#mainContent{
  /* background: #000000; */
  height: 100vh;
  position: relative;
  overflow: hidden;
}
#sketch-container{
position: absolute;
  width: 100% !important;
  height: auto !important;
}
#mainImage{
  width: 100%;
  height: auto;
  position: absolute;
}</code>```

```

Title: p5 show div as mouse moves

Body:
so I have a div and I want it at first to be covered by a black canvas and then as im moving the mouse clear the black color with shape of an ellipse in order to show the div contents. I just got it working with single pixels but not with the shape of an ellipse. help

my sketch.js

function setup(){
  var canvas = createCanvas(100,100);
  canvas.id("sketch-container")
  canvas.parent("mainContent");
  background(0);

}
function draw(){
  var transparent = color("#1C00ff00")
  var x = mouseX;
  var y = mouseY;
  set(x,y,transparent);
  updatePixels();
}

my css

/*main content */
#mainContent{
  /* background: #000000; */
  height: 100vh;
  position: relative;
  overflow: hidden;
}
#sketch-container{
position: absolute;
  width: 100% !important;
  height: auto !important;
}
#mainImage{
  width: 100%;
  height: auto;
  position: absolute;
}

Body:
One way of achieving this is to use blend() and blendMode; blendMode(REMOVE) specifically because it

removes pixels from B with the alpha strength of A,

Where B are the pixels already being displayed (the black background of the canvas) and A are the source pixels (the shapes drawn)

You can create a transparent mask layer to draw on and use a color with some alpha value (in your case completely solid) to make the shapes you want; then use the blend method with the mask layer as a source and REMOVE as the blend mode, like this:

let maskCanvas

function setup(){
  var canvas = createCanvas(100,100);
  canvas.id("sketch-container")
  canvas.parent("mainContent");
  background(0);
  maskCanvas = createGraphics(100, 100)
}

function draw(){
  maskCanvas.fill('red') // Any color will do
  maskCanvas.ellipse(mouseX, mouseY, 10, 5)
  blend(maskCanvas, 0, 0, 100, 100, 0, 0, 100, 100, REMOVE);
}

/*main content */
#mainContent{
  /* background: #000000; */
  height: 100vh;
  position: relative;
  overflow: hidden;
}
#sketch-container{
position: absolute;
  width: 100% !important;
  height: auto !important;
}
#mainImage{
  width: 100%;
  height: auto;
  position: absolute;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.min.js"></script>

 <div id="mainContent">
  <div> <img id="mainImage" src="https://picsum.photos/200"></div>
  </div>


问:
Typescript: ERROR TypeError: Cannot set property '[variable]' of undefined
I have an array of LoginData objects, one attribute of which is email. The following function takes a string parameter and is supposed to check whether there already exists a LoginData object with a matching email adress. Here is the code:

```<code>import { Injectable } from '@angular/core';
import { LOGINDATA } from '../mock-users';

@Injectable({
  providedIn: 'root'
})

export class CheckLoginDataService {
  emailString: string = "";
  loginData = LOGINDATA;

  checkLoginData(str: string){
    let emailExists: boolean = false;

    this.loginData.forEach( function(LoginData){
      this.emailString = LoginData.email;
      console.log(this.emailString);

      if (str === this.emailString){
        emailExists = true;
      }
    })

    return emailExists;
  }
}
</code>```

When I run my code I the Error:

"ERROR TypeError: Cannot set property 'emailString' of undefined".

I looked at the other stackoverflow threads discussing this problems and they suggest to initialize "emailString" (in my case). I think I am doing that in the beginning already - what am I doing wrong?

答:
Change

this.loginData.forEach( function(LoginData){

to

this.loginData.forEach((LoginData) => {

Using arrow functions within a class binds this within the function to the class instance itself.

Body:
I have an array of LoginData objects, one attribute of which is email. The following function takes a string parameter and is supposed to check whether there already exists a LoginData object with a matching email adress. Here is the code:

import { Injectable } from '@angular/core';
import { LOGINDATA } from '../mock-users';

@Injectable({
  providedIn: 'root'
})

export class CheckLoginDataService {
  emailString: string = "";
  loginData = LOGINDATA;

  checkLoginData(str: string){
    let emailExists: boolean = false;

    this.loginData.forEach( function(LoginData){
      this.emailString = LoginData.email;
      console.log(this.emailString);

      if (str === this.emailString){
        emailExists = true;
      }
    })

    return emailExists;
  }
}

When I run my code I the Error:

"ERROR TypeError: Cannot set property 'emailString' of undefined".

I looked at the other stackoverflow threads discussing this problems and they suggest to initialize "emailString" (in my case). I think I am doing that in the beginning already - what am I doing wrong?


问:
how to use regular expression for this below stuff in php
I have a database of more than 70000 records and its primary key value started from 1 single digit.

So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.

But my problem is i want this type of things having 9 letters in the string and the pattern is like this

```<code>1    - nm0000001
9    - nm0000009
10   - nm0000010
2020 - nm0002020
</code>```

And from the above pattern i want only the digits like 1,9,10,2020 in php.

答:
Here:

```<code>$i = (int)substr($input, 2);
</code>```

No reason to use regexes at all.

Anyway, if you're insisting on using regexp, then:

```<code>$input = 'nm0002020';
preg_match('~0*(\d+)$~', $input, $matches);
var_dump($matches[1]);
</code>```

Body:
I have a database of more than 70000 records and its primary key value started from 1 single digit.

So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.

But my problem is i want this type of things having 9 letters in the string and the pattern is like this

1    - nm0000001
9    - nm0000009
10   - nm0000010
2020 - nm0002020

And from the above pattern i want only the digits like 1,9,10,2020 in php.

Body:
Here:

$i = (int)substr($input, 2);

No reason to use regexes at all.

Anyway, if you're insisting on using regexp, then:

$input = 'nm0002020';
preg_match('~0*(\d+)$~', $input, $matches);
var_dump($matches[1]);


问:
Order of promise array in Promise.allSettled and order in which database transactions are created?
In the following code,

```<code>Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );
</code>```

promises entry_save and save_state are both readwrite database transactions and get_HTML is readonly. The two readwrite transactions could be combined together but that complicates the undo/redo chain that is maintained and it ties the success and rollback of the two together which is undesired.

The entry_save transaction needs to write before the save_state transaction.  Before moving entry_save into the Promise.allSettled that is how it worked because the entry_save transaction was created prior to those of the others.  This MDN article explains how the order in which  requests are performed is based upon when the transactions are created independently of the order in which the requests are made.

My question is does the synchronous code of each promise process in the order in which it is placed in the array, such that placing entry_save first will always result in its transaction being created first and guaranteeing its database requests will be performed first?

Although it works and is quick enough, I'd prefer to not do this:

```<code>entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );
</code>```

If it matters, that's not the exactly the way it is written, it's more consistent with:

entry_save().then( intermediate ); where intermediate invokes the Promise.allSettled.

Thank you.

To clarify a bit, below is the example given in the above cited MDN document.

```<code>var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
var objectStore2 = trans2.objectStore("foo")
var objectStore1 = trans1.objectStore("foo")
objectStore2.put("2", "key");
objectStore1.put("1", "key");
</code>```

After the code is executed the object store should contain the value "2", since trans2 should run after trans1.

If entry_save creates trans1 and save_state create trans2, and all in the synchronous code of the functions, meaning not within an onsuccess or onerror handler of a database request or something similar, will the MDN example not hold?

Thus, where @jfriend00 writes,

The functions are called in the order they are placed in the array,
  but that only determines the order in which the asynchronous are
  started.

will this order the timing of the write requests by that of the creation of the transactions, since the transactions are created in the synchronous code before the asynchronous can commence?

I'd like to test it but I'm not sure how.  If two nearly identical promises are used in a Promise.allSettled, how can the write request of the first created transaction be delayed such that it takes place after the write request of the second created transaction, to test if it will be written first? A setTimeout should terminate the transaction. Perhaps a long-running synchronous loop placed before the request.

The code at the very end of this question may better illustrate more precisely what I have attempted to ask. It takes the MDN example in the article cited above and spreads it across two promises placed in a Promise.allSettled, both of which attempt to write to the same object store from within the onsuccess event of a get request.

The question was will the same principle in the article of the first transaction created writing before the second transaction created, regardless of the order the requests are made, still hold in this set up. Since the synchronous portions of the promises will process in the order the promises are placed in the array, the transaction in promise p_1 will be created before that of p_2.  However, the put request in the onsuccess event of the get request in p_1 is delayed by the loop building a large string. The question is will p_1 still write before p_2?

In experimenting with this, I cannot get p_2 to write before p_1. Thus, it appears that the MDN example applies even in this type of set up.  However, I cannot be sure of why because I don't understand how the JS code is really interpreted/processed.

For example, why can the req.onsuccess function be defined after the request is made? I asked that question sometime ago but still don't know enough to be sure that it doesn't affect the way I attempted to add in a delay here. I know that it won't work the other way around; but my point is I'm not sure how the browser handles that synchronous loop before the put request is made in p_1 to really know for sure that this example demonstrates that the MDN article ALWAYS holds in this set up.  However, I can observe that it takes longer for the requests to complete as the number of loop iterations is increased; and, in all cases I have observed, p_1 always writes before p_2. The only way p_2 writes before p_1 is if p_1 doesn't write at all because of the string taking up to much memory causing the transaction in p_1 to be aborted.

That being said, and returning to the fuller set up of my question concerning three promises in the array of the Promise.allSettled compared to requiring entry_save to complete before commencing a Promise.allSettled on the two remaining promises, in the full code of my project, for reasons I am not sure of, the latter is quicker than the former, that is, waiting for entry_save to complete is quicker than including it in the Promise.allSettled.

I was expecting it to be the other way around.  The only reason I can think of at this point is that, since entry_save and save_state are both writing to the same object store, perhaps whatever the browser does equivalent to locking the object store until the first transaction, which is that in entry_save, completes and removing the lock takes longer than requiring that entry_save complete before the Promise.allSettled commences and not involving a lock. I thought that everything would be ready "in advance" just waiting for the two put requests to take place in transaction order. They took place in order but more slowly or at least not as quick as using:

```<code>entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );
</code>```

instead of:

```<code> Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );
</code>```

```<code>function p_all() { Promise.allSettled( [ p_1(), p_2() ] ); }

function p_1()
  {
    return new Promise( ( resolve, reject ) =>
      {
        let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
            q = T.objectStore( 'os_1' ),
            u = T.objectStore( 'os_2' ),
            req, i, t ='', x = '';

     req = q.get( 1 );

     req.onsuccess = () =>
       {
         let i, t, r = req.result;
         for ( i = 1; i < 10000000; i++ ) t = t + 'This is a string';
         r.n = 'p1';
         u.put( r );
         console.log( r );
       };
    }); }

function p_2()
  {
    return new Promise( ( resolve, reject ) =>
      {
       let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
           q = T.objectStore( 'os_1' ),
           u = T.objectStore( 'os_2' ),
           req;

        req = q.get( 1 );

        req.onsuccess = () =>
          {
            let r = req.result;
            r.n = 'p2';
            u.put( r );
            console.log( r );
          };
    }); }
</code>```

答:
indexedDB will maintain the order of the transactions in order created, except when those transactions do not overlap (e.g. do not involve the same store out of the set of stores each one involves). this is pretty much regardless of what you do at the higher promise layer.

at the same time, maybe it is unwise to rely on that behavior, because it is implicit and a bit confusing. so maybe it is ok to linearize with promises. the only reach catch is when you need maximum performance, which I doubt applies.

see https://www.w3.org/TR/IndexedDB-2/#transaction-construct

see are indexeddb/localforage reads resolved from a synchronous buffer?

moreover, promises begin execution at the time they are created. they just do not necessarily end at that time, they end eventually instead of immediately. that means that the calls happen in the order you 'create' the promises that are wrapping the indexedDB calls. which means that it relies on the order in which you create the transactions.

regardless of which promise wins the race. regardless of using promise.all.

also, promise.all will retain order even if promises complete out of order, just fyi, but do not let that throw you off.

Body:
In the following code,

Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );

promises entry_save and save_state are both readwrite database transactions and get_HTML is readonly. The two readwrite transactions could be combined together but that complicates the undo/redo chain that is maintained and it ties the success and rollback of the two together which is undesired.

The entry_save transaction needs to write before the save_state transaction.  Before moving entry_save into the Promise.allSettled that is how it worked because the entry_save transaction was created prior to those of the others.  This MDN article explains how the order in which  requests are performed is based upon when the transactions are created independently of the order in which the requests are made.

My question is does the synchronous code of each promise process in the order in which it is placed in the array, such that placing entry_save first will always result in its transaction being created first and guaranteeing its database requests will be performed first?

Although it works and is quick enough, I'd prefer to not do this:

entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );

If it matters, that's not the exactly the way it is written, it's more consistent with:

entry_save().then( intermediate ); where intermediate invokes the Promise.allSettled.

Thank you.

To clarify a bit, below is the example given in the above cited MDN document.

var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
var objectStore2 = trans2.objectStore("foo")
var objectStore1 = trans1.objectStore("foo")
objectStore2.put("2", "key");
objectStore1.put("1", "key");

After the code is executed the object store should contain the value "2", since trans2 should run after trans1.

If entry_save creates trans1 and save_state create trans2, and all in the synchronous code of the functions, meaning not within an onsuccess or onerror handler of a database request or something similar, will the MDN example not hold?

Thus, where @jfriend00 writes,

The functions are called in the order they are placed in the array,
  but that only determines the order in which the asynchronous are
  started.

will this order the timing of the write requests by that of the creation of the transactions, since the transactions are created in the synchronous code before the asynchronous can commence?

I'd like to test it but I'm not sure how.  If two nearly identical promises are used in a Promise.allSettled, how can the write request of the first created transaction be delayed such that it takes place after the write request of the second created transaction, to test if it will be written first? A setTimeout should terminate the transaction. Perhaps a long-running synchronous loop placed before the request.

The code at the very end of this question may better illustrate more precisely what I have attempted to ask. It takes the MDN example in the article cited above and spreads it across two promises placed in a Promise.allSettled, both of which attempt to write to the same object store from within the onsuccess event of a get request.

The question was will the same principle in the article of the first transaction created writing before the second transaction created, regardless of the order the requests are made, still hold in this set up. Since the synchronous portions of the promises will process in the order the promises are placed in the array, the transaction in promise p_1 will be created before that of p_2.  However, the put request in the onsuccess event of the get request in p_1 is delayed by the loop building a large string. The question is will p_1 still write before p_2?

In experimenting with this, I cannot get p_2 to write before p_1. Thus, it appears that the MDN example applies even in this type of set up.  However, I cannot be sure of why because I don't understand how the JS code is really interpreted/processed.

For example, why can the req.onsuccess function be defined after the request is made? I asked that question sometime ago but still don't know enough to be sure that it doesn't affect the way I attempted to add in a delay here. I know that it won't work the other way around; but my point is I'm not sure how the browser handles that synchronous loop before the put request is made in p_1 to really know for sure that this example demonstrates that the MDN article ALWAYS holds in this set up.  However, I can observe that it takes longer for the requests to complete as the number of loop iterations is increased; and, in all cases I have observed, p_1 always writes before p_2. The only way p_2 writes before p_1 is if p_1 doesn't write at all because of the string taking up to much memory causing the transaction in p_1 to be aborted.

That being said, and returning to the fuller set up of my question concerning three promises in the array of the Promise.allSettled compared to requiring entry_save to complete before commencing a Promise.allSettled on the two remaining promises, in the full code of my project, for reasons I am not sure of, the latter is quicker than the former, that is, waiting for entry_save to complete is quicker than including it in the Promise.allSettled.

I was expecting it to be the other way around.  The only reason I can think of at this point is that, since entry_save and save_state are both writing to the same object store, perhaps whatever the browser does equivalent to locking the object store until the first transaction, which is that in entry_save, completes and removing the lock takes longer than requiring that entry_save complete before the Promise.allSettled commences and not involving a lock. I thought that everything would be ready "in advance" just waiting for the two put requests to take place in transaction order. They took place in order but more slowly or at least not as quick as using:

entry_save().then( () => { Promise.allSettled( [ save_state(), get_HTML() ] ) } ).then( ... );

instead of:

 Promise.allSettled( [ entry_save(), save_state(), get_HTML() ] ).then( ... );

function p_all() { Promise.allSettled( [ p_1(), p_2() ] ); }

function p_1()
  {
    return new Promise( ( resolve, reject ) =>
      {
        let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
            q = T.objectStore( 'os_1' ),
            u = T.objectStore( 'os_2' ),
            req, i, t ='', x = '';

     req = q.get( 1 );

     req.onsuccess = () =>
       {
         let i, t, r = req.result;
         for ( i = 1; i < 10000000; i++ ) t = t + 'This is a string';
         r.n = 'p1';
         u.put( r );
         console.log( r );
       };
    }); }

function p_2()
  {
    return new Promise( ( resolve, reject ) =>
      {
       let T = DB.transaction( [ 'os_1', 'os_2' ], 'readwrite' ),
           q = T.objectStore( 'os_1' ),
           u = T.objectStore( 'os_2' ),
           req;

        req = q.get( 1 );

        req.onsuccess = () =>
          {
            let r = req.result;
            r.n = 'p2';
            u.put( r );
            console.log( r );
          };
    }); }


问:
How to create a separate 'archive widget' only for my cpt 'portfolio'?
I am creating one custom wordpress theme for my portfolio, trying to do everything from scratch by using fields and meta-boxes and don't want to use any plugin.

I have created one cpt as below:

function codex_custom_init() {

     register_post_type(
        'Portfolio', array(
        'labels' => array('name' => __( 'Portfolio' ), 'singular_name' => __( 'Portfolio' ) ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail', 'comments'),
        'menu_icon' => 'dashicons-sos',
        )
    );

    //register taxonomy for portfolio post tags
    register_taxonomy(
        'portfolio-tag', //taxonomy
        'portfolio', //post-type
        array(
            'hierarchical'  => false,
            'label'         => __( 'Portfolio Tags','taxonomy general name'),
            'singular_name' => __( 'Tag', 'taxonomy general name' ),
            'rewrite'       => true,
            'query_var'     => true
        )
    );

    // add categories for Portfolio

    register_taxonomy(
            'portfoliocategories',
            'portfolio',
            array(
                'labels' => array(
                    'name' => 'Portfolio Categories',
                    'add_new_item' => 'Add New Portfolio Category',
                    'new_item_name' => "New Portfolio Type"
                ),
                'show_ui' => true,
                'show_tagcloud' => false,
                'hierarchical' => true
            )
        );

    }
    add_action( 'init', 'codex_custom_init' );```
</div>
</div>
</p>

<p>I have created all the required pages and sidebars. I want to show archive widget on my 'archive portfolio page', a separate archive widget, which will have posts only related to portfolio.
Thanks for your concern.</p>

<p>How to edit and customize this for cpt:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
    wp_get_archives(
    apply_filters(
    'widget_archives_args',
    array(
        'type'   => 'monthly',
        'show_post_count' => $count,
        ),
        $instance
        )
        );
    ?></code>```

答:
Use this code for creating sidebar widget for custom CPT.
For register new sidebar.

```<code>// Register new sidebar with ID ==> deals-sidebar
genesis_register_sidebar( array(
    'id' => 'deals-sidebar',
    'name' => 'SideBar for Deals',
    'description' => 'SideBar for Deals Custom Post Type',
) );
</code>```

Remove default WordPress Sidebar and add action hook to add new sidebar to CPT deals.

```<code>add_action('get_header','crunchify_update_deals_sidebar');
function crunchify_update_deals_sidebar() {
    if ( is_singular('deals')) { // Here "deals" is a slug name for my CPT
        remove_action( 'genesis_sidebar', 'genesis_do_sidebar' ); //remove the default genesis sidebar
        add_action( 'genesis_sidebar', 'crunchify_add_sidebar' ); //add an action hook to call the function for my custom sidebar
    }
}

//Function to output my custom sidebar
function crunchify_add_sidebar() {
    dynamic_sidebar( 'deals-sidebar' ); // id of sidebar which you just registered
}
</code>```

Hope it helps!!!

Body:
I am creating one custom wordpress theme for my portfolio, trying to do everything from scratch by using fields and meta-boxes and don't want to use any plugin.

I have created one cpt as below:

function codex_custom_init() {

     register_post_type(
        'Portfolio', array(
        'labels' => array('name' => __( 'Portfolio' ), 'singular_name' => __( 'Portfolio' ) ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail', 'comments'),
        'menu_icon' => 'dashicons-sos',
        )
    );

    //register taxonomy for portfolio post tags
    register_taxonomy(
        'portfolio-tag', //taxonomy
        'portfolio', //post-type
        array(
            'hierarchical'  => false,
            'label'         => __( 'Portfolio Tags','taxonomy general name'),
            'singular_name' => __( 'Tag', 'taxonomy general name' ),
            'rewrite'       => true,
            'query_var'     => true
        )
    );

    // add categories for Portfolio

    register_taxonomy(
            'portfoliocategories',
            'portfolio',
            array(
                'labels' => array(
                    'name' => 'Portfolio Categories',
                    'add_new_item' => 'Add New Portfolio Category',
                    'new_item_name' => "New Portfolio Type"
                ),
                'show_ui' => true,
                'show_tagcloud' => false,
                'hierarchical' => true
            )
        );

    }
    add_action( 'init', 'codex_custom_init' );

I have created all the required pages and sidebars. I want to show archive widget on my 'archive portfolio page', a separate archive widget, which will have posts only related to portfolio.
Thanks for your concern.

How to edit and customize this for cpt:

<?php
    wp_get_archives(
    apply_filters(
    'widget_archives_args',
    array(
        'type'   => 'monthly',
        'show_post_count' => $count,
        ),
        $instance
        )
        );
    ?>

Body:
Use this code for creating sidebar widget for custom CPT.
For register new sidebar.

// Register new sidebar with ID ==> deals-sidebar
genesis_register_sidebar( array(
    'id' => 'deals-sidebar',
    'name' => 'SideBar for Deals',
    'description' => 'SideBar for Deals Custom Post Type',
) );

Remove default WordPress Sidebar and add action hook to add new sidebar to CPT deals.

add_action('get_header','crunchify_update_deals_sidebar');
function crunchify_update_deals_sidebar() {
    if ( is_singular('deals')) { // Here "deals" is a slug name for my CPT
        remove_action( 'genesis_sidebar', 'genesis_do_sidebar' ); //remove the default genesis sidebar
        add_action( 'genesis_sidebar', 'crunchify_add_sidebar' ); //add an action hook to call the function for my custom sidebar
    }
}

//Function to output my custom sidebar
function crunchify_add_sidebar() {
    dynamic_sidebar( 'deals-sidebar' ); // id of sidebar which you just registered
}

Hope it helps!!!


问:
Pandas returns empty DataFrame , empty columns and empty index
This is from a youtube tutorial online; heres the link if the question is not clear enough
https://www.youtube.com/watch?v=3nzk_D6PD20&list=PLqT5wYj8Tan3g8cdTYaCN-n-J4jxN2iDH&index=6

Im trying to get a dataframe of all the adj closes of a specific set tickers from the bitfinex API.

```<code>import requests
import time
import pandas as pd
import numpy as np

curr_date=round(time.time())
start_date=curr_date*1000 - 14*24*60*60*1000 #getting the latest date

sym_requests=requests.get('https://api.bitfinex.com/v1/symbols') #get all ticker symbols

if sym_requests.status_code == 200:
    symbols = eval(sym_requests.content)

symbols_filtered=[]

for elem in symbols:
    if elem[-3:]=='btc':
        symbols_filtered.append(elem) #put all the tickers that have a btc pair in a list

final_df=pd.DataFrame() #create an empty dataframe

for pair in symbols_filtered: #iterate through the different symbols in list
    time.sleep(3)
    r=requests.get('https://api.bitfinex.com/v2/candles/trade:30m:t'
    +pair.upper()+'/hist?sort=1&start='+str(start_date)
    +'&limit=1000') # retrieve symbol pair data
    if r.status_code ==200:
        res=eval(r.content)
        if len(res)>660: # continue loop if only length of data is more than 660 lines
            df=pd.DataFrame(res) #save data into a dataframe
            df.set_index(0)
            final_df[str(pair)]=df[2] # save close values which are located in df[2] column to the final_df dataframe
final_df.dropna(inplace=True)
print(final_df)
</code>```

The code seems to be working for individual tickers , however the for loop seems to be not working for all the tickers in the symbols_filtered=[] list as I am getting the following as the output:
Empty DataFrame
Columns: []
Index: []

Id really appreciate some help with this, as this is my first question on the platform.

Body:
This is from a youtube tutorial online; heres the link if the question is not clear enough
https://www.youtube.com/watch?v=3nzk_D6PD20&list=PLqT5wYj8Tan3g8cdTYaCN-n-J4jxN2iDH&index=6

Im trying to get a dataframe of all the adj closes of a specific set tickers from the bitfinex API.

import requests
import time
import pandas as pd
import numpy as np

curr_date=round(time.time())
start_date=curr_date*1000 - 14*24*60*60*1000 #getting the latest date

sym_requests=requests.get('https://api.bitfinex.com/v1/symbols') #get all ticker symbols

if sym_requests.status_code == 200:
    symbols = eval(sym_requests.content)

symbols_filtered=[]

for elem in symbols:
    if elem[-3:]=='btc':
        symbols_filtered.append(elem) #put all the tickers that have a btc pair in a list

final_df=pd.DataFrame() #create an empty dataframe

for pair in symbols_filtered: #iterate through the different symbols in list
    time.sleep(3)
    r=requests.get('https://api.bitfinex.com/v2/candles/trade:30m:t'
    +pair.upper()+'/hist?sort=1&start='+str(start_date)
    +'&limit=1000') # retrieve symbol pair data
    if r.status_code ==200:
        res=eval(r.content)
        if len(res)>660: # continue loop if only length of data is more than 660 lines
            df=pd.DataFrame(res) #save data into a dataframe
            df.set_index(0)
            final_df[str(pair)]=df[2] # save close values which are located in df[2] column to the final_df dataframe
final_df.dropna(inplace=True)
print(final_df)

The code seems to be working for individual tickers , however the for loop seems to be not working for all the tickers in the symbols_filtered=[] list as I am getting the following as the output:
Empty DataFrame
Columns: []
Index: []

Id really appreciate some help with this, as this is my first question on the platform.

Body:
What I found is that the conditionlen(res)>600 is causing the problem as received data's length is less than 660 try smaller value like 600

final output I am getting is something like this:

       ltcbtc    ethbtc    etcbtc    zecbtc    xmrbtc    dshbtc    xrpbtc  \
0    0.007638  0.021456  0.001353  0.007496  0.008132  0.012747  0.000029
1    0.007594  0.021422  0.001341  0.007435  0.008093  0.012706  0.000029
2    0.007595  0.021493  0.001343  0.007449  0.008072  0.012668  0.000029
3    0.007606  0.021556  0.001345  0.007450  0.008125  0.012729  0.000029
4    0.007599  0.021742  0.001340  0.007428  0.008129  0.012730  0.000029
..        ...       ...       ...       ...       ...       ...       ...
596  0.007617  0.027687  0.000951  0.006544  0.008192  0.011229  0.000029
597  0.007576  0.027622  0.000952  0.006489  0.008094  0.011196  0.000029
598  0.007554  0.027850  0.000946  0.006515  0.008208  0.011165  0.000029
599  0.007533  0.027798  0.000944  0.006407  0.008103  0.011269  0.000029
600  0.007575  0.027713  0.000943  0.006396  0.008116  0.011233  0.000029

       iotbtc    eosbtc    neobtc
0    0.000035  0.000472  0.001343
1    0.000035  0.000471  0.001342
2    0.000035  0.000471  0.001332
3    0.000035  0.000471  0.001337
4    0.000035  0.000476  0.001350
..        ...       ...       ...
596  0.000029  0.000454  0.001467
597  0.000029  0.000452  0.001486
598  0.000029  0.000453  0.001476
599  0.000029  0.000453  0.001477
600  0.000029  0.000451  0.001474

[601 rows x 10 columns]

for better code quality and functionality add an else statement in you code with probably the same logic or as per your requirements


问:
how to checkout only specific folder from git repo and build
Hey folks I need some help on the jenkinsfile. Below is my usecase

This is the strcuture of my GIT repo:

```<code>root
  |->app1
  |   |->jenkinsfile
  |   |->dockerfile
  |->app2
      |->jenkinsfile
      |->dockerfile
</code>```

I am having a monorepo, app1 and app2 in the root folder and I want when their is a change in app1 folder, only app1 should build and same for app2. I have defined the jenkinsfile in jenkins but when its build. its looking for dockerfile1 in root folder not inside app1.

jenkisfile:

```<code>pipeline {
    agent any

    environment {
        PIPENV_VENV_IN_PROJECT = true
        DEVPI_USER = '\'jenkins_user\''
        DEVPI_PASSWORD = '\'V$5_Z%Bf-:mJ\''
        WORKSPACE="${WORKSPACE}/app1"

    }
    stages {
        stage('Notify Bitbucket') {
            steps {
                bitbucketStatusNotify(buildState: 'INPROGRESS')
            }
        }

        stage('Build Environment') {
            steps {
                sh 'docker build -t app-builder .'
            }
        }

        stage('Test') {

            steps{
                sh 'docker run --rm app-builder pytest'
            }
        }
</code>```

答:
Use dir command to change the directory e.g </p>

```<code>stage('Build Environment') {
   steps {
      dir("app1"){
         sh 'docker build -t app-builder .'
      }
   }
}
</code>```

Body:
Hey folks I need some help on the jenkinsfile. Below is my usecase

This is the strcuture of my GIT repo:

root
  |->app1
  |   |->jenkinsfile
  |   |->dockerfile
  |->app2
      |->jenkinsfile
      |->dockerfile

I am having a monorepo, app1 and app2 in the root folder and I want when their is a change in app1 folder, only app1 should build and same for app2. I have defined the jenkinsfile in jenkins but when its build. its looking for dockerfile1 in root folder not inside app1.

jenkisfile:

pipeline {
    agent any

    environment {
        PIPENV_VENV_IN_PROJECT = true
        DEVPI_USER = '\'jenkins_user\''
        DEVPI_PASSWORD = '\'V$5_Z%Bf-:mJ\''
        WORKSPACE="${WORKSPACE}/app1"

    }
    stages {
        stage('Notify Bitbucket') {
            steps {
                bitbucketStatusNotify(buildState: 'INPROGRESS')
            }
        }

        stage('Build Environment') {
            steps {
                sh 'docker build -t app-builder .'
            }
        }

        stage('Test') {

            steps{
                sh 'docker run --rm app-builder pytest'
            }
        }

Body:
Use dir command to change the directory e.g

stage('Build Environment') {
   steps {
      dir("app1"){
         sh 'docker build -t app-builder .'
      }
   }
}


问:
rails - list of tenants to migrate appears to be empty when loading a schema
what does it mean if in rails I run db:schema:load, and the schema loads until it says that "the list of tenants to migrate appears to be empty"?
And what ways are available to solve this?

As in here (sorry I am unable to format it better):

...

--create_table("users", {:force=>:cascade})

  -> 0.4490s

-- create_table("web_migrations", {:id=>false, :force=>:cascade})

  -> 0.6138s

-- initialize_schema_migrations_table()

  -> 0.0332s

[WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things:

```<code>      1. You may not have created any, in which case you can ignore this message
      2. You've run `apartment:migrate` directly without loading the Rails environment
        * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate`

    Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this.
</code>```

I noticed that maybe db:schema:load runs twice?
It starts fine:

-- create_table("asset_status", {:force=>:cascade})

  -> 0.5029s

-- create_table("asset_type", {:force=>:cascade})

  -> 0.2904s

[continues...]

-- create_table("web_migrations", {:id=>false, :force=>:cascade})

  -> 0.3347s

-- initialize_schema_migrations_table()    -> 1.1729s

and after this again:

-- create_table("asset_status", {:force=>:cascade})

  -> 0.6400s

-- create_table("asset_type", {:force=>:cascade})

  -> 0.5805s

[continues...]

is it wrong?

答:
In case it helps someone in future, You can use single tenant migration in-case there is no other solution.

Run DB=tenant_name rake db:migrate

This will migrate the database for a specific tenant.

Body:
what does it mean if in rails I run db:schema:load, and the schema loads until it says that "the list of tenants to migrate appears to be empty"?
And what ways are available to solve this?

As in here (sorry I am unable to format it better):

...

--create_table("users", {:force=>:cascade})

  -> 0.4490s

-- create_table("web_migrations", {:id=>false, :force=>:cascade})

  -> 0.6138s

-- initialize_schema_migrations_table()

  -> 0.0332s

[WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things:

      1. You may not have created any, in which case you can ignore this message
      2. You've run `apartment:migrate` directly without loading the Rails environment
        * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate`

    Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this.

I noticed that maybe db:schema:load runs twice?
It starts fine:

-- create_table("asset_status", {:force=>:cascade})

  -> 0.5029s

-- create_table("asset_type", {:force=>:cascade})

  -> 0.2904s

[continues...]

-- create_table("web_migrations", {:id=>false, :force=>:cascade})

  -> 0.3347s

-- initialize_schema_migrations_table()    -> 1.1729s

and after this again:

-- create_table("asset_status", {:force=>:cascade})

  -> 0.6400s

-- create_table("asset_type", {:force=>:cascade})

  -> 0.5805s

[continues...]

is it wrong?


问:
Unable to grab classes using Selenium in TripAdvisor
I'm trying to scrape all of the images for a specific TripAdivsor page but when using the find_elements_by_class_name function in Selenium, it is giving me no values whatsoever. I am confused as that is the exact class name for what values I want to iterate through and append to a list, here is the site. Any help would be greatly appreciated!</p>

```<code># importing dependencies
import re
import selenium
import io
import pandas as pd
import urllib.request
import urllib.parse
import requests
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import time
from _datetime import datetime
from selenium.webdriver.common.keys import Keys

#setup opening url window of website to be scraped
options = webdriver.ChromeOptions()
options.headless=False
prefs = {"profile.default_content_setting_values.notifications" : 2}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3") #possible issue by not including the file extension
driver.maximize_window()
time.sleep(5)
driver.get("""https://www.tripadvisor.com/""") #get the information from the page

#automate searching for hotels in specific city
driver.find_element_by_xpath('/html/body/div[2]/div/div[6]/div[1]/div/div/div/div/span[1]/div/div/div/a').click() #clicks on hotels option
driver.implicitly_wait(12) #allows xpath to be found
driver.find_element_by_xpath('//*[@id="BODY_BLOCK_JQUERY_REFLOW"]/div[12]/div/div/div[1]/div[1]/div/input').send_keys("Washington D.C.", Keys.ENTER) #change string to get certain city
time.sleep(8)

#now get current url
url = driver.current_url

response = requests.get(url)
response = response.text
data = BeautifulSoup(response, 'html.parser')

#get list of all hotels
hotels = driver.find_elements_by_class_name("prw_rup prw_meta_hsx_responsive_listing ui_section listItem")

print("Total Number of Hotels: ", len(hotels))

</code>```

答:
I would recommend that, if you use Selenium, don't use BeautifulSoup beside it because you can get whatever you want using Selenium.

You can simply achieve your goal as follows:

```<code>driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3")
driver.maximize_window()

driver.get("https://www.tripadvisor.ca/Hotels")

time.sleep(1)

driver.implicitly_wait(12)
driver.find_element_by_xpath('//*[@class="typeahead_input"]').send_keys("Washington D.C.", Keys.ENTER)
time.sleep(1)
hotels = driver.find_elements_by_xpath('//*[@class="listing collapsed"]')

print("Total Number of Hotels: ", len(hotels))
</code>```

Please note that using this code you would get the first 30 hotels (i.e., first page). You would need to loop through all the pages of hotels of the specified city in order to get them all.

Hope it helps.

Body:
I'm trying to scrape all of the images for a specific TripAdivsor page but when using the find_elements_by_class_name function in Selenium, it is giving me no values whatsoever. I am confused as that is the exact class name for what values I want to iterate through and append to a list, here is the site. Any help would be greatly appreciated!

# importing dependencies
import re
import selenium
import io
import pandas as pd
import urllib.request
import urllib.parse
import requests
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import time
from _datetime import datetime
from selenium.webdriver.common.keys import Keys

#setup opening url window of website to be scraped
options = webdriver.ChromeOptions()
options.headless=False
prefs = {"profile.default_content_setting_values.notifications" : 2}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3") #possible issue by not including the file extension
driver.maximize_window()
time.sleep(5)
driver.get("""https://www.tripadvisor.com/""") #get the information from the page

#automate searching for hotels in specific city
driver.find_element_by_xpath('/html/body/div[2]/div/div[6]/div[1]/div/div/div/div/span[1]/div/div/div/a').click() #clicks on hotels option
driver.implicitly_wait(12) #allows xpath to be found
driver.find_element_by_xpath('//*[@id="BODY_BLOCK_JQUERY_REFLOW"]/div[12]/div/div/div[1]/div[1]/div/input').send_keys("Washington D.C.", Keys.ENTER) #change string to get certain city
time.sleep(8)

#now get current url
url = driver.current_url

response = requests.get(url)
response = response.text
data = BeautifulSoup(response, 'html.parser')

#get list of all hotels
hotels = driver.find_elements_by_class_name("prw_rup prw_meta_hsx_responsive_listing ui_section listItem")

print("Total Number of Hotels: ", len(hotels))

Body:
I would recommend that, if you use Selenium, don't use BeautifulSoup beside it because you can get whatever you want using Selenium.

You can simply achieve your goal as follows:

driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3")
driver.maximize_window()

driver.get("https://www.tripadvisor.ca/Hotels")

time.sleep(1)

driver.implicitly_wait(12)
driver.find_element_by_xpath('//*[@class="typeahead_input"]').send_keys("Washington D.C.", Keys.ENTER)
time.sleep(1)
hotels = driver.find_elements_by_xpath('//*[@class="listing collapsed"]')

print("Total Number of Hotels: ", len(hotels))

Please note that using this code you would get the first 30 hotels (i.e., first page). You would need to loop through all the pages of hotels of the specified city in order to get them all.

Hope it helps.