问:
Unexpected behaviour of function used in conjunction with lapply/sapply?
This

```<code>mult_six <- function(x) {
  y <- x * 6
}

mult_six(7)
</code>```

returns nothing (as expected), and y is not globally assigned (also as exptected, since assignment takes place in the scope of the function, not in the parent environment - so y returns Error: object 'y' not found - completely normal)

But

```<code>sapply(c(1,2,3), mult_six)
</code>```

returns

```<code>[1]  6 12 18
</code>```

(and lapply() returns the list equivalent).

I do not understand why lapply/sapply would behave any differently to calling the function on each element separately?

答:
As we know functions by default return the last line in the function, however, since a value is assigned in this function it doesn't explicitly display the result but if you use print you can see it.

```<code>print(mult_six(7))
#[1] 42
</code>```

Body:
This

mult_six <- function(x) {
  y <- x * 6
}

mult_six(7)

returns nothing (as expected), and y is not globally assigned (also as exptected, since assignment takes place in the scope of the function, not in the parent environment - so y returns Error: object 'y' not found - completely normal)

But

sapply(c(1,2,3), mult_six)

returns

[1]  6 12 18

(and lapply() returns the list equivalent).

I do not understand why lapply/sapply would behave any differently to calling the function on each element separately?

Body:
As we know functions by default return the last line in the function, however, since a value is assigned in this function it doesn't explicitly display the result but if you use print you can see it.

print(mult_six(7))
#[1] 42


来源: stackexchange

问:
How to save the information on a Page when traveling from one detail page to another
I am working with Xamarin.Forms and I am trying to implement my multipage form in a Master-Detail format. When I click on another page from the Master page menu, I want to make sure that the information on the current detail page gets saved to its respective database table on the mobile device before I travel to the next detail page. Any idea on how to achieve that?</p>

答:
Have you looked at the OnDisappearing() method?</p>

```<code>protected override void OnDisappearing()
{
    //Your code before you switch to another page
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Have you looked at the OnDisappearing() method?

protected override void OnDisappearing()
{
    //Your code before you switch to another page
}


问:
Can't seem to input any integer values when running the app? It just shows result "grade c"
The salary scheme for a company is given as follows:

Salary range for grade A: $700 - $899

Salary range for grade B: $600 - $799

Salary range for grade C: $500 - $649

A person whose salary is between $600 and $649 is in grade C if his merit points are below 10, otherwise he is in grade B. A person whose salary is between $700 and $799 is in grade B if his merit points are below 20, otherwise, he is in grade A. Write a program to read in a person’s salary and his merit points, and displays his grade.

```<code>package trydontquit1;
import java.util.*;

public class tryagain {
    public int salary;
    public int merits;

    public class employee {
        employee (int inputsalary, int inputmerits){
            salary = inputsalary;
            merits = inputmerits;
        }

        //grade the input in regard to salary and merits point
        void grade() {
            int c = 0, b = 0, a = 0;
            c = salary - 600;
            b = salary - 700;
            a = salary - 800;
            if (c <= 49 && merits < 10)
                System.out.println("Grade = C");
            else if (b <= 99 && merits < 20)
                System.out.println("Grade = B");
            else if (b > 99)
                System.out.println("Grade = A");
        }
    }
    //to instantiate an object and to grade employee
    public static void main(String[] args) {
        int x=0, y=0;
        System.out.println("Grading of employee");
        tryagain tryagain = new tryagain();
        employee sc = tryagain.new employee(x,y);
        System.out.println("Please enter salary\n");
        Scanner i = new Scanner(System.in);
        System.out.println("Please enter merits\n");
        Scanner j = new Scanner(System.in);
        sc.grade();
    }
}
</code>```

答:
See the flow

```<code>int x=0, y=0;

new employee(x,y);

employee (int inputsalary, int inputmerits){
        salary = inputsalary;
        merits = inputmerits;
 }

c = salary - 600;
</code>```

salary is always 0

Body:
The salary scheme for a company is given as follows:

Salary range for grade A: $700 - $899

Salary range for grade B: $600 - $799

Salary range for grade C: $500 - $649

A person whose salary is between $600 and $649 is in grade C if his merit points are below 10, otherwise he is in grade B. A person whose salary is between $700 and $799 is in grade B if his merit points are below 20, otherwise, he is in grade A. Write a program to read in a person’s salary and his merit points, and displays his grade.

package trydontquit1;
import java.util.*;

public class tryagain {
    public int salary;
    public int merits;

    public class employee {
        employee (int inputsalary, int inputmerits){
            salary = inputsalary;
            merits = inputmerits;
        }

        //grade the input in regard to salary and merits point
        void grade() {
            int c = 0, b = 0, a = 0;
            c = salary - 600;
            b = salary - 700;
            a = salary - 800;
            if (c <= 49 && merits < 10)
                System.out.println("Grade = C");
            else if (b <= 99 && merits < 20)
                System.out.println("Grade = B");
            else if (b > 99)
                System.out.println("Grade = A");
        }
    }
    //to instantiate an object and to grade employee
    public static void main(String[] args) {
        int x=0, y=0;
        System.out.println("Grading of employee");
        tryagain tryagain = new tryagain();
        employee sc = tryagain.new employee(x,y);
        System.out.println("Please enter salary\n");
        Scanner i = new Scanner(System.in);
        System.out.println("Please enter merits\n");
        Scanner j = new Scanner(System.in);
        sc.grade();
    }
}

Body:
See the flow

int x=0, y=0;

new employee(x,y);

employee (int inputsalary, int inputmerits){
        salary = inputsalary;
        merits = inputmerits;
 }

c = salary - 600;

salary is always 0


问:
How can I make two() to ignore the same cases as one()?
How can I make the program to skip those results where 'it does not pass'. one() ignores some cases.  two() forgets to ignore them. It should not iterate over "NO PASS" cases.

```<code>import random
def percentage(a, b):
    return 100 * (float(a) / float(b))
def one(a, b, c):
    if percentage(a, b) <= 40:
        print("%d PASS" % c)
    elif 40 < percentage(a, b) <= 80:
        print("%d PASS" % c)
    else: # ONE() IGNORES THESE CASES.
        pass
def two(a, c): # HOW CAN I MAKE THIS FUNCTION TO IGNORE THE SAME CASES AS ONE()
    if a%2 == 0:
        print("%d EVEN" % c)
    elif a%2 != 0:
        print("%d ODD" % c)

randomlist = []
for i in range(0,5):
    n = random.randint(1,500)
    randomlist.append(n)

test1 = random.randrange(1, 500)
test2 = random.randrange(1, 500)

for c, a in enumerate(randomlist):
    one(test1, test2, c+1)
for c, a in enumerate(randomlist):
    two(a, c+1)
</code>```

答:
It looks like you want to use the first function as a filter and only pass list values to the second function if they pass the filter. For this you need to return something from the first function. Here is one way to do that:

```<code>import random
def percentage(a, b):
    return 100 * (float(a) / float(b))

def one(a, b, c):
    if percentage(a, b) <= 40:
        print("%d PASS" % c)
        return True
    elif 40 < percentage(a, b) <= 80:
        print("%d PASS" % c)
        return True
    else:
        return False

def two(a, c):
    if a%2 == 0:
        print("%d EVEN" % c)
    elif a%2 != 0:
        print("%d ODD" % c)

randomlist = []
for i in range(0,5):
    n = random.randint(1,500)
    randomlist.append(n)

test1 = random.randrange(1, 500)
test2 = random.randrange(1, 500)

randomlist_filtered = []
for c, a in enumerate(randomlist):
    passed = one(test1, test2, c+1)
    if passed:
        randomlist_filtered.append(a)
for c, a in enumerate(randomlist_filtered):
    two(a, c+1)
</code>```

Output of a random run:

```<code>1 PASS
2 PASS
3 PASS
4 PASS
5 PASS
1 ODD
2 ODD
3 EVEN
4 ODD
5 EVEN
</code>```

Note that the indices of the items are different in the second loop. If you want to keep the indices, you could run both functions within the same loop or preserve the entries together with their respective indices in the filtered list. I didn't fix it because to be honest, I do not know why you even want the indices (which are generated by enumerate)

Body:
How can I make the program to skip those results where 'it does not pass'. one() ignores some cases.  two() forgets to ignore them. It should not iterate over "NO PASS" cases.

import random
def percentage(a, b):
    return 100 * (float(a) / float(b))
def one(a, b, c):
    if percentage(a, b) <= 40:
        print("%d PASS" % c)
    elif 40 < percentage(a, b) <= 80:
        print("%d PASS" % c)
    else: # ONE() IGNORES THESE CASES.
        pass
def two(a, c): # HOW CAN I MAKE THIS FUNCTION TO IGNORE THE SAME CASES AS ONE()
    if a%2 == 0:
        print("%d EVEN" % c)
    elif a%2 != 0:
        print("%d ODD" % c)

randomlist = []
for i in range(0,5):
    n = random.randint(1,500)
    randomlist.append(n)

test1 = random.randrange(1, 500)
test2 = random.randrange(1, 500)

for c, a in enumerate(randomlist):
    one(test1, test2, c+1)
for c, a in enumerate(randomlist):
    two(a, c+1)

Body:
It looks like you want to use the first function as a filter and only pass list values to the second function if they pass the filter. For this you need to return something from the first function. Here is one way to do that:

import random
def percentage(a, b):
    return 100 * (float(a) / float(b))

def one(a, b, c):
    if percentage(a, b) <= 40:
        print("%d PASS" % c)
        return True
    elif 40 < percentage(a, b) <= 80:
        print("%d PASS" % c)
        return True
    else:
        return False

def two(a, c):
    if a%2 == 0:
        print("%d EVEN" % c)
    elif a%2 != 0:
        print("%d ODD" % c)

randomlist = []
for i in range(0,5):
    n = random.randint(1,500)
    randomlist.append(n)

test1 = random.randrange(1, 500)
test2 = random.randrange(1, 500)

randomlist_filtered = []
for c, a in enumerate(randomlist):
    passed = one(test1, test2, c+1)
    if passed:
        randomlist_filtered.append(a)
for c, a in enumerate(randomlist_filtered):
    two(a, c+1)

Output of a random run:

1 PASS
2 PASS
3 PASS
4 PASS
5 PASS
1 ODD
2 ODD
3 EVEN
4 ODD
5 EVEN

Note that the indices of the items are different in the second loop. If you want to keep the indices, you could run both functions within the same loop or preserve the entries together with their respective indices in the filtered list. I didn't fix it because to be honest, I do not know why you even want the indices (which are generated by enumerate)


问:
Unable to connect to External PostgreSql Database from a web Docker Container
I have installed PostgreSql on my machine which I want to use as external DB for the Dockerized Laravel Web app.
I do not want to use the postgre image, but the local DB. It can be mysql as well.

docker-compose.yml

```<code>     `version: ‘3’
        services:
        app:
        build:
        context: .
        dockerfile: .docker/Dockerfile
        image: docker-app
        ports:
        - 8004:80`

    .env

 `DB_CONNECTION=pgsql
    DB_HOST= 127.0.0.1 or localhost
    DB_PORT=5432
    DB_DATABASE=testdb
    DB_USERNAME=postgres
    DB_PASSWORD=password`
