问:
Get object version with JaVers
I'm using JaVers 5.6.3 with Spring Boot 2.1. Saving history is working fine and I also can read object changes.

I use this code:

```<code>List<Change> changes = javers.findChanges(jqlQuery.build());
</code>```

My problem is that the result contains only the commit id, but not the object version. In the database there is a jv_snapshot.version field, that contains the real object version.

How can I get it in my code?

答:
I don't know if this helps or not
but you can get whole entity with its version

First get the shadow and then try to get snapshot from the committed. As given in the code

```<code> List<Shadow<YourObject>> shadows=        javers.findShadows(QueryBuilder.byInstance(optionalObject.get()).build());

 List<CdoSnapshot> changes=javers.findSnapshots(QueryBuilder.byInstanceId(id,YourObject.class).withCommitId(shadow.get(0).getCommitId()).build());
</code>```

In this way, you can get version of each entity, let me know if you find some better way.

Title: Get object version with JaVers

Body:
I'm using JaVers 5.6.3 with Spring Boot 2.1. Saving history is working fine and I also can read object changes.

I use this code:

List<Change> changes = javers.findChanges(jqlQuery.build());

My problem is that the result contains only the commit id, but not the object version. In the database there is a jv_snapshot.version field, that contains the real object version.

How can I get it in my code?

Body:
I don't know if this helps or not
but you can get whole entity with its version

First get the shadow and then try to get snapshot from the committed. As given in the code

 List<Shadow<YourObject>> shadows=        javers.findShadows(QueryBuilder.byInstance(optionalObject.get()).build());

 List<CdoSnapshot> changes=javers.findSnapshots(QueryBuilder.byInstanceId(id,YourObject.class).withCommitId(shadow.get(0).getCommitId()).build());

In this way, you can get version of each entity, let me know if you find some better way.


来源: stackexchange

问:
Save Oracle stored procedure out clob parameter (to create JSON format) to a file with Informatica
I'd like to create a JSON file of oracle table. To do so, I've created a Oracle SP:

```<code> PROCEDURE P_JSON_GEN( SCHEMA_NAME_IN IN VARCHAR2 DEFAULT 'CDM_MART', TABLE_NAME_IN IN VARCHAR2 DEFAULT NULL, P_JSON OUT CLOB) IS

  v_schema_name varchar2(20);
  v_table_name varchar2(30);
  v_sql varchar2(32767);
  type t_json is TABLE of varchar2(1000) INDEX BY BINARY_INTEGER;
  table_json t_json;
  v_json clob;
  CURSOR c_col_lst IS SELECT column_name FROM all_tab_cols WHERE OWNER = 'CDM_MART' AND table_name = (SELECT table_name FROM all_synonyms WHERE synonym_name = table_name_in AND OWNER= schema_name_in);

  BEGIN

v_schema_name := schema_name_in;
v_table_name := TABLE_NAME_IN;
v_sql := 'SELECT json_object(''';
v_json := '';

for n in c_col_lst
             loop
                v_sql := v_sql ||n.column_name||''' VALUE '||n.column_name||',''';
             end loop;
             v_sql := RTRIM(v_sql, ',''') || ' FORMAT JSON) as json FROM '||TABLE_NAME_IN;

             execute immediate v_sql BULK COLLECT into table_json;
             DBMS_OUTPUT.PUT_LINE (v_sql);
             for i in 1 .. table_json.count
             loop
             v_json := v_json || table_json(i) || chr(10);
             end loop;

        P_JSON := v_sql;
        RETURN;
    end;
</code>```

So it creates me an output CLOB (as it is a long string) and, as I cannot save it on DB server, I need to save it on Informatica server, so I'd like to use WFL with following mapping to save the output into file on server.

WFL executes successfully, file is created, but nothing written.
When I have changed the output to varchar2(4000) in SP and string(4000) within mappings  it had created the file.

Could you please suggest how should I resolve datatype mismatch and is it possible to save such long variable into a file?

答: Yes you can save max length of string into to a file. Looking at your design, seems to be there is no any conflict on the datatype. You can use string to string mapping</p>

ContentLicense: CC BY-SA 4.0

Body:
I'd like to create a JSON file of oracle table. To do so, I've created a Oracle SP:

 PROCEDURE P_JSON_GEN( SCHEMA_NAME_IN IN VARCHAR2 DEFAULT 'CDM_MART', TABLE_NAME_IN IN VARCHAR2 DEFAULT NULL, P_JSON OUT CLOB) IS

  v_schema_name varchar2(20);
  v_table_name varchar2(30);
  v_sql varchar2(32767);
  type t_json is TABLE of varchar2(1000) INDEX BY BINARY_INTEGER;
  table_json t_json;
  v_json clob;
  CURSOR c_col_lst IS SELECT column_name FROM all_tab_cols WHERE OWNER = 'CDM_MART' AND table_name = (SELECT table_name FROM all_synonyms WHERE synonym_name = table_name_in AND OWNER= schema_name_in);

  BEGIN

v_schema_name := schema_name_in;
v_table_name := TABLE_NAME_IN;
v_sql := 'SELECT json_object(''';
v_json := '';

for n in c_col_lst
             loop
                v_sql := v_sql ||n.column_name||''' VALUE '||n.column_name||',''';
             end loop;
             v_sql := RTRIM(v_sql, ',''') || ' FORMAT JSON) as json FROM '||TABLE_NAME_IN;

             execute immediate v_sql BULK COLLECT into table_json;
             DBMS_OUTPUT.PUT_LINE (v_sql);
             for i in 1 .. table_json.count
             loop
             v_json := v_json || table_json(i) || chr(10);
             end loop;

        P_JSON := v_sql;
        RETURN;
    end;

So it creates me an output CLOB (as it is a long string) and, as I cannot save it on DB server, I need to save it on Informatica server, so I'd like to use WFL with following mapping to save the output into file on server.

WFL executes successfully, file is created, but nothing written.
When I have changed the output to varchar2(4000) in SP and string(4000) within mappings  it had created the file.

Could you please suggest how should I resolve datatype mismatch and is it possible to save such long variable into a file?


问:
Why is my WordPress visual editor not working?
I have website running WordPress 4.6.2 and I can't use the visual editor right now, only the text editor. When I open the browser console it show various errors.

I've been working on this problem for a good few hours and tried:

restoring WordPress

deactivating plugins

deactivate the custom CSS used in the site

Looking for can_compress_scripts in the DB and all various stuff that I stumble upon internet but with no success whatsoever

Used theme is Spacious

Include define('CONCATENATE_SCRIPTS', false); into wp-config.php

Replaced TinyMCE folder content with TinyMCE content from clear installation

A screenshot of the error from my web browser's console (below):

答:
I have found a workaround or possibly the solution if you dont want to go deep into codes.

This is the fix: (It worked in my case and I am sure it can work for others with similar issue.)

Install Visual Composer(Wpbackery or others)

Go to => Role manager => Post type => custom => Select both for post and page.

That's all.

I found this workaround that is very good and can work in other case after running into this case where I could not switch from visual editor to text editor on wordpress.
I simply adjusted my WPbackery setting and everything works fine now on my site.