</code>```

Error is given below:

SQLSTATE[08006] [7] could not connect to server: Connection refused

Is the server running on host “127.0.0.1” and accepting TCP/IP connections on port 5432?`

The reason of the issue I know the application container is not connecting to the external DB as it is outside of its filesystem.

If I change the DB_HOST to the local IP Address, there comes up this

error:SQLSTATE[08006] [7] FATAL: no pg_hba.conf entry for host
  10.0.9.57`

答: If you get message "no pg_hba.conf entry for host 10.0.9.57" you need to change the configuration of your postgresql to all remote connections from the docker image (10.0.9.57), see this answer</p>

Body:
I have installed PostgreSql on my machine which I want to use as external DB for the Dockerized Laravel Web app.
I do not want to use the postgre image, but the local DB. It can be mysql as well.

docker-compose.yml

     `version: ‘3’
        services:
        app:
        build:
        context: .
        dockerfile: .docker/Dockerfile
        image: docker-app
        ports:
        - 8004:80`

    .env

 `DB_CONNECTION=pgsql
    DB_HOST= 127.0.0.1 or localhost
    DB_PORT=5432
    DB_DATABASE=testdb
    DB_USERNAME=postgres
    DB_PASSWORD=password`

Error is given below:

SQLSTATE[08006] [7] could not connect to server: Connection refused

Is the server running on host “127.0.0.1” and accepting TCP/IP connections on port 5432?`

The reason of the issue I know the application container is not connecting to the external DB as it is outside of its filesystem.

If I change the DB_HOST to the local IP Address, there comes up this

error:SQLSTATE[08006] [7] FATAL: no pg_hba.conf entry for host
  10.0.9.57`


问:
Concatenating columns not returning full results
I have a table that I want to concatenate 4 columns together; 2 of them are integers, 1 text & 1 date.

I have joined them together by casting the integers to varchar & formatting the date. But I have an example where the last item is not being shown

```<code>SELECT
    CAST(CONTRACT_ID VARCHAR(15)) + '-' +
    CAST(CONTRACT_TYPE AS VARCHAR(15))  + '-' +
    GENDER + '-' + FORMAT(DOB, 'yyyy') AS UNIQUE_ID
</code>```

There are 4 rows which should have the same output, then they differ.

```<code>- 12345678-70-M -1948
- 12345678-70-M
- 12345678-70-M
- 12345678-70-M
</code>```

But when run as results to text, the correct results return

```<code>- 12345678-70-M -1948
- 12345678-70-M -1948
- 12345678-70-M -1948
- 12345678-70-M -1948
</code>```

This isn't a visual error within the grid, because if I do a filter on it it will only return the 1 row.

I did notice though, if I cast the gender to varchar(1), the results do work.
Could there be a hidden character at the end of the gender field that is causing the issue.

It seems to be working fine 99% of the time.

答:
This suggests that there are spaces in GENDER -- or some other character.  Try this:

```<code>SELECT CONCAT(CONTRACT_ID, '-', CONTRACT_TYPE, '-',
              LTRIM(RTRIM(GENDER)), '-', YEAR(DOB)
             ) AS UNIQUE_ID
</code>```

Another possibility is that GENDER has some character such as a newline at the end.  It looks like the first character is correct, so:

```<code>SELECT CONCAT(CONTRACT_ID, '-', CONTRACT_TYPE, '-',
              LEFT(GENDER, 1), '-', YEAR(DOB)
             ) AS UNIQUE_ID
</code>```

Body:
I have a table that I want to concatenate 4 columns together; 2 of them are integers, 1 text & 1 date.

I have joined them together by casting the integers to varchar & formatting the date. But I have an example where the last item is not being shown

SELECT
    CAST(CONTRACT_ID VARCHAR(15)) + '-' +
    CAST(CONTRACT_TYPE AS VARCHAR(15))  + '-' +
    GENDER + '-' + FORMAT(DOB, 'yyyy') AS UNIQUE_ID

There are 4 rows which should have the same output, then they differ.

- 12345678-70-M -1948
- 12345678-70-M
- 12345678-70-M
- 12345678-70-M

But when run as results to text, the correct results return

- 12345678-70-M -1948
- 12345678-70-M -1948
- 12345678-70-M -1948
- 12345678-70-M -1948

This isn't a visual error within the grid, because if I do a filter on it it will only return the 1 row.

I did notice though, if I cast the gender to varchar(1), the results do work.
Could there be a hidden character at the end of the gender field that is causing the issue.

It seems to be working fine 99% of the time.

Body:
This suggests that there are spaces in GENDER -- or some other character.  Try this:

SELECT CONCAT(CONTRACT_ID, '-', CONTRACT_TYPE, '-',
              LTRIM(RTRIM(GENDER)), '-', YEAR(DOB)
             ) AS UNIQUE_ID

Another possibility is that GENDER has some character such as a newline at the end.  It looks like the first character is correct, so:

SELECT CONCAT(CONTRACT_ID, '-', CONTRACT_TYPE, '-',
              LEFT(GENDER, 1), '-', YEAR(DOB)
             ) AS UNIQUE_ID


问:
Irony Parsing a list delimited with white space
I am trying to write a parser for Allen Bradly SLC Language/File format. I have successfully got it to parse a register reference. I.E. N5:4/3. However, when I try to move to to the next level, having it parse a list of register references separated by whitespace, it throws the following error

Input:

N30:3/8 B20:3/3

Error:

(L1, C9) Syntax error, expected: :

Here is my code, this can be built and the dll loaded into the Irony Grammar Explorer

```<code>using System;
using Irony.Parsing;