Before then I had tried so many solutions and even included define('CONCATENATE_SCRIPTS',  to my config but to no avail.

I don't know if there is the need to explain all the things I have done on the cause of troubleshooting for this for a whole day. But with the solution I posted above it would solve your issue.

ContentLicense: CC BY-SA 3.0


问:
dispatchEvent doesn't work in javascript with Internet explorer 11
In my website I have a javascript in which I wish to open a file save dialog. The purpose is to save in a text file some data that are coming from the web server.

I am trying to use the code snippet shown in this post:

[Using HTML5/JavaScript to generate and save a file

And to be precise:

```<code>function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
</code>```

This works great for Firefox and Chrome. However with Internet Explorer 11 it doesn't work. When this instruction is executed...

```<code>pom.dispatchEvent(event);
</code>```

...nothing happens. The save dialog is not opened, and no error is shown in the java console of the browser. The event seems to get lost in the void.
Any help would be greatly appreciated.

答:
This is widely supported in modern browser. However,

Older versions of IE supported an equivalent, proprietary
  EventTarget.fireEvent() method.

Source: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

Body:
In my website I have a javascript in which I wish to open a file save dialog. The purpose is to save in a text file some data that are coming from the web server.

I am trying to use the code snippet shown in this post:

[Using HTML5/JavaScript to generate and save a file

And to be precise:

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

This works great for Firefox and Chrome. However with Internet Explorer 11 it doesn't work. When this instruction is executed...

pom.dispatchEvent(event);

...nothing happens. The save dialog is not opened, and no error is shown in the java console of the browser. The event seems to get lost in the void.
Any help would be greatly appreciated.


问:
How to find beginning letters in string.I am getting errors in the program below
```<code>#include <stdio.h>
#include <string.h>
void printfletter(char *);``
int main ()
{
    char a[50]="where are you";
    printfletter(a);
    return 0;
}
void printfletter(char *p)
{
    int i;
    printf("%c",*p);
    for (i=1;*(p+i)!='\0';i++)
    {
        if (*(p+i)==32)
        {
            printf("%c",*(++p));
        }
    }
}
</code>```

Program is to print all the beginning letters in string.
I should get the output as 'way'(w-where,a-are,y-you)
But i get 'whe'
I tried to implement it using functions and pointers.

答:
I suggest a function similar to this:

```<code>// Argument is a constant pointer to constant character, because
// we neither modify the pointer nor modify the data it points to
void printfletter(const char * const p)
{
    if (p == NULL)
    {
        // The caller passed a null pointer
        return;  // Don't print anything, just return from the function
    }

    size_t i;  // Used as index into the string

    // First skip over all leading spaces, in case there is any
    for (i = 0; p[i] != '\0'; ++i)
    {
        // If the current character is not a space, then break out of the loop
        if (!isspace(p[i]))
        {
            break;
        }
    }

    if (p[i] == '\0')
    {
        // All of the string was space, no letters or anything else
        return;  // Don't print anything
    }

    // State variable, to say if the last character checked was a space
    bool last_was_space = true;  // Initialize to true, to print the first character

    // Iterate over all character in the null-terminated string
    // We reuse the index variable i, it will already be positioned at the
    // next character to check
    for (; p[i] != '\0'; ++i)
    {
        // If the current character at index i is a space...
        if (isspace(p[i]))
        {
            // ... then set the state variable
            last_was_space = true;
        }
        // Otherwise, if the last character was a space...
        else if (last_was_space)
        {
            // ... then print the current character
            putchar(p[i]);

            // And reset the state
            last_was_space = false;
        }
        // Else do nothing
    }
}
</code>```

The above function should print the first character of every space-delimited "word".

With the string you show ("where are you") it prints way.

Body:
#include <stdio.h>
#include <string.h>
void printfletter(char *);``
int main ()
{
    char a[50]="where are you";
    printfletter(a);
    return 0;
}
void printfletter(char *p)
{
    int i;
    printf("%c",*p);
    for (i=1;*(p+i)!='\0';i++)
    {
        if (*(p+i)==32)
        {
            printf("%c",*(++p));
        }
    }
}

Program is to print all the beginning letters in string.
I should get the output as 'way'(w-where,a-are,y-you)
But i get 'whe'
I tried to implement it using functions and pointers.

Body:
I suggest a function similar to this:

// Argument is a constant pointer to constant character, because
// we neither modify the pointer nor modify the data it points to
void printfletter(const char * const p)
{
    if (p == NULL)
    {
        // The caller passed a null pointer
        return;  // Don't print anything, just return from the function
    }

    size_t i;  // Used as index into the string

    // First skip over all leading spaces, in case there is any
    for (i = 0; p[i] != '\0'; ++i)
    {
        // If the current character is not a space, then break out of the loop
        if (!isspace(p[i]))
        {
            break;
        }
    }

    if (p[i] == '\0')
    {
        // All of the string was space, no letters or anything else
        return;  // Don't print anything
    }

    // State variable, to say if the last character checked was a space
    bool last_was_space = true;  // Initialize to true, to print the first character

    // Iterate over all character in the null-terminated string
    // We reuse the index variable i, it will already be positioned at the
    // next character to check
    for (; p[i] != '\0'; ++i)
    {
        // If the current character at index i is a space...
        if (isspace(p[i]))
        {
            // ... then set the state variable
            last_was_space = true;
        }
        // Otherwise, if the last character was a space...
        else if (last_was_space)
        {
            // ... then print the current character
            putchar(p[i]);

            // And reset the state
            last_was_space = false;
        }
        // Else do nothing
    }
}

The above function should print the first character of every space-delimited "word".

With the string you show ("where are you") it prints way.


问:
Gimp switch color channels
I'm capturing a raw framebuffer on an embedded device.  The framebuffer is 32bit BGRA color mode

```<code>cp /dev/fb0 framebuffer.data
</code>```

I can transfer the raw dump to my PC and import it into GIMP, but GIMP only allows me to read the raw data as if it were ARGB, which results in incorrect colors.  Is there a way to just switch the red and blue channels in GIMP?

答:
I found a way around this by using gstreamer to convert the color and do the screencap...</p>

```<code>#!/bin/bash

cp /dev/fb0 /home/root/framebuffer.data
gst-launch-1.0 filesrc location="/home/root/framebuffer.data" ! rawvideoparse use-sink-caps=false width=800 height=1280 format=bgra  ! imxvideoconvert_ipu !  videoconvert ! pngenc snapshot=false compression-level=1 ! filesink location=/home/root/screencap.png
rm /home/root/framebuffer.data

</code>```

Title: Gimp switch color channels

Body:
I'm capturing a raw framebuffer on an embedded device.  The framebuffer is 32bit BGRA color mode

cp /dev/fb0 framebuffer.data

I can transfer the raw dump to my PC and import it into GIMP, but GIMP only allows me to read the raw data as if it were ARGB, which results in incorrect colors.  Is there a way to just switch the red and blue channels in GIMP?

Body:
I found a way around this by using gstreamer to convert the color and do the screencap...

#!/bin/bash

cp /dev/fb0 /home/root/framebuffer.data
gst-launch-1.0 filesrc location="/home/root/framebuffer.data" ! rawvideoparse use-sink-caps=false width=800 height=1280 format=bgra  ! imxvideoconvert_ipu !  videoconvert ! pngenc snapshot=false compression-level=1 ! filesink location=/home/root/screencap.png
rm /home/root/framebuffer.data


问:
Spring Data CrudRepository.findAllById exception with large number of IDs
I am using the Spring Data JDBC (version 1.1.6) method CrudRepository.findAllById to load entities from a database with a large number of IDs. The underlying database connection uses a Postgres database. The invocation of the method raises a PSQLException:

```<code>2020-05-28 05:58:35,260 WARN com.zaxxer.hikari.pool.ProxyConnection [task-2] HikariPool-1 - Connection org.postgresql.jdbc.PgConnection@1224f39f marked as broken because of SQLSTATE(08006), ErrorCode(0)
org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:358)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
...
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 137525
    at org.postgresql.core.PGStream.sendInteger2(PGStream.java:275)
    at org.postgresql.core.v3.QueryExecutorImpl.sendParse(QueryExecutorImpl.java:1553)
    at org.postgresql.core.v3.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1876)
    at org.postgresql.core.v3.QueryExecutorImpl.sendQuery(QueryExecutorImpl.java:1439)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
</code>```

The exception seem to be ultimately caused by a 16-bit limit on the number of values in the SELECT IN (?) clause, that is generated by Sprint Data JDBC upon using findAllById.

Am I supposed to partition the list of IDs myself? Shouldn't the CrudRepository.findAllById handle this correctly in a fashion compatible with the underlying database dialect?

答:
Am I supposed to partition the list of IDs myself?

Yes, assuming this kind of query makes sense in the first place.

Spring Data JDBC currently creates a straight forward select ... where id in (..) query which in turn is limited by the capabilities of the underlying database/JDBC driver.

With the apparent limit being ~216 for Postgres there doesn't seem to be much need for special handling in Spring Data JDBC since looking for so many ids in a single select seems rare enough to justify some manual coding.

Body:
I am using the Spring Data JDBC (version 1.1.6) method CrudRepository.findAllById to load entities from a database with a large number of IDs. The underlying database connection uses a Postgres database. The invocation of the method raises a PSQLException:

2020-05-28 05:58:35,260 WARN com.zaxxer.hikari.pool.ProxyConnection [task-2] HikariPool-1 - Connection org.postgresql.jdbc.PgConnection@1224f39f marked as broken because of SQLSTATE(08006), ErrorCode(0)
org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:358)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
...
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 137525
    at org.postgresql.core.PGStream.sendInteger2(PGStream.java:275)
    at org.postgresql.core.v3.QueryExecutorImpl.sendParse(QueryExecutorImpl.java:1553)
    at org.postgresql.core.v3.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1876)
    at org.postgresql.core.v3.QueryExecutorImpl.sendQuery(QueryExecutorImpl.java:1439)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)

The exception seem to be ultimately caused by a 16-bit limit on the number of values in the SELECT IN (?) clause, that is generated by Sprint Data JDBC upon using findAllById.

Am I supposed to partition the list of IDs myself? Shouldn't the CrudRepository.findAllById handle this correctly in a fashion compatible with the underlying database dialect?


问:
Why cant Puppeteer find this link element on page?
^^UPDATE^^

Willing to pay someone to walk me through this, issue posted on codeMentor.io: https://www.codementor.io/u/dashboard/my-requests/9j42b83f0p

I've been looking to click on the element:

```<code><a id="isc_LinkItem_1$20j" href="javascript:void" target="javascript" tabindex="2"
onclick="if(window.isc_LinkItem_1) return isc_LinkItem_1.$30i(event);"
$9a="$9d">Reporting</a>
</code>```