namespace Irony.Samples.SLC
{
    [Language("SLC", "1.0", "RS Logix 500 SLC")]
    public class SLCGrammar : Grammar
    {
        public SLCGrammar()
        {
            //Terminals
            var SLCFilePrefix = new FixedLengthLiteral("Type", 1, TypeCode.String);
            var SLCRegisterWord = new NumberLiteral("Word");
            var SLCRegisterBit = new NumberLiteral("Bit");
            var SLCRegisterFileNumber = new NumberLiteral("FileNumber");

            //Nonterminals
            var SLCInstructionRegisterList = new NonTerminal("InstructionRegisterList");
            var SLCRegisterReference = new NonTerminal("RegisterReference");
            var SLCRegisterReferenceWordOrBit = new NonTerminal("RegisterReferenceWordOrBit");
            var SLCRegisterReferenceWordWithBit = new NonTerminal("RegisterReferenceWordWithBit");

            //Rules
            SLCRegisterReferenceWordWithBit.Rule = SLCRegisterWord + "/" + SLCRegisterBit;
            SLCRegisterReferenceWordOrBit.Rule = SLCRegisterReferenceWordWithBit | SLCRegisterWord;
            SLCRegisterReference.Rule = SLCFilePrefix + SLCRegisterFileNumber + ":" + SLCRegisterReferenceWordOrBit;
            SLCInstructionRegisterList.Rule = MakePlusRule(SLCInstructionRegisterList, SLCRegisterReference);

            //Set grammar root
            this.Root = SLCInstructionRegisterList;
            //MarkPunctuation(" ");

        }//constructor
    }//class
}//namespace
</code>```

If I change the following line

```<code>SLCInstructionRegisterList.Rule = MakePlusRule(SLCInstructionRegisterList, SLCRegisterReference);
</code>```

To

```<code>SLCInstructionRegisterList.Rule = MakePlusRule(SLCInstructionRegisterList, ToTerm(" "), SLCRegisterReference);
</code>```

I get

Error: (L1,C9) Syntax error, expected:

Which I assume means it is expecting a space character

Any help would be appreciated. I've just started Learning irony and there isn't a ton of documentation.

Note: Later on I would like to be able to parse a register that takes this form T8:5/DN meaning that after the forward-slash is a string instead of a number. that is terminated is white space

答:
Using the ValidateTokenMethod, and rejecting anything that was not A-Z Solved this issue.

The problem was that / was being interpreted as the start of a new Register Reference

```<code>var SLCFilePrefix = new FixedLengthLiteral("Type", 1, TypeCode.String);
SLCFilePrefix.ValidateToken += (e, s) =>
{
    if (char.IsUpper(s.Token.ValueString[0]) == false)
    {
        s.RejectToken();
    }
};
</code>```

Thank you Roman Ivantsov (Original Creator) for responding and helping me with this via email.

Body:
I am trying to write a parser for Allen Bradly SLC Language/File format. I have successfully got it to parse a register reference. I.E. N5:4/3. However, when I try to move to to the next level, having it parse a list of register references separated by whitespace, it throws the following error

Input:

N30:3/8 B20:3/3

Error:

(L1, C9) Syntax error, expected: :

Here is my code, this can be built and the dll loaded into the Irony Grammar Explorer

using System;
using Irony.Parsing;

namespace Irony.Samples.SLC
{
    [Language("SLC", "1.0", "RS Logix 500 SLC")]
    public class SLCGrammar : Grammar
    {
        public SLCGrammar()
        {
            //Terminals
            var SLCFilePrefix = new FixedLengthLiteral("Type", 1, TypeCode.String);
            var SLCRegisterWord = new NumberLiteral("Word");
            var SLCRegisterBit = new NumberLiteral("Bit");
            var SLCRegisterFileNumber = new NumberLiteral("FileNumber");

            //Nonterminals
            var SLCInstructionRegisterList = new NonTerminal("InstructionRegisterList");
            var SLCRegisterReference = new NonTerminal("RegisterReference");
            var SLCRegisterReferenceWordOrBit = new NonTerminal("RegisterReferenceWordOrBit");
            var SLCRegisterReferenceWordWithBit = new NonTerminal("RegisterReferenceWordWithBit");

            //Rules
            SLCRegisterReferenceWordWithBit.Rule = SLCRegisterWord + "/" + SLCRegisterBit;
            SLCRegisterReferenceWordOrBit.Rule = SLCRegisterReferenceWordWithBit | SLCRegisterWord;
            SLCRegisterReference.Rule = SLCFilePrefix + SLCRegisterFileNumber + ":" + SLCRegisterReferenceWordOrBit;
            SLCInstructionRegisterList.Rule = MakePlusRule(SLCInstructionRegisterList, SLCRegisterReference);

            //Set grammar root
            this.Root = SLCInstructionRegisterList;
            //MarkPunctuation(" ");

        }//constructor
    }//class
}//namespace

If I change the following line

SLCInstructionRegisterList.Rule = MakePlusRule(SLCInstructionRegisterList, SLCRegisterReference);

To

SLCInstructionRegisterList.Rule = MakePlusRule(SLCInstructionRegisterList, ToTerm(" "), SLCRegisterReference);

I get

Error: (L1,C9) Syntax error, expected:

Which I assume means it is expecting a space character

Any help would be appreciated. I've just started Learning irony and there isn't a ton of documentation.

Note: Later on I would like to be able to parse a register that takes this form T8:5/DN meaning that after the forward-slash is a string instead of a number. that is terminated is white space

Body:
Using the ValidateTokenMethod, and rejecting anything that was not A-Z Solved this issue.

The problem was that / was being interpreted as the start of a new Register Reference

var SLCFilePrefix = new FixedLengthLiteral("Type", 1, TypeCode.String);
SLCFilePrefix.ValidateToken += (e, s) =>
{
    if (char.IsUpper(s.Token.ValueString[0]) == false)
    {
        s.RejectToken();
    }
};

Thank you Roman Ivantsov (Original Creator) for responding and helping me with this via email.


问:
Python Compare lists
So I have this script,

```<code>good_users=[]

async def callposts(ctx):
    g0=str(ctx.guild)
    g=g0.replace(' ','_')
    sqluse(g)
    x="SELECT authorid, COUNT(*) FROM posts GROUP BY authorid"
    mycursor.execute(x)
    k=mycursor.fetchall()
    for user in k:
        if user[1] > 7:
            good_users.append(user)
            k.remove(user)
            print(user)
    return k

async def kick(ctx, uid):
    await ctx.guild.kick(ctx.guild.get_member(int(uid)))

@client.command(pass_context = True)
async def post_check(ctx):
    ausers=list(ctx.guild.members)
    lowposters= await callposts(ctx)
    for user in ausers:
        if user == client.user:
            print(user.name+" is a bot!")
            ausers.remove(user)
        elif user.id in exempt:
            print(user.name+" is exempt!")
            ausers.remove(user)
        elif user.id in good_users:
            print(user.name+" is a good user!")
            ausers.remove(user)
        else:
            await kick(ctx,user.id)
    print(ausers)
</code>```

What I am trying to do here is remove inactive users. So I have 2 lists that I want to compare the memberlist to, exempt and good_users. I also am checking to make sure it isn't the bot. So this script removes the bot from the list but it doesn't remove the user that's in exempt or good users. So in turn it tries to kick everyone that's not a bot.  They are trying to take over!

I'm looking this over but right now I'm sick so not 100%.

The prints are just for troubleshooting purposes however, all but the firt print in the callpost function print nothing and that one for some reason only prints the user, now it isn't printing the bot so the bot may not be in the list to get removed.

Any thoughts?

答:
You're never appending anything to exempt_users and because of the scope of good_users it is only filled with users within callposts() because you're not returning it when calling it in post_check().

Changing the following should fix your problem:

Return good_users from callposts()

Add a new variable to where you call callposts() in post_check() like

```<code>lowposters, good_users = await callposts(ctx)
</code>```

Title: Python Compare lists

Body:
So I have this script,

good_users=[]

async def callposts(ctx):
    g0=str(ctx.guild)
    g=g0.replace(' ','_')
    sqluse(g)
    x="SELECT authorid, COUNT(*) FROM posts GROUP BY authorid"
    mycursor.execute(x)
    k=mycursor.fetchall()
    for user in k:
        if user[1] > 7:
            good_users.append(user)
            k.remove(user)
            print(user)
    return k

async def kick(ctx, uid):
    await ctx.guild.kick(ctx.guild.get_member(int(uid)))

@client.command(pass_context = True)
async def post_check(ctx):
    ausers=list(ctx.guild.members)
    lowposters= await callposts(ctx)
    for user in ausers:
        if user == client.user:
            print(user.name+" is a bot!")
            ausers.remove(user)
        elif user.id in exempt:
            print(user.name+" is exempt!")
            ausers.remove(user)
        elif user.id in good_users:
            print(user.name+" is a good user!")
            ausers.remove(user)
        else:
            await kick(ctx,user.id)
    print(ausers)

What I am trying to do here is remove inactive users. So I have 2 lists that I want to compare the memberlist to, exempt and good_users. I also am checking to make sure it isn't the bot. So this script removes the bot from the list but it doesn't remove the user that's in exempt or good users. So in turn it tries to kick everyone that's not a bot.  They are trying to take over!

I'm looking this over but right now I'm sick so not 100%.

The prints are just for troubleshooting purposes however, all but the firt print in the callpost function print nothing and that one for some reason only prints the user, now it isn't printing the bot so the bot may not be in the list to get removed.

Any thoughts?

Body:
You're never appending anything to exempt_users and because of the scope of good_users it is only filled with users within callposts() because you're not returning it when calling it in post_check().

Changing the following should fix your problem:

Return good_users from callposts()

Add a new variable to where you call callposts() in post_check() like

lowposters, good_users = await callposts(ctx)


问:
Clicking on Notification in background not open my App?
I am a newbie in android development.

I create a background service for receive pushNotification (with our own socket service, not FCM).
And now my device receive message and show notification successfully. But when I click the notification, it not return to my app.

When I click notification, show the error below:
ActivityManager: Unable to start service Intent { cmp=com.my.app/package.name.AppActivity } U=0: not found

Here is my code:

```<code>
    public static void setNotification(Service service, String message) {

        NotificationManager manager = (NotificationManager) service.getSystemService(NOTIFICATION_SERVICE);

        String appName = service.getString(R.string.app_name);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(service)
                .setContentTitle(appName)
                .setContentText(message)
                .setContentIntent(getDefaultIntent(service))
                .setWhen(System.currentTimeMillis())
                .setOngoing(false)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setSmallIcon(R.drawable.icon)
                .setLargeIcon(BitmapFactory.decodeResource(service.getResources(), R.drawable.icon))
                .setSound(alarmSound);
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        manager.notify(1, notification);
    }

    private static PendingIntent getDefaultIntent(Service service) {
        Intent intent = new Intent(service, AppActivity.class);
        PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return pendingIntent;
    }
}
</code>```

MainActivity setting in AndroidManifest.xml

```<code><activity android:name="package.name.AppActivity" android:configChanges="orientation|screenSize" android:label="@string/app_name" android:launchMode="singleTask" android:screenOrientation="landscape" android:theme= "@android:style/Theme.NoTitleBar.Fullscreen" android:enabled="true" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>

    </activity>