In: https://stackblitz.com/edit/js-nzhhbk
(I haven't included the acutal page because its behind a username & pass)

seems easy enough

----------------------------------------------------------------------

solution1:

```<code>page.click('[id=isc_LinkItem_1$20j]') //not a valid selector
</code>```

solution2:

```<code>const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
} //link not found
</code>```

----------------------------------------------------------------------

I have looked at every which way to select and click it and it says it isn't in the document even though it clearly is (verified by inspecting the html in chrome dev tools and calling:page.evaluate(() => document.body.innerHTML))

**tried to see if it was in an iframe

**tried to select by id

**tried to select by inner text

**tried to console log the body in the browser (console logging not               working verified on the inspect _element) //nothing happens

**tried to create an alert with body text by using:
 _evaluate(() => alert(document)) // nothing happens

**tried to create an alert to test to see if javascript can be injected by:
 _evaluate(() => alert('works')) // nothing happens

**also tried this: How to select elements within an iframe element in Puppeteer // doesn't work

Here is the code I have built so far

```<code>const page = await browser.newPage();

const login1url =
    'https://np3.nextiva.com/NextOSPortal/ncp/landing/landing-platform';
await page.goto(login1url);
await page.waitFor(1000);
await page.type('[name=loginUserName', 'itsaSecretLol');
await page.type('[name=loginPassword]', 'nopeHaha');
await page.click('[type=submit]');
await page.waitForNavigation();
const login3url = 'https://np3.nextiva.com/NextOSPortal/ncp/admin/dashboard';
await page.goto(login3url);
await page.click('[id=hdr_users]');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/manageUsers');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/garrettmrg');
await page.waitFor(2000);
await page.click('[id=loginAsUser]');
await page.waitFor(2000);
await page.click('[id=react-select-5--value');
await page.waitFor(1000);
await page.click('[id=react-select-5--option-0]');
await page.waitFor(20000);
const elementHandle = await page.$('iframe[id=callcenter]');
const frame = await elementHandle.contentFrame();
const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
}
</code>```

答:
due isc_LinkItem_1$20j is not a valid selector, maybe you can try finding elements STARTING WITH isc_LinkItem_1 , like this

```<code>await page.waitForSelector("[id^=isc_LinkItem_1]", {visible: true, timeout: 30000});
await page.click("[id?=isc_LinkItem_1]);
</code>```

?

Body:
^^UPDATE^^

Willing to pay someone to walk me through this, issue posted on codeMentor.io: https://www.codementor.io/u/dashboard/my-requests/9j42b83f0p

I've been looking to click on the element:

Reporting

In: https://stackblitz.com/edit/js-nzhhbk
(I haven't included the acutal page because its behind a username & pass)

seems easy enough

----------------------------------------------------------------------

solution1:

page.click('[id=isc_LinkItem_1$20j]') //not a valid selector

solution2:

const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
} //link not found

----------------------------------------------------------------------

I have looked at every which way to select and click it and it says it isn't in the document even though it clearly is (verified by inspecting the html in chrome dev tools and calling:page.evaluate(() => document.body.innerHTML))

**tried to see if it was in an iframe

**tried to select by id

**tried to select by inner text

**tried to console log the body in the browser (console logging not               working verified on the inspect _element) //nothing happens

**tried to create an alert with body text by using:
 _evaluate(() => alert(document)) // nothing happens

**tried to create an alert to test to see if javascript can be injected by:
 _evaluate(() => alert('works')) // nothing happens

**also tried this: How to select elements within an iframe element in Puppeteer // doesn't work

Here is the code I have built so far

const page = await browser.newPage();

const login1url =
    'https://np3.nextiva.com/NextOSPortal/ncp/landing/landing-platform';
await page.goto(login1url);
await page.waitFor(1000);
await page.type('[name=loginUserName', 'itsaSecretLol');
await page.type('[name=loginPassword]', 'nopeHaha');
await page.click('[type=submit]');
await page.waitForNavigation();
const login3url = 'https://np3.nextiva.com/NextOSPortal/ncp/admin/dashboard';
await page.goto(login3url);
await page.click('[id=hdr_users]');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/manageUsers');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/garrettmrg');
await page.waitFor(2000);
await page.click('[id=loginAsUser]');
await page.waitFor(2000);
await page.click('[id=react-select-5--value');
await page.waitFor(1000);
await page.click('[id=react-select-5--option-0]');
await page.waitFor(20000);
const elementHandle = await page.$('iframe[id=callcenter]');
const frame = await elementHandle.contentFrame();
const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
}

Body:
due isc_LinkItem_1$20j is not a valid selector, maybe you can try finding elements STARTING WITH isc_LinkItem_1 , like this

await page.waitForSelector("[id^=isc_LinkItem_1]", {visible: true, timeout: 30000});
await page.click("[id?=isc_LinkItem_1]);

?


问:
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: </p>

```<code>typedef std::map<std::string, std::map<std::string, int> > CSVData;
</code>```

<p>Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this? </p>

答:
I tend to avoid pure typedef outside a class (apart from the typical alias to save some typing in a file/function).

There are two (closely related) reasons, and both stems from the same fact: I can control what operations/methods are available on my class:

I can give them proper names, pertaining to the problem domain, instead of generic names

I can control the implementations of those methods: maintaining invariants, adding debugging informations / assertions

Of course, I would then use the typedef within the class, and delegate the bulk of the implementation to those already coding methods, but do not sneer at the thin layer on top of it. It's valuable.

Title: STL + typedefs vs. OOP, best practices?

Body:
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:

typedef std::map<std::string, std::map<std::string, int> > CSVData;

Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?


问:
antd menu icons API not working. Does not render
im trying to render a a side menu with a submenu , however i soon realize that the icon api is not working:

```<code>                  <Menu.Item key="1" >
                        <HomeOutlined />
                        <span>Home</span>
                        <Link to='/' />
                    </Menu.Item>
</code>```

This is one of the menu items , it renders correctly if i were to place the icon within the menu.item.
However when i do this :

```<code>                   <Menu.Item key="1" icon={<HomeOutlined/>}>
                        <span>Home</span>
                        <Link to='/' />
                    </Menu.Item>
</code>```

The icon no longer shows. I have no issues for the first approach , however when i try to tranplant the 1st approach to a submenu :

```<code>             <SubMenu key="sub1" title="Settings">
                        <SettingFilled />
                    <Menu.Item key="7" onClick={this.props.logout}>
                        <span>Logout</span>
                    </Menu.Item>
                    </SubMenu>
</code>```

It would render the icon inside the inner dropdown instead of where its supposed to be

答:
You can try this, the icon has to be part of the title parameter in order for the icon to be shown correctly when the menu is not expanded. :-)</p>

```<code>  <SubMenu key="sub1" title={<span><UserOutlined /><span>Settings</span></span>}>
        <SettingFilled />
        <Menu.Item key="7" onClick={this.props.logout}>
             <span>Logout</span>
        </Menu.Item>
  </SubMenu>
</code>```

Body:
im trying to render a a side menu with a submenu , however i soon realize that the icon api is not working:

                  <Menu.Item key="1" >
                        <HomeOutlined />
                        Home
                        <Link to='/' />
                    </Menu.Item>

This is one of the menu items , it renders correctly if i were to place the icon within the menu.item.
However when i do this :

                   <Menu.Item key="1" icon={<HomeOutlined/>}>
                        Home
                        <Link to='/' />
                    </Menu.Item>

The icon no longer shows. I have no issues for the first approach , however when i try to tranplant the 1st approach to a submenu :

             <SubMenu key="sub1" title="Settings">
                        <SettingFilled />
                    <Menu.Item key="7" onClick={this.props.logout}>
                        Logout
                    </Menu.Item>
                    </SubMenu>

It would render the icon inside the inner dropdown instead of where its supposed to be

Body:
You can try this, the icon has to be part of the title parameter in order for the icon to be shown correctly when the menu is not expanded. :-)

  <SubMenu key="sub1" title={<span><UserOutlined /><span>Settings</span></span>}>
        <SettingFilled />
        <Menu.Item key="7" onClick={this.props.logout}>
             <span>Logout</span>
        </Menu.Item>
  </SubMenu>


问:
Passing props from Laravel Blade to Vue.Js return undefined
I tried to pass props from Laravel blade to Vue element, tried to use:
:data or
data
both didn't work.

Returns undefined on Vue Devtool.

file.blade.php

```<code><div id="truthchallenge">
  <truth-challenge data="datastring" />
</div>
</code>```

truthchallenge.js (main.js)

```<code>import Vue from 'vue'
import router from '../router'
import TruthChallenge from './views/TruthChallenge'

new Vue({
  router,
  render: h => h(TruthChallenge)
}).$mount('#truthchallenge')
</code>```

TruthChallenge.vue

```<code><script>
export default {
  name: 'truth-challenge',
  props: {
    data: String
  }
}
</script>
</code>```

I tried to pass props from a vue.js  to child, it works, but not from the Laravel blade.
Do you have clues about what doesn't work on my code?

答:
If I understood correctly, you are trying to pass php variable into Vue template?

Try it like this:

```<code><truth-challenge :data="{{ $data }}"/>
</code>```

Body:
I tried to pass props from Laravel blade to Vue element, tried to use:
:data or
data
both didn't work.

Returns undefined on Vue Devtool.

file.blade.php

  <truth-challenge data="datastring" />

truthchallenge.js (main.js)

import Vue from 'vue'
import router from '../router'
import TruthChallenge from './views/TruthChallenge'

new Vue({
  router,
  render: h => h(TruthChallenge)
}).$mount('#truthchallenge')

TruthChallenge.vue

I tried to pass props from a vue.js  to child, it works, but not from the Laravel blade.
Do you have clues about what doesn't work on my code?

Body:
If I understood correctly, you are trying to pass php variable into Vue template?

Try it like this:

<truth-challenge :data="{{ $data }}"/>


问:
How to do background sync instead of fetch requests on UI changes?
For example, let's take a simple web application with comments feature. In my understanding, when a user posts a new comment, the following would occur:

display UI loader;

update the front-end state;

send a fetch request to the API to post a new comment;

Wait for the response;

send another fetch request to the API to request the new list of comments;

waiting;

update the front-end state with new comments;

update UI to reflect the new state with a new comment;

And the user needs to wait while front-end app interacts with back-end on almost every data change. The same way we did it earlier with PHP/Python/Ruby, ajax, server-side rendering and templates.

That makes me think what's the point of adding so much front-end complexity with something like react, when the result is basically the same.

My question is: are there any alternative approaches to this? Is it possible instead to do the above case the following way:

user clicks to post a comment;

update the front-end state;

update UI to reflect the new state with a new comment;

sync front-end state with API DB in the background;

答:
I get it that you think it's waste of time for users to wait until requests are successful. However, isn't it more important to stop users from keeping making bad requests to the server?

So, what I would do is just to stop fetching data from the database every after users make requests.

Fetching the DB data to begin with and store them in redux states

Make requests to the DB while holding users from doing anything

Make changes to the redux state if the requests are successful

But what you want to do could be done like this

Fetching the DB data to begin with and store them in redux states

Make changes to the redux state while making requests to the DB in the background

Depending on whether the requests fail or not, roll back the change users made from the redux state


问:
How does one get the sprite to stop accelerating after colliding with the wall?
Making a platform game and expect the sprite to collide with the wall and be aligned with the top of the wall and not accelerate through the wall but the moment it collides with the wall it slowly sinks through the wall,  after testing it has shown that during the sinking part it does not actually collide with the wall. At the moment I've just been focusing on gravity and the y axis.