</code>```

Please guide me what I am missing or doing wrong in this code. Many thanks.

答:
I pass same id in padding intent and manager.notify(0, notification);

And use PendingIntent.getActivity instead of PendingIntent.getService

it works!

Body:
I am a newbie in android development.

I create a background service for receive pushNotification (with our own socket service, not FCM).
And now my device receive message and show notification successfully. But when I click the notification, it not return to my app.

When I click notification, show the error below:
ActivityManager: Unable to start service Intent { cmp=com.my.app/package.name.AppActivity } U=0: not found

Here is my code:

    public static void setNotification(Service service, String message) {

        NotificationManager manager = (NotificationManager) service.getSystemService(NOTIFICATION_SERVICE);

        String appName = service.getString(R.string.app_name);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(service)
                .setContentTitle(appName)
                .setContentText(message)
                .setContentIntent(getDefaultIntent(service))
                .setWhen(System.currentTimeMillis())
                .setOngoing(false)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setSmallIcon(R.drawable.icon)
                .setLargeIcon(BitmapFactory.decodeResource(service.getResources(), R.drawable.icon))
                .setSound(alarmSound);
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        manager.notify(1, notification);
    }

    private static PendingIntent getDefaultIntent(Service service) {
        Intent intent = new Intent(service, AppActivity.class);
        PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return pendingIntent;
    }
}

MainActivity setting in AndroidManifest.xml

<activity android:name="package.name.AppActivity" android:configChanges="orientation|screenSize" android:label="@string/app_name" android:launchMode="singleTask" android:screenOrientation="landscape" android:theme= "@android:style/Theme.NoTitleBar.Fullscreen" android:enabled="true" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>

    </activity>

Please guide me what I am missing or doing wrong in this code. Many thanks.


问:
remove black border from UISearchController search bar swift
I have a UISearchController in my tableView. Also note that there is a navigation item in the top.
My issue is that i have a black border in the top and bottom when I load the page, however, it is not present when I click the search bar.

Search bar on page load (with black border):

After clicking on search bar (no black border):

Here is the code related:

```<code>let searchController = UISearchController(searchResultsController: nil)
</code>```

in viewDidLoad:

```<code>searchController.searchBar.barTintColor = UIColor.redColor()
        searchController.searchBar.tintColor = UIColor.whiteColor()
</code>```

I followed several similar questions and made the following changes after the above lines in viewDidLoad():

1) searchController.searchBar.backgroundImage = UIImage()

2) searchController.searchBar.searchBarStyle = UISearchBarStyle.Minimal

3) searchController.searchBar.layer.borderColor = UIColor.clearColor().CGColor

4)

```<code> searchBar.layer.borderWidth = 1
    searchBar.layer.borderColor = UIColor.whiteColor().CGColor
</code>```

None worked. Is this an issue with the order I am using the code, or how would I get rid of these lines?

答:
For iOS 13 / Swift 5; the following line makes the trick: </p>

```<code>  UISearchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
</code>```

<p>Cheers! </p>

ContentLicense: CC BY-SA 3.0

Body:
I have a UISearchController in my tableView. Also note that there is a navigation item in the top.
My issue is that i have a black border in the top and bottom when I load the page, however, it is not present when I click the search bar.

Search bar on page load (with black border):

After clicking on search bar (no black border):

Here is the code related:

let searchController = UISearchController(searchResultsController: nil)

in viewDidLoad:

searchController.searchBar.barTintColor = UIColor.redColor()
        searchController.searchBar.tintColor = UIColor.whiteColor()

I followed several similar questions and made the following changes after the above lines in viewDidLoad():

1) searchController.searchBar.backgroundImage = UIImage()

2) searchController.searchBar.searchBarStyle = UISearchBarStyle.Minimal

3) searchController.searchBar.layer.borderColor = UIColor.clearColor().CGColor

4)

 searchBar.layer.borderWidth = 1
    searchBar.layer.borderColor = UIColor.whiteColor().CGColor

None worked. Is this an issue with the order I am using the code, or how would I get rid of these lines?

Body:
For iOS 13 / Swift 5; the following line makes the trick:

  UISearchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)

Cheers!


问:
PHP preg_match captures not working as expected
```<code><?php
$html = <<<EOD
dsfgvsdfgv
sdfgv
sdfgv
<span id="userStatusText" class="text-overflow ng-binding userstatus-editable" title="_epic Can I have Coffee" ng-class="{'userstatus-editable':profileHeaderLayout.mayUpdateStatus}" ng-bind="profileHeaderLayout.statusText|statusfilter" ng-click="revealStatusForm()">"_epic Can I have Coffee"</span>
fdgvsdfgvsdfvg
var_dumpgv
dsfgv
EOD;

preg_match("!<span.+id=\"userStatusText\".+>(.*)<\/span>!", $html, $element);

if (!$element) {
  return;
}
echo $element[0];
</code>```

I apologize for the atrocious variable, but I am trying to fetch _epic Can I have Coffee from the string.

I have been trying to fetch the string inside the parenthesis which were called captures on the PHP documentation.

I want to be able to capture the text inside (.*) which is not working.

When executing the preg_match, I would still get only the span element ... (substitute ... for the content in the $html variable).

I have looked on several threads and documentation and couldn't find anything that would answer my issue.

Here is what it looks like when I execute it

I'm not trying to get the element but getting the text inside the  Right Here

答:
DOMDocument and DOMXPath are the more appropriate way to parse HTML in PHP:

```<code>$html = <<<EOD
dsfgvsdfgv
sdfgv
sdfgv
<span id="userStatusText" class="text-overflow ng-binding userstatus-editable" title="_epic Can I have Coffee" ng-class="{'userstatus-editable':profileHeaderLayout.mayUpdateStatus}" ng-bind="profileHeaderLayout.statusText|statusfilter" ng-click="revealStatusForm()">"_epic Can I have Coffee"</span>
fdgvsdfgvsdfvg
var_dumpgv
dsfgv
EOD;

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//span[@id="userStatusText"]') as $span) {
    echo $span->getAttribute('title');
}
</code>```

Output:

```<code>_epic Can I have Coffee
</code>```

Demo on 3v4l.org

Body:
<?php
$html = <<<EOD
dsfgvsdfgv
sdfgv
sdfgv
"_epic Can I have Coffee"
fdgvsdfgvsdfvg
var_dumpgv
dsfgv
EOD;

preg_match("!(.*)<\/span>!", $html, $element);

if (!$element) {
  return;
}
echo $element[0];

I apologize for the atrocious variable, but I am trying to fetch _epic Can I have Coffee from the string.

I have been trying to fetch the string inside the parenthesis which were called captures on the PHP documentation.

I want to be able to capture the text inside (.*) which is not working.

When executing the preg_match, I would still get only the span element ... (substitute ... for the content in the $html variable).

I have looked on several threads and documentation and couldn't find anything that would answer my issue.

Here is what it looks like when I execute it

I'm not trying to get the element but getting the text inside the  Right Here

Body:
DOMDocument and DOMXPath are the more appropriate way to parse HTML in PHP:

$html = <<<EOD
dsfgvsdfgv
sdfgv
sdfgv
<span id="userStatusText" class="text-overflow ng-binding userstatus-editable" title="_epic Can I have Coffee" ng-class="{'userstatus-editable':profileHeaderLayout.mayUpdateStatus}" ng-bind="profileHeaderLayout.statusText|statusfilter" ng-click="revealStatusForm()">"_epic Can I have Coffee"</span>
fdgvsdfgvsdfvg
var_dumpgv
dsfgv
EOD;

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//span[@id="userStatusText"]') as $span) {
    echo $span->getAttribute('title');
}

Output:

_epic Can I have Coffee

Demo on 3v4l.org


问:
Where in Azure Portal are the logger.Log statements?
I have a .NET Core WebAPI app. The app is deployed on Azure as an App Service.

In the code, I have enabled Application Insights like so

```<code>public static IWebHost BuildWebHost(string[] args) =>
    WebHost
    .CreateDefaultBuilder(args)
    .UseApplicationInsights()
    .UseStartup<Startup>()
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")).SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Error);
        logging.AddApplicationInsights(" xxxxx-xxxx-xxxx-xxxx--xxxxxxxxxxx").SetMinimumLevel(LogLevel.Trace);
    })
    .Build();
</code>```

In the constructor of a controller and inside an method of a controller I have these logging statements.

```<code>_logger.LogInformation("ApiController, information");
_logger.LogWarning("ApiController, warning");
_logger.LogCritical("ApiController, critical");
_logger.LogWarning("ApiController, error");
_logger.LogDebug("ApiController, debug");
</code>```

In the Azure Portal I have Application Insights for my App Service enabled. Here a picture from the portal.

App Insights in Azure Portal

But where do I see the logging statements in the Azure portal?

When I go to Application Insights -> Logs and I query by

```<code>search *
</code>```

I can see the requests made to the API but not the logging statements.

Application Insights Log

Where are the log statements?

答:
First, it is not good practice to configure the log level in code. You can easily configure the log level in the appsettings.json file. So in Program.cs -> public static IWebHost BuildWebHost method, change the code to below:

```<code>public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseApplicationInsights()
                .UseStartup<Startup>()
                .Build();
</code>```

Then in appsettings.json(also right click the file -> properties -> set "copy to output directory" to "Copy if newer"):

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Trace"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "the key"
  }
}
</code>```

In Controller, like ValuesController:

```<code>    public class ValuesController : Controller
    {
        private readonly ILogger _logger;
        public ValuesController(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<ValuesController>();
        }

        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            _logger.LogInformation("ApiController, information");
            _logger.LogWarning("ApiController, warning");
            _logger.LogCritical("ApiController, critical");
            _logger.LogWarning("ApiController, error");
            _logger.LogDebug("ApiController, debug");

            return new string[] { "value1", "value2" };
        }
     }
</code>```

Run the project, and wait for a few minutes(application insights would always take 3 to 5 minutes or more to display the data). Then nave to azure portal -> application insights logs, remember that all the logs written by ILogger are stored in "traces" table. Just write the query like "traces" and specify a proper time range, you should see all the logs like below:

Body:
I have a .NET Core WebAPI app. The app is deployed on Azure as an App Service.

In the code, I have enabled Application Insights like so

public static IWebHost BuildWebHost(string[] args) =>
    WebHost
    .CreateDefaultBuilder(args)
    .UseApplicationInsights()
    .UseStartup<Startup>()
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")).SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Error);
        logging.AddApplicationInsights(" xxxxx-xxxx-xxxx-xxxx--xxxxxxxxxxx").SetMinimumLevel(LogLevel.Trace);
    })
    .Build();

In the constructor of a controller and inside an method of a controller I have these logging statements.

_logger.LogInformation("ApiController, information");
_logger.LogWarning("ApiController, warning");
_logger.LogCritical("ApiController, critical");
_logger.LogWarning("ApiController, error");
_logger.LogDebug("ApiController, debug");

In the Azure Portal I have Application Insights for my App Service enabled. Here a picture from the portal.

App Insights in Azure Portal

But where do I see the logging statements in the Azure portal?

When I go to Application Insights -> Logs and I query by

search *

I can see the requests made to the API but not the logging statements.

Application Insights Log

Where are the log statements?

Body:
First, it is not good practice to configure the log level in code. You can easily configure the log level in the appsettings.json file. So in Program.cs -> public static IWebHost BuildWebHost method, change the code to below:

public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseApplicationInsights()
                .UseStartup<Startup>()
                .Build();

Then in appsettings.json(also right click the file -> properties -> set "copy to output directory" to "Copy if newer"):

{
  "Logging": {
    "IncludeScopes": false,
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Trace"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "the key"
  }
}

In Controller, like ValuesController:

    public class ValuesController : Controller
    {
        private readonly ILogger _logger;
        public ValuesController(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<ValuesController>();
        }

        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            _logger.LogInformation("ApiController, information");
            _logger.LogWarning("ApiController, warning");
            _logger.LogCritical("ApiController, critical");
            _logger.LogWarning("ApiController, error");
            _logger.LogDebug("ApiController, debug");

            return new string[] { "value1", "value2" };
        }
     }

Run the project, and wait for a few minutes(application insights would always take 3 to 5 minutes or more to display the data). Then nave to azure portal -> application insights logs, remember that all the logs written by ILogger are stored in "traces" table. Just write the query like "traces" and specify a proper time range, you should see all the logs like below:


问:
C# Design pattern for periodic execution of multiple Threads
I have a below requirement in my C# Windows Service.

At the starting of Service, it fetches a collection of data from db
and keeps it in memory.

Have a business logic to be executed periodically from 3 different threads.

Each thread will execute same bussiness logic with different subset of data from the data collection mentioned in step 1. Each thread will produce different result sets.

All 3 threads will run periodically if any change happened to the data collection.

When any client makes call to the service, service should be able to return the status of the thread execution.

I know C# has different mechanisms to implement periodic thread execution.
 Timers, Threads with Sleep, Event eventwaithandle ect.,
 I am trying to understand Which threading mechanism or design pattern will be best fit for this requirement?

答:
The simplest solution would be to define the scheduled logic in Task Method() style, and execute them using Task.Run(), while in the main thread just wait for the execution to finish using Task.WaitAny(). If a task is finished, you could Call Task.WaitAny again, but instead of the finished task, you'd pass Task.Delay(timeUntilNextSchedule).
This way the tasks are not blocking the main thread, and you can avoid spinning the CPU just to wait. In general, you can avoid managing directly in modern .NET

Depending on other requirements, like standardized error handling, monitoring capability, management of these scheduled task, you could also rely on a more robust solution, like HangFire.


问:
Microsoft Graph: How to get the alias from an email message?
When I use Microsoft Graph to retrieve a message's toRecipients or internetMessageHeaders, I am unable to find the actual email alias that the mail was sent to. How do I get the alias? It is always returning the "parent" account, never the alias account.

For example, this shows alias1@company.com as an alias to account email1@company.com.

Request:

https://graph.microsoft.com/v1.0/users/email1@company.com?$select=proxyAddresses

Response:

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(proxyAddresses)/$entity",
    "proxyAddresses": [
        "smtp:alias1@company.com",
        "X500:/o=Org1/ou=External (xxxxx)/cn=Recipients/cn=00000000000000000000",
        "x500:/o=ExchangeLabs/ou=Exchange Administrative Group (xxxxx)/cn=Recipients/cn=1111111111111111",
        "smtp:email1@company.mail.onmicrosoft.com",
        "X500:/o=Org1/ou=Exchange Administrative Group (xxxxx)/cn=Recipients/cn=yyyyyyyy",
        "smtp:email1@company.onmicrosoft.com",
        "SMTP:email1@company.com"
    ]
}
</code>```

I then send an email to alias1@company.com. I do not see the alias when retrieving toRecipients or internetMessageHeaders, only the parent account email@company.com.

Request:

https://graph.microsoft.com/v1.0/me/messages/{messageId}?$select=toRecipients,internetMessageHeader

Response:

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('...')/messages(toRecipients,internetMessageHeaders)/$entity",
    "@odata.etag": "W/\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"",
    "id": "{messageId}",
    "internetMessageHeaders": [
        {
            "name": "Received",
            "value": "...."
        },
        {
            "name": "Received",
            "value": "..."
        },
        {
            "name": "Received",
            "value": "..."
        },
        {
            "name": "Authentication-Results",
            "value": "company.com; dkim=none (message not signed) header.d=none;company.com; dmarc=none action=none header.from=company.com;"
        },
        {
         ...
        }
    ],
    "toRecipients": [
        {
            "emailAddress": {
                "name": "FirstName LastName",
                "address": "email1@company.com"
            }
        }
    ]
}
</code>```

答:
You can't.