```<code>import os
import pygame
import time
import random
vec = pygame.math.Vector2

class player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image=pygame.image.load("rectmo.png").convert_alpha()
        self.image=pygame.transform.scale(self.image, (25,100))
        self.rect = self.image.get_rect()
        self.rect.center = (width/2,height/2)
        self.pos = vec(width/2,height/2)
        self.vel = vec(0,0)
        self.acc = vec(0,0)

    def update(self):

        user_input=pygame.key.get_pressed()

        if user_input[pygame.K_d]:
            self.acc.x=player_acc
        if user_input[pygame.K_a]:
            self.acc.x=-player_acc

        for wall in walls:
            if self.rect.colliderect(wall.rect)==True:
                if self.acc.x > 0:
                    self.rect.right=wall.rect.left
                    self.vel.x=0
                if self.acc.x < 0:
                    self.rect.left=wall.rect.right
                    self.vel.x=0
                if self.acc.y > 0:
                    self.rect.bottom=wall.rect.top
                    self.acc.y=0
                    self.vel.y=0
                if self.pos.y < 0:
                    self.rect.top=wall.rect.bottom
                    self.acc.y=0
            if self.rect.colliderect(wall.rect)==False:
                #gravity
                self.acc = vec(0,0.5)

        #adds Friction
        self.acc.x += self.vel.x * player_friction
        #applying accelerating equation
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc
        self.rect.center = self.pos
</code>```

I can't tell if the way I made the wall is the problem so I'll just leave it here.

```<code>class Wall(object):
    def __init__(self,wx,wy):
        walls.append(self)
        self.rect= pygame.Rect(wx,wy,30,30)
    def reset_wall(self):
        self.active = False

walls=[]

levels= [['WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
   'W  E                                         W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W             W                              W',
   'W             W                              W',
   'W             W                              W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             WWWWWWWWWWWWWWWWWWW            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
 ]]

x=y=0
level=random.choice(levels)
for row in level:
    for col in row:
        if col=='W':
            Wall(x,y)
        if col=='E':
            end_rect=pygame.Rect(x,y,30,30)
        x += 30
    y+=30
    x=0
</code>```

Here's the the whole code for testing:

```<code>import os
import pygame
import time
import random
vec = pygame.math.Vector2

class player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image=pygame.image.load("rectmo.png").convert_alpha()
        self.image=pygame.transform.scale(self.image, (25,100))
        self.rect = self.image.get_rect()
        self.rect.center = (width/2,height/2)
        self.pos = vec(width/2,height/2)
        self.vel = vec(0,0)
        self.acc = vec(0,0)

    def update(self):

        user_input=pygame.key.get_pressed()

        if user_input[pygame.K_d]:
            self.acc.x=player_acc
        if user_input[pygame.K_a]:
            self.acc.x=-player_acc

        for wall in walls:
            if self.rect.colliderect(wall.rect)==True:
                if self.acc.x > 0:
                    self.rect.right=wall.rect.left
                    self.vel.x=0
                if self.acc.x < 0:
                    self.rect.left=wall.rect.right
                    self.vel.x=0
                if self.acc.y > 0:
                    self.rect.bottom=wall.rect.top
                    self.vel.y=0
                if self.pos.y < 0:
                    self.rect.top=wall.rect.bottom
                    self.vel.y=0
            if self.rect.colliderect(wall.rect)==False:
                self.acc = vec(0,0.5)

        #adds Friction
        self.acc.x += self.vel.x * player_friction
        #applying accelerating equation
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc
        self.rect.center = self.pos

class Wall(object):
    def __init__(self,wx,wy):
        walls.append(self)
        self.rect= pygame.Rect(wx,wy,30,30)
    def reset_wall(self):
        self.active = False

os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()

pygame.display.set_caption('A Game')
width = 1366
height= 768
screen=pygame.display.set_mode((width,height))

clock = pygame.time.Clock()
walls=[]
player_acc=0.5
player_friction=-0.05
rectmo=player()

rectmo.rect.x=500
rectmo.rect.y=400
main_colour=(0,0,0)
colour=main_colour
wall_colour=(255,255,255)
current_score=0

levels= [['WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
   'W  E                                         W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W             W                              W',
   'W             W                              W',
   'W             W                              W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             WWWWWWWWWWWWWWWWWWW            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
 ]]

x=y=0
level=random.choice(levels)
for row in level:
    for col in row:
        if col=='W':
            Wall(x,y)
        if col=='E':
            end_rect=pygame.Rect(x,y,30,30)
        x += 30
    y+=30
    x=0

running=True

while running==True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    rectmo.update()

    if running==True:
        screen.fill(main_colour)
        for wall in walls:
            pygame.draw.rect(screen, wall_colour,wall.rect)
        pygame.draw.rect(screen,(255,0,0),end_rect)
        pygame.draw.rect(screen,colour,rectmo.rect)

        all_sprites_list = pygame.sprite.Group()
        all_sprites_list.add(rectmo)
        all_sprites_list.draw(screen)
        pygame.display.flip()

</code>```

答:
Chang the position of the player, before evaluation the collisions.
If the player collides, then you've to update self.rect and you have to synchronize self.pos to  self.rect.center. For instnace:

if self.val.x > 0:
    self.rect.right=wall.rect.left
    self.vel.x=0
    self.pos = vec(self.rect.center)
```

<p>Evaluate if the player stays on the ground, by testing if the player would intersect the wall if he would be located 1 pixel below:</p>

<pre class="lang-py prettyprint-override"><code>test_rect = pygame.Rect(self.rect.x, self.rect.y+1, self.rect.width, self.rect.height)
if test_rect.colliderect(wall.rect):
   on_ground = True
</code>```

Set the acceleration in y direction dependent on the state on_ground:

if on_ground:
    self.acc.y = 0
elif self.acc.y == 0:
    self.acc.y = 0.5
```

<p>Method <code>update</code>:</p>

<pre class="lang-py prettyprint-override"><code>class player(pygame.sprite.Sprite):
    # [...]

    def update(self):

        user_input=pygame.key.get_pressed()

        self.acc.x = 0
        if user_input[pygame.K_d]:
            self.acc.x=player_acc
        if user_input[pygame.K_a]:
            self.acc.x=-player_acc

        self.vel.x = self.vel.x * 0.95 + self.acc.x
        self.vel.y += self.acc.y
        self.pos += self.vel
        self.rect.center = self.pos

        on_ground = False
        for wall in walls:
            if self.rect.colliderect(wall.rect)==True:
                if self.vel.x > 0:
                    self.rect.right=wall.rect.left
                    self.vel.x=0
                    self.pos = vec(self.rect.center)
                if self.vel.x < 0:
                    self.rect.left=wall.rect.right
                    self.vel.x=0
                    self.pos = vec(self.rect.center)
                if self.vel.y > 0:
                    self.rect.bottom=wall.rect.top
                    self.vel.y=0
                    self.pos = vec(self.rect.center)
                if self.vel.y < 0:
                    self.rect.top=wall.rect.bottom
                    self.vel.y=0
                    self.pos = vec(self.rect.center)

            test_rect = pygame.Rect(self.rect.x, self.rect.y+1, self.rect.width, self.rect.height)
            if test_rect.colliderect(wall.rect):
                on_ground = True

        if on_ground:
            self.acc.y = 0
        elif self.acc.y == 0:
            self.acc.y = 0.5
</code>```

Body:
Making a platform game and expect the sprite to collide with the wall and be aligned with the top of the wall and not accelerate through the wall but the moment it collides with the wall it slowly sinks through the wall,  after testing it has shown that during the sinking part it does not actually collide with the wall. At the moment I've just been focusing on gravity and the y axis.

import os
import pygame
import time
import random
vec = pygame.math.Vector2

class player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image=pygame.image.load("rectmo.png").convert_alpha()
        self.image=pygame.transform.scale(self.image, (25,100))
        self.rect = self.image.get_rect()
        self.rect.center = (width/2,height/2)
        self.pos = vec(width/2,height/2)
        self.vel = vec(0,0)
        self.acc = vec(0,0)

    def update(self):

        user_input=pygame.key.get_pressed()

        if user_input[pygame.K_d]:
            self.acc.x=player_acc
        if user_input[pygame.K_a]:
            self.acc.x=-player_acc

        for wall in walls:
            if self.rect.colliderect(wall.rect)==True:
                if self.acc.x > 0:
                    self.rect.right=wall.rect.left
                    self.vel.x=0
                if self.acc.x < 0:
                    self.rect.left=wall.rect.right
                    self.vel.x=0
                if self.acc.y > 0:
                    self.rect.bottom=wall.rect.top
                    self.acc.y=0
                    self.vel.y=0
                if self.pos.y < 0:
                    self.rect.top=wall.rect.bottom
                    self.acc.y=0
            if self.rect.colliderect(wall.rect)==False:
                #gravity
                self.acc = vec(0,0.5)

        #adds Friction
        self.acc.x += self.vel.x * player_friction
        #applying accelerating equation
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc
        self.rect.center = self.pos

I can't tell if the way I made the wall is the problem so I'll just leave it here.

class Wall(object):
    def __init__(self,wx,wy):
        walls.append(self)
        self.rect= pygame.Rect(wx,wy,30,30)
    def reset_wall(self):
        self.active = False

walls=[]

levels= [['WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
   'W  E                                         W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W             W                              W',
   'W             W                              W',
   'W             W                              W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             WWWWWWWWWWWWWWWWWWW            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
 ]]

x=y=0
level=random.choice(levels)
for row in level:
    for col in row:
        if col=='W':
            Wall(x,y)
        if col=='E':
            end_rect=pygame.Rect(x,y,30,30)
        x += 30
    y+=30
    x=0

Here's the the whole code for testing:

import os
import pygame
import time
import random
vec = pygame.math.Vector2