Microsoft Exchange Server, Office 365 and Outlook.com (formerly Hotmail) do not preserve (or at least expose) the SMTP RCPT TO value (i.e. the envelope address) - which is distinct from the To:, Cc:, and Bcc: headers (note that the Bcc header isn't usually sent at all to the recipient anyway).

This is how e-mail users can receive emails that don't look like they're intended for them (as e-mail servers use the RCPT TO value to route the email and ignore the To: header.

Note that anti-spam software will often flag emails when the RCPT TO value doesn't appear in any of the To:, Cc:, or Bcc: headers as in the late-1990s/early-200s mass-mailed spam didn't have personalised To: headers.

Warning: editorial content below:

I did submit a request with Office 365 support (as I'm an Enterprise subscriber, which I hope means something) to request that they add support for storing the RCPT TO envelope address, but it was thrown onto the backlog and so will never happen. It's yet another bloody obvious feature of an e-mail system that Microsoft steadfastly refuses to adopt, just like disposable addresses, messaging tagging, inline quote replies, separating mailboxes from users, and a tree-view for conversation threads - and more besides. Oy vey.

Body:
When I use Microsoft Graph to retrieve a message's toRecipients or internetMessageHeaders, I am unable to find the actual email alias that the mail was sent to. How do I get the alias? It is always returning the "parent" account, never the alias account.

For example, this shows alias1@company.com as an alias to account email1@company.com.

Request:

https://graph.microsoft.com/v1.0/users/email1@company.com?$select=proxyAddresses

Response:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(proxyAddresses)/$entity",
    "proxyAddresses": [
        "smtp:alias1@company.com",
        "X500:/o=Org1/ou=External (xxxxx)/cn=Recipients/cn=00000000000000000000",
        "x500:/o=ExchangeLabs/ou=Exchange Administrative Group (xxxxx)/cn=Recipients/cn=1111111111111111",
        "smtp:email1@company.mail.onmicrosoft.com",
        "X500:/o=Org1/ou=Exchange Administrative Group (xxxxx)/cn=Recipients/cn=yyyyyyyy",
        "smtp:email1@company.onmicrosoft.com",
        "SMTP:email1@company.com"
    ]
}

I then send an email to alias1@company.com. I do not see the alias when retrieving toRecipients or internetMessageHeaders, only the parent account email@company.com.

Request:

https://graph.microsoft.com/v1.0/me/messages/{messageId}?$select=toRecipients,internetMessageHeader

Response:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('...')/messages(toRecipients,internetMessageHeaders)/$entity",
    "@odata.etag": "W/\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"",
    "id": "{messageId}",
    "internetMessageHeaders": [
        {
            "name": "Received",
            "value": "...."
        },
        {
            "name": "Received",
            "value": "..."
        },
        {
            "name": "Received",
            "value": "..."
        },
        {
            "name": "Authentication-Results",
            "value": "company.com; dkim=none (message not signed) header.d=none;company.com; dmarc=none action=none header.from=company.com;"
        },
        {
         ...
        }
    ],
    "toRecipients": [
        {
            "emailAddress": {
                "name": "FirstName LastName",
                "address": "email1@company.com"
            }
        }
    ]
}


问:
The css attribute "line-height" has no effect under an iframe wrapper?
I don't know why "line-height" lose efficacy under iframe, did someone meet same issue before? By the way, there are two diffs:
 1. I used iframe in a way: document.write not src. Does it matter?
 2. There is a svg tag under div

```<code><div style="line-height: 20;">
    <i aria-label="icon: warning" class="anticon anticon-warning icon" style="font-size: 22px;">
      <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path>
      </svg>
    </i>
</div>
</code>```

Here is an full example:

setTimeout(function() {
  var iframe = document.getElementById('iframe');
  var doc = iframe.contentWindow.document;
  var body = iframe.contentWindow.document.body;
  doc.open();
  doc.write(`

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>EDITOR DEMO IFRAME</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/antd@3.26.8/dist/antd.min.css" />

        test

          <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path></svg>

    `);
  doc.close();
}, 2000)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>EDITOR DEMO</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/antd@3.26.8/dist/antd.min.css" />
</head>

<body>
  <div id="app">
    <div>
      <i aria-label="icon: warning" class="anticon anticon-warning icon" style="font-size: 22px;"><svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path></svg></i>
    </div>
    iframe：
    <iframe id="iframe" style="width: 500px; height: 500px; border: 1px solid #ccc;"></iframe>
  </div>
</body>

</html></code>```

答:
Solved! <!DOCTYPE html> and  is missing when running doc.write.

```<code>setTimeout(function() {
  var iframe = document.getElementById('iframe');
  var doc = iframe.contentWindow.document;
  var body = iframe.contentWindow.document.body;
  doc.open();
  doc.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>EDITOR DEMO IFRAME</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/antd@3.26.8/dist/antd.min.css" />
      </head>
      <body>
        test
        <div style="line-height: 20;">
          <i aria-label="icon: warning" class="anticon anticon-warning icon" style="font-size: 22px;"><svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path></svg></i>
        </div>
      </body>
      </html>
    `);
  doc.close();
}, 2000)
</code>```

Body:
I don't know why "line-height" lose efficacy under iframe, did someone meet same issue before? By the way, there are two diffs:
 1. I used iframe in a way: document.write not src. Does it matter?
 2. There is a svg tag under div

      <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path>
      </svg>

Here is an full example:

setTimeout(function() {
  var iframe = document.getElementById('iframe');
  var doc = iframe.contentWindow.document;
  var body = iframe.contentWindow.document.body;
  doc.open();
  doc.write(`

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>EDITOR DEMO IFRAME</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/antd@3.26.8/dist/antd.min.css" />

        test

          <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path></svg>

    `);
  doc.close();
}, 2000)

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>EDITOR DEMO</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/antd@3.26.8/dist/antd.min.css" />

      <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path></svg>

    iframe：

Body:
Solved! <!DOCTYPE html> and <html> is missing when running doc.write.

setTimeout(function() {
  var iframe = document.getElementById('iframe');
  var doc = iframe.contentWindow.document;
  var body = iframe.contentWindow.document.body;
  doc.open();
  doc.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>EDITOR DEMO IFRAME</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/antd@3.26.8/dist/antd.min.css" />
      </head>
      <body>
        test
        <div style="line-height: 20;">
          <i aria-label="icon: warning" class="anticon anticon-warning icon" style="font-size: 22px;"><svg viewBox="64 64 896 896" focusable="false" class="" data-icon="warning" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M464 720a48 48 0 1 0 96 0 48 48 0 1 0-96 0zm16-304v184c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V416c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8zm475.7 440l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zm-783.5-27.9L512 239.9l339.8 588.2H172.2z"></path></svg></i>
        </div>
      </body>
      </html>
    `);
  doc.close();
}, 2000)


问:
Error: Environment /Users/myuser/.virtualenvs/iron does not contain activation script
I am running python 3.7.6 on macOS Catalina version 10.15.1 and I am trying to install and set up virtualenvwrapper which I have installed with pip3 install virtualenvwrapper.

I have the following lines in my .bash_profile:

```<code>export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV=/Users/maxcarey/Library/Python/3.7/bin/virtualenv
export WORKON_HOME=$HOME/.virtualenvs
source /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh
</code>```

These are configuration steps I have followed from:
https://stackoverflow.com/a/42643313/5420796. As well as other tutorials (like this one)

So you can see I'm attemping to point these export variables to the right place, in my terminal, the output of which python3 is /usr/local/bin/python3
The output of which virtualenv is: /Users/maxcarey/Library/Python/3.7/bin/virtualenv.
The output of which virtualenvwrapper.sh is /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh

Here is the problem: when I run: mkvirtualenv iron  to create a new virtual environment (called iron in this case), the output of the command is:

created virtual environment in 193ms CPython3Posix(dest=/Users/maxcarey/.virtualenvs/iron, clear=False, global=False) with seeder FromAppData pip=latest setuptools=latest wheel=latest app_data_dir=/Users/maxcarey/Library/Application Support/virtualenv/seed-v1 via=copy
virtualenvwrapper.user_scripts creating /Users/maxcarey/.virtualenvs/iron/bin/predeactivate
ERROR: Environment '/Users/maxcarey/.virtualenvs/iron' does not contain an activate script.

You can see that a virtual environment is indeed created, however, I get an error saying there is no activation script. However, when I navigate to ~/.virtualenvs, I can indeed see the activation scripts. Here is the output of tree inside the new folder iron/local/:

```<code>└── local
    └── bin
        ├── activate
        ├── activate.csh
        ├── activate.fish
        ├── activate.ps1
        ├── activate.xsh
        ├── activate_this.py
        ├── easy_install
        ├── easy_install-3.7
        ├── easy_install3
        ├── pip
        ├── pip-3.7
        ├── pip3
        ├── python -> /Library/Developer/CommandLineTools/usr/bin/python3
        ├── python3 -> python
        ├── python3.7 -> python
        ├── wheel
        ├── wheel-3.7
        └── wheel3

</code>```

It does indeed appear that there are activation scripts. So I am stumped about why I get the activation script error (which I also get when running workon iron). I have tried simply destroying and recreating the virtual environment with rmvirtualenv iron, which works, however, when creating the environment again I still get the same error. Thank You

答:
I'm running on a raspbian buster with Python 3.7.3. I ran into the same issue, "ERROR...no activation script". I tried @Lombax answer but it didn't work.

However, I noticed that the version of virtualenvwrapper I had installed was 5.0.0. I checked on PyPi and it's still at version 4.8.4. So I uninstalled virtualenv and virtualenvwrapper: sudo pip3 uninstall virtualenv virtualenvwrapper.

Then I reinstalled both and specified the version: sudo pip3 install virtualenv virtualenvwrapper=='4.8.4'
I sourced my .bashrc, in which I had appended the settings:

```<code>VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
export PATH=/usr/local/bin:$PATH
export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
</code>```

And now mkvirtualenv test works.  Not sure what's the bug with version 5.x of virtualenvwrapper, in the meantime, this got around the problem for me, hope this helps.

Body:
I am running python 3.7.6 on macOS Catalina version 10.15.1 and I am trying to install and set up virtualenvwrapper which I have installed with pip3 install virtualenvwrapper.

I have the following lines in my .bash_profile:

export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV=/Users/maxcarey/Library/Python/3.7/bin/virtualenv
export WORKON_HOME=$HOME/.virtualenvs
source /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh

These are configuration steps I have followed from:
https://stackoverflow.com/a/42643313/5420796. As well as other tutorials (like this one)

So you can see I'm attemping to point these export variables to the right place, in my terminal, the output of which python3 is /usr/local/bin/python3
The output of which virtualenv is: /Users/maxcarey/Library/Python/3.7/bin/virtualenv.
The output of which virtualenvwrapper.sh is /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh

Here is the problem: when I run: mkvirtualenv iron  to create a new virtual environment (called iron in this case), the output of the command is:

created virtual environment in 193ms CPython3Posix(dest=/Users/maxcarey/.virtualenvs/iron, clear=False, global=False) with seeder FromAppData pip=latest setuptools=latest wheel=latest app_data_dir=/Users/maxcarey/Library/Application Support/virtualenv/seed-v1 via=copy
virtualenvwrapper.user_scripts creating /Users/maxcarey/.virtualenvs/iron/bin/predeactivate
ERROR: Environment '/Users/maxcarey/.virtualenvs/iron' does not contain an activate script.

You can see that a virtual environment is indeed created, however, I get an error saying there is no activation script. However, when I navigate to ~/.virtualenvs, I can indeed see the activation scripts. Here is the output of tree inside the new folder iron/local/:

└── local
    └── bin
        ├── activate
        ├── activate.csh
        ├── activate.fish
        ├── activate.ps1
        ├── activate.xsh
        ├── activate_this.py
        ├── easy_install
        ├── easy_install-3.7
        ├── easy_install3
        ├── pip
        ├── pip-3.7
        ├── pip3
        ├── python -> /Library/Developer/CommandLineTools/usr/bin/python3
        ├── python3 -> python
        ├── python3.7 -> python
        ├── wheel
        ├── wheel-3.7
        └── wheel3

It does indeed appear that there are activation scripts. So I am stumped about why I get the activation script error (which I also get when running workon iron). I have tried simply destroying and recreating the virtual environment with rmvirtualenv iron, which works, however, when creating the environment again I still get the same error. Thank You

Body:
I'm running on a raspbian buster with Python 3.7.3. I ran into the same issue, "ERROR...no activation script". I tried @Lombax answer but it didn't work.

However, I noticed that the version of virtualenvwrapper I had installed was 5.0.0. I checked on PyPi and it's still at version 4.8.4. So I uninstalled virtualenv and virtualenvwrapper: sudo pip3 uninstall virtualenv virtualenvwrapper.

Then I reinstalled both and specified the version: sudo pip3 install virtualenv virtualenvwrapper=='4.8.4'
I sourced my .bashrc, in which I had appended the settings:

VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
export PATH=/usr/local/bin:$PATH
export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

And now mkvirtualenv test works.  Not sure what's the bug with version 5.x of virtualenvwrapper, in the meantime, this got around the problem for me, hope this helps.


问:
Send modbus rtu command directly to client without using Virtual Comport
I'm doing a system that gathers information from sensors and receive information sent by them through USR DTU.

For now, I have succeeded configuring the sensors - DTU & server connection through TCP/IP.
However, my old program can only read & write data through COM Port.
That's why I have to use Virtual COM Port software to make a bridge between Server program (which uses COM Port) & USR DTU through TCP/IP Connection.

My question is: Can I send the command (which is modbus rtu protocol) through TCP/IP Connection directly without help of Virtual COM Port software ? I want to do this because virtual com port software only allows me to create 255 ports and that is not enough to me.

答:
Can I send the command (which is modbus rtu protocol) through TCP/IP
  Connection directly without help of Virtual COM Port software

It looks like you are using a USR-GPRS232-730 and these units have a "Transparent Mode". With that mode enabled anything sent via the TCP/IP link is retransmitted over the serial link and vice versa. So long as that is the case then the answer is yes it is possible to transmit Modbus RTU commands over the link without using a virtual com port. I use this technique (with different GPRS units) to poll a range of remote RTU devices.

I want to do this because virtual com port software only allows me to
  create 255 ports and that is not enough to me

Therein lies the problem; if your software only supports local ports then you need to provide it with a local port (which is what the Virtual Com Port software does). Your question is not clear on whether you are considering replacing your "old program" or what the software is, what OS you are using etc.


问:
SVN user access to certain projects configuration
i'm completely new to the unix systems... been playing around about 2 weeks.
i've managed to install subversion and create a repositories.

lets say we have users:

```<code>internal_developer
external_developer_1
external_developer_2
</code>```

we have a projects:

```<code>repositories/project1
repositories/project2
repositories/project3
</code>```

how can i configure the access for each user and project independantly.

internal_developer - can access all projects ( rw )

external_developer_1 - can only access project1 ( rw )

external_developer_2 - can only access project2 ( rw )

when i say "can only access" it means that he can not see the repositories/* content, only the projects he is working with.

i've tried to look for some manuals or tutorials how can i do this... but all of them are for more expierienced users then i am...

any help is appreciated.

---

Edit. ( can not yet answer my question )

in the file /etc/apache2/mods-available/dav_svn.conf

at the location of AuthUserFile stored only user names and passwords.

then

need to add new line: AuthzSVNAccessFile /usr/passwd/svn.authz

then there goes the syntax from Floyd ^^.

I looked here: Subversion - how do I control user access for single repository when SVNParentPath is used?

And with the groups it looks more like it.

Stil, one missing part left... can not configure the admin user to see all repositories when comes to http://xxxxxx/svn/

gives an error

Forbidden

You don't have permission to access /svn/ on this server.

even i puted in the svn.authz:

```<code>[/]
@internal = rw
</code>```

答:
If you using Apache (Mod_Dav_Svn) to expose your repository then you need to add Auth support to the  Directive in your apache conf file

```<code><location ...>
   ...
   AuthType Basic
   AuthName "My Subversion repository"
   AuthUserFile /srv/svn/conf/passwd
</Location>
</code>```

In the file referenced in the AuthUserFile you can specify the permissions you need like so:

```<code>[/]
* =
[project1:/]
internal_developer = rw
external_developer_1 =
external_developer_2 =
[project2:/]
internal_developer = rw
external_developer_1 =  rw
external_developer_2 =
[project2:/]
internal_developer = rw
external_developer_1 =
external_developer_2 = rw
</code>```

You can also set permissions at a more granular level on a per folder basis as follows

```<code>[/project1:/public_folder]
* = r
</code>```

I hope this helps?

You might also want to consider using a third party to host your code, CodeSpaces.com do subversion hosting that have granular permissions, plus you don't have the headache of managing your own infrastructure, backups, etc...

Body:
i'm completely new to the unix systems... been playing around about 2 weeks.
i've managed to install subversion and create a repositories.

lets say we have users:

internal_developer
external_developer_1
external_developer_2

we have a projects:

repositories/project1
repositories/project2
repositories/project3

how can i configure the access for each user and project independantly.

internal_developer - can access all projects ( rw )

external_developer_1 - can only access project1 ( rw )

external_developer_2 - can only access project2 ( rw )

when i say "can only access" it means that he can not see the repositories/* content, only the projects he is working with.

i've tried to look for some manuals or tutorials how can i do this... but all of them are for more expierienced users then i am...

any help is appreciated.

---

Edit. ( can not yet answer my question )

in the file /etc/apache2/mods-available/dav_svn.conf

at the location of AuthUserFile stored only user names and passwords.

then

need to add new line: AuthzSVNAccessFile /usr/passwd/svn.authz

then there goes the syntax from Floyd ^^.

I looked here: Subversion - how do I control user access for single repository when SVNParentPath is used?

And with the groups it looks more like it.

Stil, one missing part left... can not configure the admin user to see all repositories when comes to http://xxxxxx/svn/

gives an error

Forbidden

You don't have permission to access /svn/ on this server.

even i puted in the svn.authz:

[/]
@internal = rw

Body:
If you using Apache (Mod_Dav_Svn) to expose your repository then you need to add Auth support to the  Directive in your apache conf file

<location ...>
   ...
   AuthType Basic
   AuthName "My Subversion repository"
   AuthUserFile /srv/svn/conf/passwd
</Location>

In the file referenced in the AuthUserFile you can specify the permissions you need like so:

[/]
* =
[project1:/]
internal_developer = rw
external_developer_1 =
external_developer_2 =
[project2:/]
internal_developer = rw
external_developer_1 =  rw
external_developer_2 =
[project2:/]
internal_developer = rw
external_developer_1 =
external_developer_2 = rw

You can also set permissions at a more granular level on a per folder basis as follows

[/project1:/public_folder]
* = r

I hope this helps?

You might also want to consider using a third party to host your code, CodeSpaces.com do subversion hosting that have granular permissions, plus you don't have the headache of managing your own infrastructure, backups, etc...


问:
Implementing filter of nested arrays in PHP/Wordpress
I have in the process of moving some code from the front-end (in JavaScript) to the server-side (which is PHP) where it will be filtered and sent out in an API call, and I can't seem to get the filter working properly on the back-end. The code takes an array of objects and filters it for the objects where a certain nested field (which is also an array of objects) contains certain values. The basic shape of the API:

```<code>{
  "id": 1217,
  "name": "Best product ever",
  "tags": [
      {
        "id": 125,
        "name": "Important Value",
        "slug": "important-value"
      },
      {
        "id": 157,
        "name": "Value",
        "slug": "value"
      },
      {
    "id": 180,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 126,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 206,
    "name": "Other Important Value",
    "slug": "other-important-value"
  }
}
</code>```

The working JS code:

```<code>let productAttributes = ['important-value', 'value', 'value', 'value', 'other-important-value'];

filterResults(results) {
let filteredResults = results.filter(product => {
  return product.tags.find(tag => {
    return tag.slug === this.productAttributes[0];
  });
});

if (this.productAttributes[0] !== 'certain important value') {
  filteredResults = filteredResults.filter(product => {
    return product.tags.find(tag => {
      return tag.slug === this.productAttributes[4];
    });
  });
}

return filteredResults;
}
</code>```

And the (not yet working) PHP code:

```<code>function get_awesome_products() {
 $baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/?
 consumer_key=xxxx&consumer_secret=xxxx&per_page=100&page=';
 for ($count = 1; $count <= 9; $count++ ) {
$request = wp_remote_get( $baseRequest . (string)$count);
$body = wp_remote_retrieve_body( $request );
$data = array_values( json_decode( $body, true ));

  if ($count < 2) {
    $completeProductList = $data;
  } else {
    $completeProductList = array_merge($completeProductList, $data);
  }
}
// The code above this comment is doing what I expect, the code below is not.

$filteredProducts = null;
foreach ($completeProductList as &$product) {
  $tagArray = $product['tags'];
  if (in_array($reg_test_array[0], $tagArray, true) &&
  in_array($reg_test_array[4], $tagArray, true))
  {
    array_push($filteredProducts, $product);
  }

  unset($product);
  return new WP_REST_Response($filteredProducts, 200);
</code>```

The impression I get is that I need to write a custom function to take the place of Array.prototype.find(), but I'm not strong in PHP and am having trouble wrapping my head around it.

EDIT: Edited to add example of object being filtered and additional PHP code

答:
This should be equivalent to the JavaScript code you posted, but done without looping through the filtered results twice.

Without knowing the context of important-value and other-important-value, and how they come to be ordered in the $attributes array, it's a little difficult to improve upon the conditional checks used. What I've written thus far however feels like a code smell to me, because it's reliant hard coded values.

```<code>function filterResults(array $results, array $attributes)
{
    return array_reduce($results, function ($filteredResults, $result) use ($attributes) {
        // Extract tag slugs from result
        $tagSlugs = array_column($result['tags'], 'slug');

        // Append result to filtered results where first attribute exists in tag slugs;
        // Or first attribute is not *other-important-value* and fourth attribute exists in tag slugs
        if (in_array($attribute[0], $tagSlugs) && ($attribute[0] === 'other-important-value' || in_array($attribute[4], $tagSlugs))) {
            $filteredResults[] = $result;
        }

        return $filteredResults;
    }, []);
}
</code>```

Body:
I have in the process of moving some code from the front-end (in JavaScript) to the server-side (which is PHP) where it will be filtered and sent out in an API call, and I can't seem to get the filter working properly on the back-end. The code takes an array of objects and filters it for the objects where a certain nested field (which is also an array of objects) contains certain values. The basic shape of the API:

{
  "id": 1217,
  "name": "Best product ever",
  "tags": [
      {
        "id": 125,
        "name": "Important Value",
        "slug": "important-value"
      },
      {
        "id": 157,
        "name": "Value",
        "slug": "value"
      },
      {
    "id": 180,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 126,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 206,
    "name": "Other Important Value",
    "slug": "other-important-value"
  }
}

The working JS code:

let productAttributes = ['important-value', 'value', 'value', 'value', 'other-important-value'];

filterResults(results) {
let filteredResults = results.filter(product => {
  return product.tags.find(tag => {
    return tag.slug === this.productAttributes[0];
  });
});

if (this.productAttributes[0] !== 'certain important value') {
  filteredResults = filteredResults.filter(product => {
    return product.tags.find(tag => {
      return tag.slug === this.productAttributes[4];
    });
  });
}

return filteredResults;
}

And the (not yet working) PHP code:

function get_awesome_products() {
 $baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/?
 consumer_key=xxxx&consumer_secret=xxxx&per_page=100&page=';
 for ($count = 1; $count <= 9; $count++ ) {
$request = wp_remote_get( $baseRequest . (string)$count);
$body = wp_remote_retrieve_body( $request );
$data = array_values( json_decode( $body, true ));

  if ($count < 2) {
    $completeProductList = $data;
  } else {
    $completeProductList = array_merge($completeProductList, $data);
  }
}
// The code above this comment is doing what I expect, the code below is not.

$filteredProducts = null;
foreach ($completeProductList as &$product) {
  $tagArray = $product['tags'];
  if (in_array($reg_test_array[0], $tagArray, true) &&
  in_array($reg_test_array[4], $tagArray, true))
  {
    array_push($filteredProducts, $product);
  }

  unset($product);
  return new WP_REST_Response($filteredProducts, 200);

The impression I get is that I need to write a custom function to take the place of Array.prototype.find(), but I'm not strong in PHP and am having trouble wrapping my head around it.

EDIT: Edited to add example of object being filtered and additional PHP code

Body:
This should be equivalent to the JavaScript code you posted, but done without looping through the filtered results twice.

Without knowing the context of important-value and other-important-value, and how they come to be ordered in the $attributes array, it's a little difficult to improve upon the conditional checks used. What I've written thus far however feels like a code smell to me, because it's reliant hard coded values.

function filterResults(array $results, array $attributes)
{
    return array_reduce($results, function ($filteredResults, $result) use ($attributes) {
        // Extract tag slugs from result
        $tagSlugs = array_column($result['tags'], 'slug');

        // Append result to filtered results where first attribute exists in tag slugs;
        // Or first attribute is not *other-important-value* and fourth attribute exists in tag slugs
        if (in_array($attribute[0], $tagSlugs) && ($attribute[0] === 'other-important-value' || in_array($attribute[4], $tagSlugs))) {
            $filteredResults[] = $result;
        }

        return $filteredResults;
    }, []);
}


问:
Download remote file using laravel
I've a link that gets the image, but the image has been removed, renamed or moved to another place

```<code>public function index()
{
    $array = [
         { image:'https://imgimob.sobressai.com.br/fotos/765/475139/12768822_g.jpg' },
         { image:'http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg' }
    ]
    for ($i = 0; $i < count($array); $i++) {
       if(!$contents = file_get_contents($array[$i]['image']))
       {
             return 'Not found!';
       else {
        Storage::disk('public')->put('default/teste.jpg', $contents);
       }
   }
}
</code>```

if the image no exist then I get this error

file_get_contents(http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

I would link get to return "doesnt' exist" and download file if it does.

答:
If you are certain that the file does exist, then this is a permission issue. Check the file's owner and mode are the ones you expect. (edited)

Also, make sure that your PHP is configured with allow-url-fopen enabled. This will authorize PHP to open remote files. Read more at https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

Title: Download remote file using laravel

Body:
I've a link that gets the image, but the image has been removed, renamed or moved to another place

public function index()
{
    $array = [
         { image:'https://imgimob.sobressai.com.br/fotos/765/475139/12768822_g.jpg' },
         { image:'http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg' }
    ]
    for ($i = 0; $i < count($array); $i++) {
       if(!$contents = file_get_contents($array[$i]['image']))
       {
             return 'Not found!';
       else {
        Storage::disk('public')->put('default/teste.jpg', $contents);
       }
   }
}

if the image no exist then I get this error

file_get_contents(http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

I would link get to return "doesnt' exist" and download file if it does.


问:
How to make condition dependent on trade execution
I want to make my script dependent on the strategy.entry being executed. Do anyone know how?

My code:

```<code>buy = crossover(delta, 0)

milliseconds_in_xdays = 1000 * 60 * 60 * 24 * 15

lastTrade = na
closetrd = time >= (lastTrade[15] + milliseconds_in_xdays)

if (buy)
    strategy.entry("Long", strategy.long, comment="Long")
    ***if( strategy.long = true)*** NEED HELP HERE
        lastTrade := time

if (closetrd)
    strategy.close("Long")
    lastTrade := na
</code>```

As you can see in my first if i'm setting the time and trying to close the trade after 15 days pass. I want the time to be set only if my "long" strategy is entered. Right now it is closing trades 15 days after any buy condition is met. I don't want this because my pyramiding is off.

Any ideas?

答:
Use:

```<code>barssince(change(strategy.position_size) > 0) == 15
</code>```

as a condition.

Body:
I want to make my script dependent on the strategy.entry being executed. Do anyone know how?

My code:

buy = crossover(delta, 0)

milliseconds_in_xdays = 1000 * 60 * 60 * 24 * 15

lastTrade = na
closetrd = time >= (lastTrade[15] + milliseconds_in_xdays)

if (buy)
    strategy.entry("Long", strategy.long, comment="Long")
    ***if( strategy.long = true)*** NEED HELP HERE
        lastTrade := time

if (closetrd)
    strategy.close("Long")
    lastTrade := na

As you can see in my first if i'm setting the time and trying to close the trade after 15 days pass. I want the time to be set only if my "long" strategy is entered. Right now it is closing trades 15 days after any buy condition is met. I don't want this because my pyramiding is off.

Any ideas?

Body:
Use:

barssince(change(strategy.position_size) > 0) == 15

as a condition.


问:
Docker Error bind: address already in use
When I run docker-compose up in my Docker project it fails with the following message:

Error starting userland proxy: listen tcp 0.0.0.0:3000: bind: address already in use

```<code>netstat -pna | grep 3000
</code>```

shows this:

```<code>tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      -
</code>```

I've already tried docker-compose down, but it doesn't help.

答:
A variation of @DmitrySandalov's answer: I had tomcat/java running on 8080, which needed to keep going. Looked at the docker-compose.yml file and altered the entry for 8080 to another of my choosing.

```<code>nginx:
  build: nginx
  ports:
    #- '8080:80' <-- original entry
    - '8880:80'
    - '8443:443'
</code>```

Worked perfectly. (The only wrinkle is the change will be wiped if I ever update the project, since it's coming from an external repo.)

Body:
When I run docker-compose up in my Docker project it fails with the following message:

Error starting userland proxy: listen tcp 0.0.0.0:3000: bind: address already in use

netstat -pna | grep 3000

shows this:

tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      -

I've already tried docker-compose down, but it doesn't help.

Body:
A variation of @DmitrySandalov's answer: I had tomcat/java running on 8080, which needed to keep going. Looked at the docker-compose.yml file and altered the entry for 8080 to another of my choosing.

nginx:
  build: nginx
  ports:
    #- '8080:80' <-- original entry
    - '8880:80'
    - '8443:443'

Worked perfectly. (The only wrinkle is the change will be wiped if I ever update the project, since it's coming from an external repo.)


问:
useState on React Hooks not updating Array
I have tried many things and can't seem to understand why setTypes won't update the 'types' array??

```<code>import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);

  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined

  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (
    <div className="filter">
      <label htmlFor="options">Post Type: </label>
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>
    </div>
  );
}
</code>```

Please, take a look at the console.log and notice the different responses.

What I am trying to do is to load list of types, in this case 'post', 'page' and 'case' and then render a list of posts based on the current 'type'. The default type is 'post'.

If I add [types] to useEffect. I finally get the values but the component renders nonstop.

Thanks to everyone for your comments. Multiple people have pointed out the problem, being that, the fact that we set the state doesn't mean it will set right away because it it asynchronous.

How do we solve this problem then? Regardless of the reasons, how do we get it done? How do we work with our state at any point in time and perform calculations based on our state if we don't know when it will become available? How do we make sure we wait whatever we need to and then use the values we expect?

答:
You have declared your types to be an array, yet you are passing a dictionary of dictionaries through to it.
Try this:

```<code>const [types, setTypes]     = useState({});
</code>```

You also do not need to call

```<code>loadPosts()
</code>```

becuase the useState hook will re-render your component, only updating what is needed.

Body:
I have tried many things and can't seem to understand why setTypes won't update the 'types' array??

import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);

  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined

  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (

      Post Type:
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>

  );
}

Please, take a look at the console.log and notice the different responses.

What I am trying to do is to load list of types, in this case 'post', 'page' and 'case' and then render a list of posts based on the current 'type'. The default type is 'post'.

If I add [types] to useEffect. I finally get the values but the component renders nonstop.

Thanks to everyone for your comments. Multiple people have pointed out the problem, being that, the fact that we set the state doesn't mean it will set right away because it it asynchronous.

How do we solve this problem then? Regardless of the reasons, how do we get it done? How do we work with our state at any point in time and perform calculations based on our state if we don't know when it will become available? How do we make sure we wait whatever we need to and then use the values we expect?

Body:
You have declared your types to be an array, yet you are passing a dictionary of dictionaries through to it.
Try this:

const [types, setTypes]     = useState({});

You also do not need to call

loadPosts()

becuase the useState hook will re-render your component, only updating what is needed.


问:
Customising the floating button to show in one tab
I would like to show my floating button in one Tab, how can I overcome that?

答:
As @francesco-galgani wrote this is indeed the case. Instead of doing:

```<code>tabs.add("Tab Name", myContainer);
</code>```

Do:

```<code>Container withFab = FloatingActionButton.bindFabToContainer(myContainer);
tabs.add("Tab Name", withFab);
</code>```

Notice we now need to add the withFab container.

Body:
As @francesco-galgani wrote this is indeed the case. Instead of doing:

tabs.add("Tab Name", myContainer);

Do:

Container withFab = FloatingActionButton.bindFabToContainer(myContainer);
tabs.add("Tab Name", withFab);

Notice we now need to add the withFab container.