class player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image=pygame.image.load("rectmo.png").convert_alpha()
        self.image=pygame.transform.scale(self.image, (25,100))
        self.rect = self.image.get_rect()
        self.rect.center = (width/2,height/2)
        self.pos = vec(width/2,height/2)
        self.vel = vec(0,0)
        self.acc = vec(0,0)

    def update(self):

        user_input=pygame.key.get_pressed()

        if user_input[pygame.K_d]:
            self.acc.x=player_acc
        if user_input[pygame.K_a]:
            self.acc.x=-player_acc

        for wall in walls:
            if self.rect.colliderect(wall.rect)==True:
                if self.acc.x > 0:
                    self.rect.right=wall.rect.left
                    self.vel.x=0
                if self.acc.x < 0:
                    self.rect.left=wall.rect.right
                    self.vel.x=0
                if self.acc.y > 0:
                    self.rect.bottom=wall.rect.top
                    self.vel.y=0
                if self.pos.y < 0:
                    self.rect.top=wall.rect.bottom
                    self.vel.y=0
            if self.rect.colliderect(wall.rect)==False:
                self.acc = vec(0,0.5)

        #adds Friction
        self.acc.x += self.vel.x * player_friction
        #applying accelerating equation
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc
        self.rect.center = self.pos

class Wall(object):
    def __init__(self,wx,wy):
        walls.append(self)
        self.rect= pygame.Rect(wx,wy,30,30)
    def reset_wall(self):
        self.active = False

os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()

pygame.display.set_caption('A Game')
width = 1366
height= 768
screen=pygame.display.set_mode((width,height))

clock = pygame.time.Clock()
walls=[]
player_acc=0.5
player_friction=-0.05
rectmo=player()

rectmo.rect.x=500
rectmo.rect.y=400
main_colour=(0,0,0)
colour=main_colour
wall_colour=(255,255,255)
current_score=0

levels= [['WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
   'W  E                                         W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W             W                              W',
   'W             W                              W',
   'W             W                              W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             W                 W            W',
   'W             WWWWWWWWWWWWWWWWWWW            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'W                                            W',
   'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
 ]]

x=y=0
level=random.choice(levels)
for row in level:
    for col in row:
        if col=='W':
            Wall(x,y)
        if col=='E':
            end_rect=pygame.Rect(x,y,30,30)
        x += 30
    y+=30
    x=0

running=True

while running==True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    rectmo.update()

    if running==True:
        screen.fill(main_colour)
        for wall in walls:
            pygame.draw.rect(screen, wall_colour,wall.rect)
        pygame.draw.rect(screen,(255,0,0),end_rect)
        pygame.draw.rect(screen,colour,rectmo.rect)

        all_sprites_list = pygame.sprite.Group()
        all_sprites_list.add(rectmo)
        all_sprites_list.draw(screen)
        pygame.display.flip()

Body:
Chang the position of the player, before evaluation the collisions.
If the player collides, then you've to update self.rect and you have to synchronize self.pos to  self.rect.center. For instnace:

if self.val.x > 0:
    self.rect.right=wall.rect.left
    self.vel.x=0
    self.pos = vec(self.rect.center)

Evaluate if the player stays on the ground, by testing if the player would intersect the wall if he would be located 1 pixel below:

test_rect = pygame.Rect(self.rect.x, self.rect.y+1, self.rect.width, self.rect.height)
if test_rect.colliderect(wall.rect):
   on_ground = True

Set the acceleration in y direction dependent on the state on_ground:

if on_ground:
    self.acc.y = 0
elif self.acc.y == 0:
    self.acc.y = 0.5

Method update:

class player(pygame.sprite.Sprite):
    # [...]

    def update(self):

        user_input=pygame.key.get_pressed()

        self.acc.x = 0
        if user_input[pygame.K_d]:
            self.acc.x=player_acc
        if user_input[pygame.K_a]:
            self.acc.x=-player_acc

        self.vel.x = self.vel.x * 0.95 + self.acc.x
        self.vel.y += self.acc.y
        self.pos += self.vel
        self.rect.center = self.pos

        on_ground = False
        for wall in walls:
            if self.rect.colliderect(wall.rect)==True:
                if self.vel.x > 0:
                    self.rect.right=wall.rect.left
                    self.vel.x=0
                    self.pos = vec(self.rect.center)
                if self.vel.x < 0:
                    self.rect.left=wall.rect.right
                    self.vel.x=0
                    self.pos = vec(self.rect.center)
                if self.vel.y > 0:
                    self.rect.bottom=wall.rect.top
                    self.vel.y=0
                    self.pos = vec(self.rect.center)
                if self.vel.y < 0:
                    self.rect.top=wall.rect.bottom
                    self.vel.y=0
                    self.pos = vec(self.rect.center)

            test_rect = pygame.Rect(self.rect.x, self.rect.y+1, self.rect.width, self.rect.height)
            if test_rect.colliderect(wall.rect):
                on_ground = True

        if on_ground:
            self.acc.y = 0
        elif self.acc.y == 0:
            self.acc.y = 0.5


问:
echoing text field value in a while loop
```<code>echo " <table bgcolor='#d3fcfe'   align='center'>  ";

while ($row = mysql_fetch_array($result)) {

echo '</div> <tr onmouseout="this.bgColor=\'#d3fcfe\';"  onmouseover= "this   .bgColor=\'#fffdcd\';" >  ';
 $numq2=$row['username'] ;

{
echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
}

echo '  </table>';
}
</code>```

<p>i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script? </p>

答:
try</p>

```<code>echo <td ><div class="iddiv"> <input name="" type="text" value="<?php echo $numq2;?>" />   <div></td>';
</code>```

Body:
echo "
  ";

while ($row = mysql_fetch_array($result)) {

echo '

  ';
 $numq2=$row['username'] ;

{
echo '
 <input name="" type="text" value="$numq2" />
    	 ';
}

echo '
';
}

i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script?

Body:
try

echo <td ><div class="iddiv"> <input name="" type="text" value="<?php echo $numq2;?>" />   <div></td>';


问:
Can I use expo packages or libraries in bare work flow, I used some permissions and
Can I use expo packages or libraries in bare work flow,  I used some permissions and apploading these type of blah blah packages in my expo project and ejected to bare work flow, after running react-native run-android getting error expo require expo sdk to run</p>

答:
what SDK version were you on when you ejected? if you are not using the latest sdk version (37 at the time of writing), i would recommend reverting the eject and running expo upgrade then ejecting again. the process is a lot smoother in 37 and will continue to get better over time.

you can absolutely use nearly every library in bare react native apps! but you can't use everything that's available from the expo package itself, we're almost done removing everything from there but they may be some leftovers. check your project to see what you're importing from "expo" and replace those with alternatives. imports from "expo-*" will work great.


问:
Re-uploading a file with AJAX after it was changed causes net::ERR_UPLOAD_FILE_CHANGED in Chrome
I have a simple HTML form that sends an selected file via AJAX to an API endpoint.

If I do the following steps:

Press the Upload button and make an POST request to upload the file

Change the selected file on the filesystem (in a text editor), without picking it again in the file picker.

Press the Upload button again, and make as second POST request

Chrome will fail the second request with an error: net::ERR_UPLOAD_FILE_CHANGED. Note that if you change the file before the initial upload, the file will be uploaded without a problem. The error happens only on the second upload, when you change the file after an initial successful upload. I am testing this with CSV files, and changing them in a text editor.

There does not seem to be a way to isolate that error.

Is there any way around this?

If not, is it possible to catch this specific error, and display a meaningful message to the user. The error that Fetch returns in the promise has no specific info about this. The only place where I see the ERR_UPLOAD_FILE_CHANGED is in the browser dev console.

I am pretty sure that there was not any problem with this about a year ago (early 2019), as the possibility to re-upload a changed file, played in nicely in our UI flow. Now we need to force the user to pick the file again. So my assumption that this was introduced with a recent chrome update.

Here is a simplified snippet of the code:

```<code><html>
<head>
        <script type='text/javascript'>
        document.addEventListener("DOMContentLoaded", function(){

                const button = document.querySelector('#btnSubmit');

                button.addEventListener('click', () => {
                        const form = new FormData(document.querySelector('#theForm'));
                        const url = '/my-api'
                        const request = new Request(url, {
                                method: 'POST',
                                body: form
                        });

                        fetch(request).then(function() {
                                console.log("ok");
                        }).catch(function(err) {
                                console.log(err);
                        });
                });
        });
        </script>

</head>
<body>
        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" /></td>
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>
</body>
</html>
</code>```

EDIT: The bug is marked as WontFix on bugs.chromium.org: https://bugs.chromium.org/p/chromium/issues/detail?id=1086707#c7

答:
I would just check file.lastModified between the upload button clicks and if different reset the form values.

https://developer.mozilla.org/en-US/docs/Web/API/File/lastModified

A better solution would be to read the file into an ArrayBuffer and upload that.

Body:
I have a simple HTML form that sends an selected file via AJAX to an API endpoint.

If I do the following steps:

Press the Upload button and make an POST request to upload the file

Change the selected file on the filesystem (in a text editor), without picking it again in the file picker.

Press the Upload button again, and make as second POST request

Chrome will fail the second request with an error: net::ERR_UPLOAD_FILE_CHANGED. Note that if you change the file before the initial upload, the file will be uploaded without a problem. The error happens only on the second upload, when you change the file after an initial successful upload. I am testing this with CSV files, and changing them in a text editor.

There does not seem to be a way to isolate that error.

Is there any way around this?

If not, is it possible to catch this specific error, and display a meaningful message to the user. The error that Fetch returns in the promise has no specific info about this. The only place where I see the ERR_UPLOAD_FILE_CHANGED is in the browser dev console.

I am pretty sure that there was not any problem with this about a year ago (early 2019), as the possibility to re-upload a changed file, played in nicely in our UI flow. Now we need to force the user to pick the file again. So my assumption that this was introduced with a recent chrome update.

Here is a simplified snippet of the code:

        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" />
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>

EDIT: The bug is marked as WontFix on bugs.chromium.org: https://bugs.chromium.org/p/chromium/issues/detail?id=1086707#c7


问:
Laravel: Form validation string-length error messages cause exception
When trying to implement Laravel's length based validation

```<code>'password' => array(
    'required',
    'alpha_dash',
    'Min:7'
)
</code>```

and outputting error messages in my view

```<code>{{
    $errors->first(
        'password',
        '<span class="error">:message</span>'
    )
}}
</code>```

I get

```<code>Unhandled Exception
Message:
Array to string conversion
Location:
_avalog\laravel\messages.php on line 188
Stack Trace:
#0 _avalog\laravel\laravel.php(42): Laravel\Error::native(8, 'Array to string...', '_avalog...', 188)
#1 [internal function]: Laravel\{closure}(8, 'Array to string...', '_avalog...', 188, Array)
#2 _avalog\laravel\messages.php(188): str_replace(':message', Array, 'get('password', 'get()
</code>```

Debugging, it appears to be true.  If I print_r( $validation );

```<code>Laravel\Validator Object (
    [attributes] => Array (
        [username] => fred
        [email] =>
        [password] => asd
        [csrf_token] => DWg3CUfqtMZkIRfyZXNEqygvWUHsGS9SQMue2V4S
    )
    [errors] => Laravel\Messages Object (
        [messages] => Array (
            [email] => Array (
                [0] => The email field is required.
            )
            [password] => Array (
                [0] => Array (
                    [numeric] => The password must be at least 7.
                    [file] => The password must be at least 7 kilobytes.
                    [string] => The password must be at least 7 characters.
                )
            )
    )
    [format] => :message
)
</code>```

You can see that messages does in fact contain an array for password which appears to be dependent upon input type, even though I've specified in the rule it is alphadash

```<code>[password] => Array (
    [0] => Array (
        [numeric] => The password must be at least 7.
        [file] => The password must be at least 7 kilobytes.
        [string] => The password must be at least 7 characters.
    )
)
</code>```

Whereas the rest, do not

```<code>[email] => Array (
    [0] => The email format is invalid.
)
</code>```

Looking at messages.php in Laravel framework, it has nothing to handle such array-based messaging so I assume I am doing something wrong before it gets there, but I don't know what.

Thanks for your help.

答:
'password.min' => "Password can not be less than 6 characters.",

```<code>$custom_validation_messages = array(
  'password.min' => "Password can not be less than 6 characters.",
  'password.required' => "Password is required"
);

   $validator = Validator::make($data, [
                //'email'          => ['required','unique:users,email','email','max:255'],
   'email'          => ['required','email','max:255'],
   'password'       => 'required|min:6|confirmed'

 ],$custom_validation_messages);
</code>```

Body:
When trying to implement Laravel's length based validation

'password' => array(
    'required',
    'alpha_dash',
    'Min:7'
)

and outputting error messages in my view

{{
    $errors->first(
        'password',
        ':message'
    )
}}

I get

Unhandled Exception
Message:
Array to string conversion
Location:
_avalog\laravel\messages.php on line 188
Stack Trace:
#0 _avalog\laravel\laravel.php(42): Laravel\Error::native(8, 'Array to string...', '_avalog...', 188)
#1 [internal function]: Laravel\{closure}(8, 'Array to string...', '_avalog...', 188, Array)
#2 _avalog\laravel\messages.php(188): str_replace(':message', Array, 'get('password', 'get()

Debugging, it appears to be true.  If I print_r( $validation );

Laravel\Validator Object (
    [attributes] => Array (
        [username] => fred
        [email] =>
        [password] => asd
        [csrf_token] => DWg3CUfqtMZkIRfyZXNEqygvWUHsGS9SQMue2V4S
    )
    [errors] => Laravel\Messages Object (
        [messages] => Array (
            [email] => Array (
                [0] => The email field is required.
            )
            [password] => Array (
                [0] => Array (
                    [numeric] => The password must be at least 7.
                    [file] => The password must be at least 7 kilobytes.
                    [string] => The password must be at least 7 characters.
                )
            )
    )
    [format] => :message
)

You can see that messages does in fact contain an array for password which appears to be dependent upon input type, even though I've specified in the rule it is alphadash

[password] => Array (
    [0] => Array (
        [numeric] => The password must be at least 7.
        [file] => The password must be at least 7 kilobytes.
        [string] => The password must be at least 7 characters.
    )
)

Whereas the rest, do not

[email] => Array (
    [0] => The email format is invalid.
)

Looking at messages.php in Laravel framework, it has nothing to handle such array-based messaging so I assume I am doing something wrong before it gets there, but I don't know what.

Thanks for your help.

Body:
'password.min' => "Password can not be less than 6 characters.",

$custom_validation_messages = array(
  'password.min' => "Password can not be less than 6 characters.",
  'password.required' => "Password is required"
);

   $validator = Validator::make($data, [
                //'email'          => ['required','unique:users,email','email','max:255'],
   'email'          => ['required','email','max:255'],
   'password'       => 'required|min:6|confirmed'

 ],$custom_validation_messages);


问:
Jmeter - Using varible: from JDBC request into another JDBC query under loop
For the purpose of my test, Based on the JDBC query id's i need to pass to another query, located under ForEach Controller.

Results return from query1

```<code>url id
https://pay1.com/ 1
https://pay3.com/ 3
https://pay8.com/ 8
</code>```

Based on the ID returned, i need to pass to another query:

```<code>select *
FROM transaction
WHERE id = '${id_1}'
</code>```

If i try like: ${id_1} or ${id_3} is working fine.

But, how can i pass dynamically to the next query, without hard coding the index?

答:
ForEach Controller has pre-defined variable exposing the current iteration, as per documentation:

JMeter will expose the looping index as a variable named __jm__<Name of your element>__idx. So for example, if your Loop Controller is named FEC, then you can access the looping index through ${__jm__FEC__idx}. Index starts at 0

So

given your ForEach Controller name is ForEach Controller you can access its current loop as ${__jm__ForEach Controller__idx}

given indices are zero-based and your variables are 1-based you need to add 1 to the current index which can be done using __intSum() function

and finally you will need to use __V() function in order to evaluate the resulting expression using your id_ prefix

Putting everything together, the code you're looking for would be something like:

```<code>${__V(id_${__intSum(${__jm__ForEach Controller__idx},1,)},)}
</code>```

Demo:

More information: Here’s What to Do to Combine Multiple JMeter Variables

Body:
For the purpose of my test, Based on the JDBC query id's i need to pass to another query, located under ForEach Controller.

Results return from query1

url id
https://pay1.com/ 1
https://pay3.com/ 3
https://pay8.com/ 8

Based on the ID returned, i need to pass to another query:

select *
FROM transaction
WHERE id = '${id_1}'

If i try like: ${id_1} or ${id_3} is working fine.

But, how can i pass dynamically to the next query, without hard coding the index?

Body:
ForEach Controller has pre-defined variable exposing the current iteration, as per documentation:

JMeter will expose the looping index as a variable named __jm__<Name of your element>__idx. So for example, if your Loop Controller is named FEC, then you can access the looping index through ${__jm__FEC__idx}. Index starts at 0

So

given your ForEach Controller name is ForEach Controller you can access its current loop as ${__jm__ForEach Controller__idx}

given indices are zero-based and your variables are 1-based you need to add 1 to the current index which can be done using __intSum() function

and finally you will need to use __V() function in order to evaluate the resulting expression using your id_ prefix

Putting everything together, the code you're looking for would be something like:

${__V(id_${__intSum(${__jm__ForEach Controller__idx},1,)},)}

Demo:

More information: Here’s What to Do to Combine Multiple JMeter Variables


问:
Redirect with PHP and skip specific parameter
Since I've started using friendly URLS in my website, I'm redirecting every page to the new version, only if the registered user has a "username" in his profile.

So, I'm redirecting from:

https://tribbr.me/post.php?id=850

with:

header("Location:/".$if_username."/post/".$post_id."?".$_SERVER['QUERY_STRING']); exit();

To keep all GET parameters.... but the problem is that this header request, obviously with $_SERVER['QUERY_STRING'] is adding the post id too to the URL, and when redirected, this is the final URL:

https://tribbr.me/TribeMasters/post/850?id=850

Is it possible to just skip the id=850 parameter to the URL redirection? Since it is a duplicated parameter: post/850 and id=850 are the same.

Thanks for helping me :)

答:
David Walsh did a good article on this

https://davidwalsh.name/php-remove-variable

```<code>function remove_querystring_var($url, $key) {
    $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
    $url = substr($url, 0, -1);
    return $url;
}
</code>```

Body:
David Walsh did a good article on this

https://davidwalsh.name/php-remove-variable

function remove_querystring_var($url, $key) {
    $url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
    $url = substr($url, 0, -1);
    return $url;
}


问:
Using R to remove all columns that sum to 0
I have a very large CSV file containing counts of unique DNA sequences, and there is a column for each unique sequence. I started with hundreds of samples and cut it down to only 15 that I care about but now I have THOUSANDS of columns that contain nothing but Zeroes and it is messing up my data processing. How do I go about completely removing any column that sums to zero? I’ve seen some similar questions on here but none of those suggestions have worked for me.

I have 6653 columns and 16 rows in my data frame.

If it matters my columns all have super crazy names, some several hundred characters long ( AATCGGCTAA..., etc) and the row names are the sample IDs which are also not entirely numeric. Any tips greatly appreciated. I am still new to R so please let me know where I will need to change things in code examples if you can! Thanks!

答:
welcome to SO here is a tidyverse approach</p>

```<code>library(tidyverse)

mtcars %>%
  select_if(is.numeric) %>%
  select_if(~ sum(.x) > 0)
</code>```

Body:
welcome to SO here is a tidyverse approach

library(tidyverse)

mtcars %>%
  select_if(is.numeric) %>%
  select_if(~ sum(.x) > 0)


问:
My If statement is not working in Middleware
I am trying to make a middleware which can filter my http request by checking if the "$created_by" that I am passing through the request alreday exists in my "users" table

If it does I want to proceed with my "$next($request)"

And if it doesn't I wanna redirect it.

When the situation is this:-

```<code>if ($ip->uuid == $request->created_by)
</code>```

It redirects to $next($request); which is correct

But when the "$request->created_by" is not present in DB it which makes $ip null

And it shows this error "Trying to get property 'uuid' of non-object"

Here's my Middleware:-

```<code><?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Posts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)

     {
      $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
        // dd($ip);
       if ($ip->uuid == $request->created_by) {
        if ($ip == null) {
             return redirect('https://www.google.com');
        }

       }

        return $next($request);

        }
    }
</code>```

答:
You have to make sure that $ip is not null before trying to access property uuid.</p>

```<code>public function handle($request, Closure $next) {
    $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
    if(is_null($ip) || $ip->uuid !== $request->created_by) {
        return redirect('https://www.google.com');
    }

    return $next($request);
}
</code>```

Body:
I am trying to make a middleware which can filter my http request by checking if the "$created_by" that I am passing through the request alreday exists in my "users" table

If it does I want to proceed with my "$next($request)"

And if it doesn't I wanna redirect it.

When the situation is this:-

if ($ip->uuid == $request->created_by)

It redirects to $next($request); which is correct

But when the "$request->created_by" is not present in DB it which makes $ip null

And it shows this error "Trying to get property 'uuid' of non-object"

Here's my Middleware:-

<?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Posts
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)

     {
      $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
        // dd($ip);
       if ($ip->uuid == $request->created_by) {
        if ($ip == null) {
             return redirect('https://www.google.com');
        }

       }

        return $next($request);

        }
    }

Body:
You have to make sure that $ip is not null before trying to access property uuid.

public function handle($request, Closure $next) {
    $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
    if(is_null($ip) || $ip->uuid !== $request->created_by) {
        return redirect('https://www.google.com');
    }

    return $next($request);
}


问:
Send custom events to browser
I dont know what i am asking is do-able or not. But, still whenever I start a ajax request I want to send processing event to the browser, so that it shows the spinning circle in the tab and brings up a progress bar, until the request completes.

Is this possible? If yes, can you point me to correct resource.

答:
There is no way to make the spinner animate programmatically, but you can simulate the behavior using a hidden iframe. As long as the iframe is loading, the browser will animate the spinner. </p>

```<code>var doneLoading = false;

var simulateLoad = function () {
    var ifrm = document.createElement('IFRAME');
    //make dummy.html a sufficiently large file
    ifrm.setAttribute('src', 'dummy.html?' + Math.floor(Math.random()*100));
    ifrm.style.display = 'none';
    ifrm.onload = function () {
        if(!doneLoading) {
            document.body.removeChild(ifrm);
            simulateLoad();
        }
    }
    document.body.appendChild(ifrm);
}

var startLoad = function () {
    doneLoading = false;
    simulateLoad();
}

var endLoad = function () {
    doneLoading = true;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Send custom events to browser

Body:
There is no way to make the spinner animate programmatically, but you can simulate the behavior using a hidden iframe. As long as the iframe is loading, the browser will animate the spinner.

var doneLoading = false;

var simulateLoad = function () {
    var ifrm = document.createElement('IFRAME');
    //make dummy.html a sufficiently large file
    ifrm.setAttribute('src', 'dummy.html?' + Math.floor(Math.random()*100));
    ifrm.style.display = 'none';
    ifrm.onload = function () {
        if(!doneLoading) {
            document.body.removeChild(ifrm);
            simulateLoad();
        }
    }
    document.body.appendChild(ifrm);
}

var startLoad = function () {
    doneLoading = false;
    simulateLoad();
}

var endLoad = function () {
    doneLoading = true;
}


问:
Why does the following snippet of multi-processing code output differently when running multiple times?
Intuitively, the output should always be 15. But sometimes, it generate 11 or 12 or something else. I tried add some delay, but didn't solve the problem.</p>

```<code>from multiprocessing import Pool, Manager
import time

def func(dic, c):
    dic['count'] += c
    # time.sleep(0.1)

if __name__=="__main__":
    d = Manager().dict()    # a manager to enable data sharing b
    d['count'] = 0
    args = [(d,1), (d,2), (d,3), (d,4), (d,5)]
    pool = Pool(5)
    pool.starmap(func, args)
    pool.close()
    pool.join()
    print(f'dic={d}')
</code>```

答:
Your problem is this statement:

```<code>dic['count'] += c
</code>```

It reads your dictionary, then increments by c and stores the value but this is not an atomic operation. Another process may have changed the dictionary between read and write operations and then your write will "overwrite" the change that happened between the operations.

You can solve this by passing a lock and using it:

```<code>def func(dic, lock, c):
    with lock:
        dic['count'] += c
    # time.sleep(0.1)

if __name__=="__main__":

    d = Manager().dict()    # a manager to enable data sharing b
    l = Manager().Lock()
    d['count'] = 0
    args = [(d, l,1), (d,l,2), (d,l,3), (d,l,4), (d,l,5)]
    pool = Pool(5)
    pool.starmap(func, args)
    pool.close()
    pool.join()
    print(f'dic={d}')
</code>```

This ensures the whole dictionary operation stays atomic.

Body:
Intuitively, the output should always be 15. But sometimes, it generate 11 or 12 or something else. I tried add some delay, but didn't solve the problem.

from multiprocessing import Pool, Manager
import time

def func(dic, c):
    dic['count'] += c
    # time.sleep(0.1)

if __name__=="__main__":
    d = Manager().dict()    # a manager to enable data sharing b
    d['count'] = 0
    args = [(d,1), (d,2), (d,3), (d,4), (d,5)]
    pool = Pool(5)
    pool.starmap(func, args)
    pool.close()
    pool.join()
    print(f'dic={d}')

Body:
Your problem is this statement:

dic['count'] += c

It reads your dictionary, then increments by c and stores the value but this is not an atomic operation. Another process may have changed the dictionary between read and write operations and then your write will "overwrite" the change that happened between the operations.

You can solve this by passing a lock and using it:

def func(dic, lock, c):
    with lock:
        dic['count'] += c
    # time.sleep(0.1)

if __name__=="__main__":

    d = Manager().dict()    # a manager to enable data sharing b
    l = Manager().Lock()
    d['count'] = 0
    args = [(d, l,1), (d,l,2), (d,l,3), (d,l,4), (d,l,5)]
    pool = Pool(5)
    pool.starmap(func, args)
    pool.close()
    pool.join()
    print(f'dic={d}')

This ensures the whole dictionary operation stays atomic.


答:
you can use optional to prevent error if you object is null.</p>

```<code>public function handle($request, Closure $next) {
    $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
    if(optional($ip)->uuid == $request->created_by) {
        return $next($request);
    }

    return redirect('https://www.google.com');

}

</code>```

Title: My If statement is not working in Middleware

Body:
you can use optional to prevent error if you object is null.

public function handle($request, Closure $next) {
    $ip = DB::table('users')->where('uuid', '=', $request->created_by)->first();
    if(optional($ip)->uuid == $request->created_by) {
        return $next($request);
    }

    return redirect('https://www.google.com');

}


问:
Install Font Awesome 5 with NPM
I am working with Angular(6) application, and I am trying to use FA icons, and drop-down with no luck. I am successfully using FA(4) icons, like:

```<code><i class="fa fa-align-justify"></i>
</code>```

But  is not working. I am using following command to install FA:

```<code>npm install font-awesome --save
</code>```

This is from package.json in node_modules folder:

I can see font-awesome.css, but it says Font Awesome 4.7.0 as shown below:

In angular.json file, I referenced FA:
"node_modules/font-awesome/css/font-awesome.min.css",

I read a lot of posts like How to use font Awesome 5 installed via NPM

What do I need to do else?

答:
Alternatively, you can install fontawesome as a module in your js code.

Steps:

npm install @fortawesome/fontawesome-free --save

in your javascript code import the all.js file as instructed at the very bottom of the instructions here.

```<code>import '@fortawesome/fontawesome-free/js/all.js';
</code>```

- or -

```<code>require('@fortawesome/fontawesome-free/js/all.js');
</code>```

Title: Install Font Awesome 5 with NPM

Body:
I am working with Angular(6) application, and I am trying to use FA icons, and drop-down with no luck. I am successfully using FA(4) icons, like:

But  is not working. I am using following command to install FA:

npm install font-awesome --save

This is from package.json in node_modules folder:

I can see font-awesome.css, but it says Font Awesome 4.7.0 as shown below:

In angular.json file, I referenced FA:
"node_modules/font-awesome/css/font-awesome.min.css",

I read a lot of posts like How to use font Awesome 5 installed via NPM

What do I need to do else?

Body:
Alternatively, you can install fontawesome as a module in your js code.

Steps:

npm install @fortawesome/fontawesome-free --save

in your javascript code import the all.js file as instructed at the very bottom of the instructions here.

import '@fortawesome/fontawesome-free/js/all.js';

- or -

require('@fortawesome/fontawesome-free/js/all.js');


问:
How do I find element in object typescript code
So, am trying to assign colours to my icons dynamically ... but this line of code keeps complaining,

```<code>let icon = iconsList[name];
</code>```

When I hover of it .. This is the explanation "

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.
    No index signature with a parameter of type 'string' was found on type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.ts(7053)

interface Props{
    name:string,
}

const Icon = ({ name }:Props) => {
    const iconsList = {
      heart: '',
      star: '',
      like: '',
      dislike: '',
      flash: '',
      marker: '',
      filter: '',
      user: '',
      circle: '',
      hashtag: '',
      calendar: '',
      chevronLeft: '',
      optionsV: '',
      optionsH: '',
      chat: '',
      explore: ''
    };

    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
  };

  export default Icon;
  ```

ScreenShot of the code in Vscode On line 25, am trying to pick the specific icon color but it complains

答:
It's worth breaking this down a little bit because it's quite educational. Getting a property string from an object is something of a partial function; some combinations of properties and objects can return values, but not all.

In your example, getting a property which has type string (name) from the type of iconsList is not guaranteed to give a value; what if the string is "xyz"? What ought the value be in that case? It's hard to give a really concrete answer to that.

If we look at a condensed example, we see the same error:

const getIcon = (iconName: string) => {
  const iconsList = {
      heart: '',
      star: '',
  };

  return iconsList[iconName];
};
```

<p>Gives us the same error on the line <code>return iconsList[iconName];</code></p>

<p>We can do better though, in order to make this work. If what we want to say is that the <code>iconName</code> we pass in will always be a property of the <code>iconsList</code> object, we can do that via. a type:</p>

<pre class="lang-js prettyprint-override"><code>const iconsList = {
    heart: '',
    star: '',
};

const getIcon = (iconName: keyof typeof iconsList) => {
  return iconsList[iconName];
}

const x = getIcon('heart'); // works
const y = getIcon('xyz');   // type error
</code>```

...and we can get more generic with this:

const path = <T>(o: T) => (k: keyof T) => o[k];

const iconsList = {
    heart: '',
    star: '',
};

const getIcon = path(iconsList);

const x = getIcon('heart'); // works
const y = getIcon('xyz');   // type error
```

<p>If you'd like to always return a usable value no matter what the input, consider looking into a <code>Maybe</code> return type; that way, you can always return a <code>Maybe</code>, which will be a <code>Nothing</code> if you can't get the key on the object.</p>

<p>Hopefully that gives an insight into why you're getting the error and how you can fix it. If you have any questions, please ask away.</p>

<hr>

<p>Update as per comment:</p>

<p>You'd want to make sure that you're also setting the type in <code>Props</code> in order that we can use it to access <code>iconTypes</code>:</p>

<pre class="lang-js prettyprint-override"><code>const iconsList = {
    heart: '',
    star: '',
    like: '',
    dislike: '',
    flash: '',
    marker: '',
    filter: '',
    user: '',
    circle: '',
    hashtag: '',
    calendar: '',
    chevronLeft: '',
    optionsV: '',
    optionsH: '',
    chat: '',
    explore: ''
};

interface Props{
    name: keyof typeof iconsList;
}

etc.

</code>```

Body:
So, am trying to assign colours to my icons dynamically ... but this line of code keeps complaining,

let icon = iconsList[name];

When I hover of it .. This is the explanation "

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.
    No index signature with a parameter of type 'string' was found on type '{ heart: string; star: string; like: string; dislike: string; flash: string; marker: string; filter: string; user: string; circle: string; hashtag: string; calendar: string; chevronLeft: string; optionsV: string; optionsH: string; chat: string; explore: string; }'.ts(7053)

interface Props{
    name:string,
}

const Icon = ({ name }:Props) => {
    const iconsList = {
      heart: '',
      star: '',
      like: '',
      dislike: '',
      flash: '',
      marker: '',
      filter: '',
      user: '',
      circle: '',
      hashtag: '',
      calendar: '',
      chevronLeft: '',
      optionsV: '',
      optionsH: '',
      chat: '',
      explore: ''
    };

    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
  };

  export default Icon;

ScreenShot of the code in Vscode On line 25, am trying to pick the specific icon color but it complains

Body:
It's worth breaking this down a little bit because it's quite educational. Getting a property string from an object is something of a partial function; some combinations of properties and objects can return values, but not all.

In your example, getting a property which has type string (name) from the type of iconsList is not guaranteed to give a value; what if the string is "xyz"? What ought the value be in that case? It's hard to give a really concrete answer to that.

If we look at a condensed example, we see the same error:

const getIcon = (iconName: string) => {
  const iconsList = {
      heart: '&#xe800;',
      star: '&#xe801;',
  };

  return iconsList[iconName];
};

Gives us the same error on the line return iconsList[iconName];

We can do better though, in order to make this work. If what we want to say is that the iconName we pass in will always be a property of the iconsList object, we can do that via. a type:

const iconsList = {
    heart: '&#xe800;',
    star: '&#xe801;',
};

const getIcon = (iconName: keyof typeof iconsList) => {
  return iconsList[iconName];
}

const x = getIcon('heart'); // works
const y = getIcon('xyz');   // type error

...and we can get more generic with this:

const path = <T>(o: T) => (k: keyof T) => o[k];

const iconsList = {
    heart: '&#xe800;',
    star: '&#xe801;',
};

const getIcon = path(iconsList);

const x = getIcon('heart'); // works
const y = getIcon('xyz');   // type error

If you'd like to always return a usable value no matter what the input, consider looking into a Maybe return type; that way, you can always return a Maybe, which will be a Nothing if you can't get the key on the object.

Hopefully that gives an insight into why you're getting the error and how you can fix it. If you have any questions, please ask away.

Update as per comment:

You'd want to make sure that you're also setting the type in Props in order that we can use it to access iconTypes:

const iconsList = {
    heart: '&#xe800;',
    star: '&#xe801;',
    like: '&#xe800;',
    dislike: '&#xe802;',
    flash: '&#xe803;',
    marker: '&#xf031;',
    filter: '&#xf0b0;',
    user: '&#xf061;',
    circle: '&#xf039;',
    hashtag: '&#xf029;',
    calendar: '&#xf4c5;',
    chevronLeft: '&#xf004;',
    optionsV: '&#xf142;',
    optionsH: '&#xf141;',
    chat: '&#xf4ac;',
    explore: '&#xf50d;'
};

interface Props{
    name: keyof typeof iconsList;
}

etc.


问:
How to use a variable inside a carbon datetime?
Good morning guys, i need to have a custom date that always has the current date but a certain time to be able to compare two dates and get the remaining time. At the moment something like this occurred to me:

```<code> $day=date("d");
            $dayy= now();
            $datelim= Carbon::createFromFormat('Y-m-d H:i:s', '2020-05-',$day, '22:00:02');
return view('fen.index', [

        'works' => Period::select('paperiod.descriptionp','pamatrixinfoperio.description', 'pamatrixinfoperio.codpar')
                ->join('pamatrixinfoperio', 'pamatrixinfoperio.cod_paperiod', '=', 'paperiod.cod')
                ->where('pamatrixinfoperio.read_at', '=', 0, 'AND')
                ->where('pamatrixinfoperio.cod_paperiod', '=', 1)
                ->get(),
        'Periodres' => $fechalim

        ]);
</code>```

but I don't know how to concatenate that variable day in the carbon '2020-05-',$day, '22:00:02' , How could I use it because my objective is that the variable always has the current day, Monday, Tuesday, Wednesday, but that the time is always the same.

On the other hand, I don't know if they could help me. How can I compare dayy and datelim? So in the view I can have for example: "The work is about to end in 3 days, 3 hours and 20 seconds" I hope you can help me, because I find more complex examples in carbon but not basic and I don't know how to do this :(

my view is this:

```<code> @extends('layouts.app')

    @section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">WorksF</div>

                    <div class="card-body">
                        @if (session('status'))
                            <div class="alert alert-success" role="alert">
                                {{ session('status') }}
                            </div>
                        @endif

                        Welcome {{Auth::user()->name}}, Lasis informs you that the following files are about to end in:
@foreach($works as $work)
            <li class="list-group-item">
            {{$work->description}}
            you have the next time to deliver the report:
            <b>{{$Periodres}}</b>
   </li>
@endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endsection
</code>```

As you can see the view is not finished but I am looking for something similar, Thanks in advance for the help.

答:
I think in your case you can use:
Carbon::create($year, $month, $day, $hour, $minute, $second)</p>

Body:
Good morning guys, i need to have a custom date that always has the current date but a certain time to be able to compare two dates and get the remaining time. At the moment something like this occurred to me:

 $day=date("d");
            $dayy= now();
            $datelim= Carbon::createFromFormat('Y-m-d H:i:s', '2020-05-',$day, '22:00:02');
return view('fen.index', [

        'works' => Period::select('paperiod.descriptionp','pamatrixinfoperio.description', 'pamatrixinfoperio.codpar')
                ->join('pamatrixinfoperio', 'pamatrixinfoperio.cod_paperiod', '=', 'paperiod.cod')
                ->where('pamatrixinfoperio.read_at', '=', 0, 'AND')
                ->where('pamatrixinfoperio.cod_paperiod', '=', 1)
                ->get(),
        'Periodres' => $fechalim

        ]);

but I don't know how to concatenate that variable day in the carbon '2020-05-',$day, '22:00:02' , How could I use it because my objective is that the variable always has the current day, Monday, Tuesday, Wednesday, but that the time is always the same.

On the other hand, I don't know if they could help me. How can I compare dayy and datelim? So in the view I can have for example: "The work is about to end in 3 days, 3 hours and 20 seconds" I hope you can help me, because I find more complex examples in carbon but not basic and I don't know how to do this :(

my view is this:

 @extends('layouts.app')

    @section('content')

WorksF

                        @if (session('status'))

                                {{ session('status') }}

                        @endif

                        Welcome {{Auth::user()->name}}, Lasis informs you that the following files are about to end in:
@foreach($works as $work)

            {{$work->description}}
            you have the next time to deliver the report:
            {{$Periodres}}

@endforeach

    @endsection

As you can see the view is not finished but I am looking for something similar, Thanks in advance for the help.