问:
Continue a nested loop after exception
I have a nested loop to get certain JSON elements the way I want, but occasionally, the API I'm fetching from gets messy and it breaks some of the fields - I am not exactly sure how to handle this since It seems to be different each time, so I'm wondering if there is a way to continue a nested for loop even if an exception occurs inside it, or at least go back to the first loop and continue again.

My code is like this:

```<code> fields = ['email', 'displayname', 'login']
    sub_fields = ['level', 'name']

    all_data = []
    for d in data:
        login_value = d['login']
        if login_value.startswith('3b3'):
            continue
        student = fetched_student.student_data(login_value)
        student = json.loads(student)
        final_json = dict()
        try:
            for field in fields:
                #print ("Student field here: %s" % student[field])
                final_json[field] = student[field]
        except Exception as e:
            print (e) # this is where I get a random KeyValue Error
            #print ("Something happening here: %s " % final_json[field])
        finally:
            for sub_field in sub_fields:
                for element in student['users']:
                    if element.get(sub_field):
                        final_json[sub_field] = element.get(sub_field)
                for element in student['campus']:
                    if element.get(sub_field):
                        final_json[sub_field] = element.get(sub_field)
        all_data.append(final_json)
        print (all_data)
</code>```

Is there a way to just go back to the first try block and continue after the exception has occurred or simply just ignore it and continue?
Because as things are now, if the exception ever occurs it breaks everything.

EDIT1: I have tried putting continue like so:

```<code>try:
    for field in fields:
        #print ("Student field here: %s" % student[field])
        final_json[field] = student[field]
except Exception as e:
    print (e)
    continue
    for sub_field in sub_fields:
        for element in student['users']:
</code>```

But it still fails regardless.

答:
Possibly you can use dict's get method like this in your try block:

try:
    for field in fields:
        #print ("Student field here: %s" % student[field])
        final_json[field] = student.get(field, "") # 2nd arg is fallback object
```

Depending on what is needed, you can pass in an fresh dict (aka JSON object), fresh list (aka JSON array), or a str like above to suit your downstream needs.

Title: Continue a nested loop after exception

Body:
I have a nested loop to get certain JSON elements the way I want, but occasionally, the API I'm fetching from gets messy and it breaks some of the fields - I am not exactly sure how to handle this since It seems to be different each time, so I'm wondering if there is a way to continue a nested for loop even if an exception occurs inside it, or at least go back to the first loop and continue again.

My code is like this:

 fields = ['email', 'displayname', 'login']
    sub_fields = ['level', 'name']

    all_data = []
    for d in data:
        login_value = d['login']
        if login_value.startswith('3b3'):
            continue
        student = fetched_student.student_data(login_value)
        student = json.loads(student)
        final_json = dict()
        try:
            for field in fields:
                #print ("Student field here: %s" % student[field])
                final_json[field] = student[field]
        except Exception as e:
            print (e) # this is where I get a random KeyValue Error
            #print ("Something happening here: %s " % final_json[field])
        finally:
            for sub_field in sub_fields:
                for element in student['users']:
                    if element.get(sub_field):
                        final_json[sub_field] = element.get(sub_field)
                for element in student['campus']:
                    if element.get(sub_field):
                        final_json[sub_field] = element.get(sub_field)
        all_data.append(final_json)
        print (all_data)

Is there a way to just go back to the first try block and continue after the exception has occurred or simply just ignore it and continue?
Because as things are now, if the exception ever occurs it breaks everything.

EDIT1: I have tried putting continue like so:

try:
    for field in fields:
        #print ("Student field here: %s" % student[field])
        final_json[field] = student[field]
except Exception as e:
    print (e)
    continue
    for sub_field in sub_fields:
        for element in student['users']:

But it still fails regardless.

Body:
Possibly you can use dict's get method like this in your try block:

try:
    for field in fields:
        #print ("Student field here: %s" % student[field])
        final_json[field] = student.get(field, "") # 2nd arg is fallback object

Depending on what is needed, you can pass in an fresh dict (aka JSON object), fresh list (aka JSON array), or a str like above to suit your downstream needs.


来源: stackexchange

答:
Use this for the try block:

```<code>for field in fields:
   try:
       #print ("Student field here: %s" % student[field])
       final_json[field] = student[field]
    except Exception as e:
        print (e)
        continue
for sub_field in sub_fields:
    for element in student['users']:
</code>```

The issue is due to the indentation level of the try block, the continue was affecting the outer most loop. Changing the try block to be inside of the loop will catch the error in that loop and continue the iteration of that specific loop.

ContentLicense: CC BY-SA 4.0

Title: Continue a nested loop after exception

Body:
Use this for the try block:

for field in fields:
   try:
       #print ("Student field here: %s" % student[field])
       final_json[field] = student[field]
    except Exception as e:
        print (e)
        continue
for sub_field in sub_fields:
    for element in student['users']:

The issue is due to the indentation level of the try block, the continue was affecting the outer most loop. Changing the try block to be inside of the loop will catch the error in that loop and continue the iteration of that specific loop.


问:
NOT HAVING (inverse HAVING) clause with aggregation in Oracle
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

```<code>SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]
</code>```

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

答:
This is the same as Michael Broughton's answer and I hate to duplicate but I thought it could be clearer.  If he wants to incorporate any of this into his answer, I'm happy to delete this one.

To determine the logical equivalent of NOT (boolean_expression), you can apply De Morgan's laws.  See: https://en.wikipedia.org/wiki/De_Morgan%27s_laws

Basically, you reverse the logic of each term and change all ANDs to ORs and all ORs to ANDs.  So,

```<code>NOT (A AND B AND C) ==> (NOT A OR NOT B OR NOT C)
</code>```

But you need to keep track of nulls too.  Here's the process:

Starting with...

```<code>HAVING NOT (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
</code>```

First, add the implicit assumptions about NULLs that exist in the starting expression.  E.g., if flag_1=1, then it is, of course, not NULL.

```<code>HAVING NOT (flag_1 = 1 AND flag_1 IS NOT NULL
        AND flag_2 = 1 AND flag_2 IS NOT NULL
        AND flag_3 = 1 AND flag_3 IS NOT NULL)
</code>```

Now, apply the first part of De Morgan's laws and reverse the logic of each term.  So, e,g., flag_1 = 1 becomes flag_1 != 1...

```<code>HAVING (flag_1 != 1 AND flag_1 IS NULL
    AND flag_2 != 1 AND flag_2 IS NULL
    AND flag_3 != 1 AND flag_3 IS NULL)
</code>```

Finally, apply the second part of De Morgan's laws and switch all ANDs->ORs and vice versa...

```<code>HAVING (flag_1 != 1 OR flag_1 IS NULL
     OR flag_2 != 1 OR flag_2 IS NULL
     OR flag_3 != 1 OR flag_3 IS NULL)
</code>```

And there is your answer.

How about just NOT (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)?

This does not work because it does not handle null values as one would expect.  In Oracle, any comparison with null is false.  So,

```<code>    (1 = NULL) ... false
NOT (1 = NULL) ... also false
</code>```

So a row with flag_1 and flag_2 both equal to 1 but flag_3 null would NOT show up in your results.

Body:
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

Body:
This is the same as Michael Broughton's answer and I hate to duplicate but I thought it could be clearer.  If he wants to incorporate any of this into his answer, I'm happy to delete this one.

To determine the logical equivalent of NOT (boolean_expression), you can apply De Morgan's laws.  See: https://en.wikipedia.org/wiki/De_Morgan%27s_laws

Basically, you reverse the logic of each term and change all ANDs to ORs and all ORs to ANDs.  So,

NOT (A AND B AND C) ==> (NOT A OR NOT B OR NOT C)

But you need to keep track of nulls too.  Here's the process:

Starting with...

HAVING NOT (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)

First, add the implicit assumptions about NULLs that exist in the starting expression.  E.g., if flag_1=1, then it is, of course, not NULL.

HAVING NOT (flag_1 = 1 AND flag_1 IS NOT NULL
        AND flag_2 = 1 AND flag_2 IS NOT NULL
        AND flag_3 = 1 AND flag_3 IS NOT NULL)

Now, apply the first part of De Morgan's laws and reverse the logic of each term.  So, e,g., flag_1 = 1 becomes flag_1 != 1...

HAVING (flag_1 != 1 AND flag_1 IS NULL
    AND flag_2 != 1 AND flag_2 IS NULL
    AND flag_3 != 1 AND flag_3 IS NULL)

Finally, apply the second part of De Morgan's laws and switch all ANDs->ORs and vice versa...

HAVING (flag_1 != 1 OR flag_1 IS NULL
     OR flag_2 != 1 OR flag_2 IS NULL
     OR flag_3 != 1 OR flag_3 IS NULL)

And there is your answer.

How about just NOT (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)?

This does not work because it does not handle null values as one would expect.  In Oracle, any comparison with null is false.  So,

    (1 = NULL) ... false
NOT (1 = NULL) ... also false

So a row with flag_1 and flag_2 both equal to 1 but flag_3 null would NOT show up in your results.


问:
LINQ, Join, GroupBy and Count
I have this vb.net LINQ query. Without the join the count and SUM worked perfectly on each. But with the join the count and SUM arent working properly due to the multiple CAMPAIGNID values. I suspect I need another group by statement in there but I am not entirely sure how to do that. IF you could help that would be great.</p>

```<code>Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group
    Select New With {
        .id = CAMPAIGNID,
        .CALLS = Group.Sum(Function(a) a.t2.CALLS),
        .count = Group.Count(Function(a) a.t1.TERMCD = "Refused")
    }
</code>```

答:
I have made an example which seems to be working properly.

Public Class T1
    Public Property CAMPAIGNID As Integer
    Public Property TERMCD As String
End Class

Public Class T2
    Public Property CAMPAIGNID As Integer
    Public Property CALLS As Integer
End Class
```

<pre class="lang-vb prettyprint-override"><code>Dim tbl1 As New List(Of T1) From {
    New T1 With {.CAMPAIGNID = 1, .TERMCD = "Refused"},
    New T1 With {.CAMPAIGNID = 1, .TERMCD = "Accepted"},
    New T1 With {.CAMPAIGNID = 2, .TERMCD = "Refused"},
    New T1 With {.CAMPAIGNID = 2, .TERMCD = "Accepted"},
    New T1 With {.CAMPAIGNID = 3, .TERMCD = "Refused"},
    New T1 With {.CAMPAIGNID = 3, .TERMCD = "Accepted"}
}
Dim tbl2 As New List(Of T2) From {
    New T2 With {.CAMPAIGNID = 1, .CALLS = 2},
    New T2 With {.CAMPAIGNID = 1, .CALLS = 4},
    New T2 With {.CAMPAIGNID = 2, .CALLS = 8},
    New T2 With {.CAMPAIGNID = 2, .CALLS = 16},
    New T2 With {.CAMPAIGNID = 3, .CALLS = 32},
    New T2 With {.CAMPAIGNID = 3, .CALLS = 64}
}

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group
    Select New With {
        .id = CAMPAIGNID,
        .CALLS = Group.Sum(Function(a) a.t2.CALLS),
        .count = Group.Count(Function(a) a.t1.TERMCD = "Refused")
    }

For Each q In query
    Console.WriteLine($"ID:{q.id}, CALLS:{q.CALLS}, COUNT:{q.count}")
Next
</code>```

ID:1, CALLS:12, COUNT:2

  ID:2, CALLS:48, COUNT:2

  ID:3, CALLS:192, COUNT:2

In the case of ID 3, the CALLS sum of 192 is correct because the sum has no constraint of TERMCD = "Refused", so it counts all. And the count of 2 is accurate because has a constraint where TERMCD = "Refused".

Just looking at the group, without aggregation, let's see what is returned

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group

For Each q In query
    Console.WriteLine($"ID:{q.CAMPAIGNID}")
    For Each g In q.Group
        Console.WriteLine($"t1.CAMPAIGNID:{g.t1.CAMPAIGNID}, t1.TERMCD:{g.t1.TERMCD}, t2.CAMPAIGNID:{g.t2.CAMPAIGNID}, t2.CALLS:{g.t2.CALLS}")
    Next
Next
```

<blockquote>
  <p>ID:1<br>
  t1.CAMPAIGNID:1, t1.TERMCD:Refused, t2.CAMPAIGNID:1, t2.CALLS:2<br>
  t1.CAMPAIGNID:1, t1.TERMCD:Refused, t2.CAMPAIGNID:1, t2.CALLS:4<br>
  t1.CAMPAIGNID:1, t1.TERMCD:Accepted, t2.CAMPAIGNID:1, t2.CALLS:2<br>
  t1.CAMPAIGNID:1, t1.TERMCD:Accepted, t2.CAMPAIGNID:1, t2.CALLS:4<br>
  ID:2<br>
  t1.CAMPAIGNID:2, t1.TERMCD:Refused, t2.CAMPAIGNID:2, t2.CALLS:8<br>
  t1.CAMPAIGNID:2, t1.TERMCD:Refused, t2.CAMPAIGNID:2, t2.CALLS:16<br>
  t1.CAMPAIGNID:2, t1.TERMCD:Accepted, t2.CAMPAIGNID:2, t2.CALLS:8<br>
  t1.CAMPAIGNID:2, t1.TERMCD:Accepted, t2.CAMPAIGNID:2, t2.CALLS:16<br>
  ID:3<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:32<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:64<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:32<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:64</p>
</blockquote>

<p>Now it should be clear why you see what you see.</p>

<p>Sum with no constraint: </p>

<blockquote>
  <p>t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:32<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:64<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:32<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:64</p>
</blockquote>

<p>Count where <code>a.t1.TERMCD = "Refused"</code></p>

<blockquote>
  <p>t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:32<br>
  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:64  </p>
</blockquote>

<p>I'm not sure what you <em>want</em> to see, but this should at least show you that your output is accurate.</p>

<p>Now that we got that out of the way, your SQL query is below</p>

<pre class="lang-sql prettyprint-override"><code>SELECT DISTINCT A.CAMPAIGNID
              , RFJOIN.RF
              , CCJOIN.CC
              , CALLSJOIN.CALLS
              , CALLSJOIN.CALLS / RFJOIN.RF as Calculated
FROM tbl1 A
inner join (SELECT CAMPAIGNID
                 , count() as RF
            FROM tbl1
            WHERE TERMCD='Refused'
            GROUP by CAMPAIGNID) RFJOIN on RFJOIN.CAMPAIGNID = a.CAMPAIGNID
inner join (SELECT CAMPAIGNID
                 , count() as CC
            FROM tbl1
            WHERE TERMCD LIKE '%Con%'
            GROUP by CAMPAIGNID) CCJOIN on CCJOIN.CAMPAIGNID = a.CAMPAIGNID
inner join (SELECT CAMPAIGNID
                 , SUM(CALLS) as CALLS
            FROM tbl2
            GROUP by CAMPAIGNID) CALLSJOIN on CALLSJOIN.CAMPAIGNID = a.CAMPAIGNID
</code>```

I would break it into the subqueries then join them together. You can almost copy the SQL syntax this way

Dim RFJ = From t1 In tbl1
          Where t1.TERMCD = "Refused"
          Group By t1.CAMPAIGNID Into Group
          Select New With {CAMPAIGNID, .RF = Group.Count()}
Dim CCJ = From t1 In tbl1
          Where t1.TERMCD.Contains("Con")
          Group By t1.CAMPAIGNID Into Group
          Select New With {CAMPAIGNID, .CC = Group.Count()}
Dim CAJ = From t2 In tbl2
          Group By t2.CAMPAIGNID Into Group
          Select New With {CAMPAIGNID, .CALLS = Group.Count()}
Dim query = From A In tbl1
            Join RFJOIN In RFJ On RFJOIN.CAMPAIGNID Equals A.CAMPAIGNID
            Join CCJOIN In CCJ On CCJOIN.CAMPAIGNID Equals A.CAMPAIGNID
            Join CALLSJOIN In CAJ On CALLSJOIN.CAMPAIGNID Equals A.CAMPAIGNID
            Select New With {A.CAMPAIGNID, RFJOIN.RF, CCJOIN.CC, CALLSJOIN.CALLS, .Calculated = CALLSJOIN.CALLS / RFJOIN.RF}
Dim queryDistinct = query.Distinct()

' or in one big ugly query :)

Dim fullQuery = (From A In tbl1
                 Join RFJOIN In From t1 In tbl1
                                Where t1.TERMCD = "Refused"
                                Group By t1.CAMPAIGNID Into Group
                                Select New With {CAMPAIGNID, .RF = Group.Count()} On RFJOIN.CAMPAIGNID Equals A.CAMPAIGNID
                 Join CCJOIN In From t1 In tbl1
                                Where t1.TERMCD.Contains("Con")
                                Group By t1.CAMPAIGNID Into Group
                                Select New With {CAMPAIGNID, .CC = Group.Count()} On CCJOIN.CAMPAIGNID Equals A.CAMPAIGNID
                 Join CALLSJOIN In From t2 In tbl2
                                   Group By t2.CAMPAIGNID Into Group
                                   Select New With {CAMPAIGNID, .CALLS = Group.Count()} On CALLSJOIN.CAMPAIGNID Equals A.CAMPAIGNID
                 Select New With {A.CAMPAIGNID, RFJOIN.RF, CCJOIN.CC, CALLSJOIN.CALLS, .Calculated = CALLSJOIN.CALLS / RFJOIN.RF}).Distinct()
```

Title: LINQ, Join, GroupBy and Count

Body:
I have this vb.net LINQ query. Without the join the count and SUM worked perfectly on each. But with the join the count and SUM arent working properly due to the multiple CAMPAIGNID values. I suspect I need another group by statement in there but I am not entirely sure how to do that. IF you could help that would be great.

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group
    Select New With {
        .id = CAMPAIGNID,
        .CALLS = Group.Sum(Function(a) a.t2.CALLS),
        .count = Group.Count(Function(a) a.t1.TERMCD = "Refused")
    }

Body:
I have made an example which seems to be working properly.

Public Class T1
    Public Property CAMPAIGNID As Integer
    Public Property TERMCD As String
End Class

Public Class T2
    Public Property CAMPAIGNID As Integer
    Public Property CALLS As Integer
End Class

Dim tbl1 As New List(Of T1) From {
    New T1 With {.CAMPAIGNID = 1, .TERMCD = "Refused"},
    New T1 With {.CAMPAIGNID = 1, .TERMCD = "Accepted"},
    New T1 With {.CAMPAIGNID = 2, .TERMCD = "Refused"},
    New T1 With {.CAMPAIGNID = 2, .TERMCD = "Accepted"},
    New T1 With {.CAMPAIGNID = 3, .TERMCD = "Refused"},
    New T1 With {.CAMPAIGNID = 3, .TERMCD = "Accepted"}
}
Dim tbl2 As New List(Of T2) From {
    New T2 With {.CAMPAIGNID = 1, .CALLS = 2},
    New T2 With {.CAMPAIGNID = 1, .CALLS = 4},
    New T2 With {.CAMPAIGNID = 2, .CALLS = 8},
    New T2 With {.CAMPAIGNID = 2, .CALLS = 16},
    New T2 With {.CAMPAIGNID = 3, .CALLS = 32},
    New T2 With {.CAMPAIGNID = 3, .CALLS = 64}
}

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group
    Select New With {
        .id = CAMPAIGNID,
        .CALLS = Group.Sum(Function(a) a.t2.CALLS),
        .count = Group.Count(Function(a) a.t1.TERMCD = "Refused")
    }

For Each q In query
    Console.WriteLine($"ID:{q.id}, CALLS:{q.CALLS}, COUNT:{q.count}")
Next

ID:1, CALLS:12, COUNT:2

  ID:2, CALLS:48, COUNT:2

  ID:3, CALLS:192, COUNT:2

In the case of ID 3, the CALLS sum of 192 is correct because the sum has no constraint of TERMCD = "Refused", so it counts all. And the count of 2 is accurate because has a constraint where TERMCD = "Refused".

Just looking at the group, without aggregation, let's see what is returned

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group

For Each q In query
    Console.WriteLine($"ID:{q.CAMPAIGNID}")
    For Each g In q.Group
        Console.WriteLine($"t1.CAMPAIGNID:{g.t1.CAMPAIGNID}, t1.TERMCD:{g.t1.TERMCD}, t2.CAMPAIGNID:{g.t2.CAMPAIGNID}, t2.CALLS:{g.t2.CALLS}")
    Next
Next

ID:1

  t1.CAMPAIGNID:1, t1.TERMCD:Refused, t2.CAMPAIGNID:1, t2.CALLS:2

  t1.CAMPAIGNID:1, t1.TERMCD:Refused, t2.CAMPAIGNID:1, t2.CALLS:4

  t1.CAMPAIGNID:1, t1.TERMCD:Accepted, t2.CAMPAIGNID:1, t2.CALLS:2

  t1.CAMPAIGNID:1, t1.TERMCD:Accepted, t2.CAMPAIGNID:1, t2.CALLS:4

  ID:2

  t1.CAMPAIGNID:2, t1.TERMCD:Refused, t2.CAMPAIGNID:2, t2.CALLS:8

  t1.CAMPAIGNID:2, t1.TERMCD:Refused, t2.CAMPAIGNID:2, t2.CALLS:16

  t1.CAMPAIGNID:2, t1.TERMCD:Accepted, t2.CAMPAIGNID:2, t2.CALLS:8

  t1.CAMPAIGNID:2, t1.TERMCD:Accepted, t2.CAMPAIGNID:2, t2.CALLS:16

  ID:3

  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:32

  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:64

  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:32

  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:64

Now it should be clear why you see what you see.

Sum with no constraint:

t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:32

  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:64

  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:32

  t1.CAMPAIGNID:3, t1.TERMCD:Accepted, t2.CAMPAIGNID:3, t2.CALLS:64

Count where a.t1.TERMCD = "Refused"

t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:32

  t1.CAMPAIGNID:3, t1.TERMCD:Refused, t2.CAMPAIGNID:3, t2.CALLS:64

I'm not sure what you want to see, but this should at least show you that your output is accurate.

Now that we got that out of the way, your SQL query is below

SELECT DISTINCT A.CAMPAIGNID
              , RFJOIN.RF
              , CCJOIN.CC
              , CALLSJOIN.CALLS
              , CALLSJOIN.CALLS / RFJOIN.RF as Calculated
FROM tbl1 A
inner join (SELECT CAMPAIGNID
                 , count() as RF
            FROM tbl1
            WHERE TERMCD='Refused'
            GROUP by CAMPAIGNID) RFJOIN on RFJOIN.CAMPAIGNID = a.CAMPAIGNID
inner join (SELECT CAMPAIGNID
                 , count() as CC
            FROM tbl1
            WHERE TERMCD LIKE '%Con%'
            GROUP by CAMPAIGNID) CCJOIN on CCJOIN.CAMPAIGNID = a.CAMPAIGNID
inner join (SELECT CAMPAIGNID
                 , SUM(CALLS) as CALLS
            FROM tbl2
            GROUP by CAMPAIGNID) CALLSJOIN on CALLSJOIN.CAMPAIGNID = a.CAMPAIGNID

I would break it into the subqueries then join them together. You can almost copy the SQL syntax this way

Dim RFJ = From t1 In tbl1
          Where t1.TERMCD = "Refused"
          Group By t1.CAMPAIGNID Into Group
          Select New With {CAMPAIGNID, .RF = Group.Count()}
Dim CCJ = From t1 In tbl1
          Where t1.TERMCD.Contains("Con")
          Group By t1.CAMPAIGNID Into Group
          Select New With {CAMPAIGNID, .CC = Group.Count()}
Dim CAJ = From t2 In tbl2
          Group By t2.CAMPAIGNID Into Group
          Select New With {CAMPAIGNID, .CALLS = Group.Count()}
Dim query = From A In tbl1
            Join RFJOIN In RFJ On RFJOIN.CAMPAIGNID Equals A.CAMPAIGNID
            Join CCJOIN In CCJ On CCJOIN.CAMPAIGNID Equals A.CAMPAIGNID
            Join CALLSJOIN In CAJ On CALLSJOIN.CAMPAIGNID Equals A.CAMPAIGNID
            Select New With {A.CAMPAIGNID, RFJOIN.RF, CCJOIN.CC, CALLSJOIN.CALLS, .Calculated = CALLSJOIN.CALLS / RFJOIN.RF}
Dim queryDistinct = query.Distinct()

' or in one big ugly query :)

Dim fullQuery = (From A In tbl1
                 Join RFJOIN In From t1 In tbl1
                                Where t1.TERMCD = "Refused"
                                Group By t1.CAMPAIGNID Into Group
                                Select New With {CAMPAIGNID, .RF = Group.Count()} On RFJOIN.CAMPAIGNID Equals A.CAMPAIGNID
                 Join CCJOIN In From t1 In tbl1
                                Where t1.TERMCD.Contains("Con")
                                Group By t1.CAMPAIGNID Into Group
                                Select New With {CAMPAIGNID, .CC = Group.Count()} On CCJOIN.CAMPAIGNID Equals A.CAMPAIGNID
                 Join CALLSJOIN In From t2 In tbl2
                                   Group By t2.CAMPAIGNID Into Group
                                   Select New With {CAMPAIGNID, .CALLS = Group.Count()} On CALLSJOIN.CAMPAIGNID Equals A.CAMPAIGNID
                 Select New With {A.CAMPAIGNID, RFJOIN.RF, CCJOIN.CC, CALLSJOIN.CALLS, .Calculated = CALLSJOIN.CALLS / RFJOIN.RF}).Distinct()


问:
Unable to create a role when using ACCOUNTADMIN or SYSADMIN in Snowflake
I am getting the error "SQL access control error: Insufficient privileges to operate on account 'XXXXXX'" when I try to create a role in Snowflake in order to get it connected to Segment.

I am following the Segment documentation here: https://segment.com/docs/connections/warehouses/catalog/snowflake/

And I am getting stuck when I run the command "CREATE ROLE "SEGMENT";"

Any help in how to get around this would be great. I am currently on the trial and was able to successfully create the data warehouse and database as per the segment instructions.

答:
Thanks to Greg in the comments:
"An easy way to remember it is that the upper right role is for UI actions, while the lower one sets the context for the worksheet"

1) while I had the correct profile up here

2) once I clicked this

3) I did not have the right profile in here

After switching to ACCOUNTADMIN in 3) I was able to create the role.

screenshot of how I fixed it


问:
how to create or update multiple tables using Sequelize?
I'm working on developing back-end with DB using Sequelize ORM. I need to create data into multiple tables or update data into multiple tables. but I'm not sure how to do this. those are example of mine below:

```<code>//Tables
const main = sequelize.define('main', {
id: {type: Sequelize.STRING, primaryKey: true},
column1: Sequelize.STRING,
column2: Sequelize.STRING,
column3: Sequelize.STRING,
}, {
tableName: 'main'
});

const table1 = sequelize.define('table1', {
column1: Sequelize.STRING,
column2: Sequelize.STRING,
column3: Sequelize.STRING,
mainId: Sequelize.STRING,
}, {
tableName: 'table1'
});

const table2 = sequelize.define('table1', {
column1: Sequelize.STRING,
column2: Sequelize.STRING,
column3: Sequelize.STRING,
mainId: Sequelize.STRING,
}, {
tableName: 'table2'
});

//relation with tables
table1.belongsTo(MAIN, {foreignKey: 'mainId'});
MAIN.hasMany(table1, {foreignKey: 'mainId'});
table2.belongsTo(MAIN, {foreignKey: 'mainId'});
MAIN.hasMany(table2, {foreignKey: 'mainId'});
table3.belongsTo(MAIN, {foreignKey: 'mainId'});
MAIN.hasMany(table3, {foreignKey: 'mainId'});

//Input Body(JSON)
{
"id": "MAIN0001",
"column1": "string",
"column1": "string",
"column3": "string",
"table1": {
  "column1": "string",
  "column2": "string",
  "column3": "string",
  "mainId": "MAIN0001",
  },
"table1": {
  "column1": "string",
  "column2": "string",
  "column3": "string",
  "mainId": "MAIN0001",
  },
"table2": {
  "column1": "string",
  "column2": "string",
  "column3": "string"
  "mainId": "MAIN0001",
  }
}
</code>```

That's all example of what I'm gonna do.
Plz let me know how can I do this.

Thxs in advance :D

答:
There a quite a few ways. Here are a few

Using transactions

```<code>try {

  const result = await sequelize.transaction(async (t) => {

    const createdMain = await main1.create({
      column1: 'string',
      column2: 'string',
      column3: 'string',
    }, { transaction: t });

    const createdTable1 = await table1.create({
      column1: 'string',
      column2: 'string',
      column3: 'string',
      mainId: createdMain.id
    }, { transaction: t });

    return {
      ...createdMain,
     table1: createdTable1,
    };
  });

} catch (error) {

  // If the execution reaches this line, an error occurred.
  // The transaction has already been rolled back automatically by Sequelize!

}
</code>```

Creating main and table1 in one step:

```<code>return main1.create({
   column1: 'string',
   column2: 'string',
   column3: 'string',
   table1: {
     column1: 'string',
     column2: 'string',
     column3: 'string',
   },
   // Repeat for table 2 and table 3
}, {
    include: [ table1 ]
  // Include table 2 and table 3
  }]
});
</code>```

Body:
I'm working on developing back-end with DB using Sequelize ORM. I need to create data into multiple tables or update data into multiple tables. but I'm not sure how to do this. those are example of mine below:

//Tables
const main = sequelize.define('main', {
id: {type: Sequelize.STRING, primaryKey: true},
column1: Sequelize.STRING,
column2: Sequelize.STRING,
column3: Sequelize.STRING,
}, {
tableName: 'main'
});

const table1 = sequelize.define('table1', {
column1: Sequelize.STRING,
column2: Sequelize.STRING,
column3: Sequelize.STRING,
mainId: Sequelize.STRING,
}, {
tableName: 'table1'
});

const table2 = sequelize.define('table1', {
column1: Sequelize.STRING,
column2: Sequelize.STRING,
column3: Sequelize.STRING,
mainId: Sequelize.STRING,
}, {
tableName: 'table2'
});

//relation with tables
table1.belongsTo(MAIN, {foreignKey: 'mainId'});
MAIN.hasMany(table1, {foreignKey: 'mainId'});
table2.belongsTo(MAIN, {foreignKey: 'mainId'});
MAIN.hasMany(table2, {foreignKey: 'mainId'});
table3.belongsTo(MAIN, {foreignKey: 'mainId'});
MAIN.hasMany(table3, {foreignKey: 'mainId'});

//Input Body(JSON)
{
"id": "MAIN0001",
"column1": "string",
"column1": "string",
"column3": "string",
"table1": {
  "column1": "string",
  "column2": "string",
  "column3": "string",
  "mainId": "MAIN0001",
  },
"table1": {
  "column1": "string",
  "column2": "string",
  "column3": "string",
  "mainId": "MAIN0001",
  },
"table2": {
  "column1": "string",
  "column2": "string",
  "column3": "string"
  "mainId": "MAIN0001",
  }
}

That's all example of what I'm gonna do.
Plz let me know how can I do this.

Thxs in advance :D

Body:
There a quite a few ways. Here are a few

Using transactions

try {

  const result = await sequelize.transaction(async (t) => {

    const createdMain = await main1.create({
      column1: 'string',
      column2: 'string',
      column3: 'string',
    }, { transaction: t });

    const createdTable1 = await table1.create({
      column1: 'string',
      column2: 'string',
      column3: 'string',
      mainId: createdMain.id
    }, { transaction: t });

    return {
      ...createdMain,
     table1: createdTable1,
    };
  });

} catch (error) {

  // If the execution reaches this line, an error occurred.
  // The transaction has already been rolled back automatically by Sequelize!

}

Creating main and table1 in one step:

return main1.create({
   column1: 'string',
   column2: 'string',
   column3: 'string',
   table1: {
     column1: 'string',
     column2: 'string',
     column3: 'string',
   },
   // Repeat for table 2 and table 3
}, {
    include: [ table1 ]
  // Include table 2 and table 3
  }]
});


问:
Get inserted id (node.js + mysql)
I try to get id of user (auto increment id field) when insert data to user table. Here is ,my code:

```<code>  let sql = "INSERT into users(name, date, photo) VALUES ('"+name+"', '"+date+"',  '"+photo+"')";
  connection.query(sql, (err, result) => {
      if(err) {
        //console.log(error);
          res.status(500).json({message: "Invalid Request"});
      } else {
        let inserted_id = result.user_id; // undefined
        console.log(inserted_id);
        res.status(200).json({message: ""});
      }
  });
</code>```

And when i try to print user_id i get undefined. Please help me.

答:
result.insertId will give inserted id. Use it like this:

```<code>connection.query(sql, (err, result) => {
      if(err) {

      } else {
          let inserted_id = result.insertId;
      }
 });
</code>```

Title: Get inserted id (node.js + mysql)

Body:
I try to get id of user (auto increment id field) when insert data to user table. Here is ,my code:

  let sql = "INSERT into users(name, date, photo) VALUES ('"+name+"', '"+date+"',  '"+photo+"')";
  connection.query(sql, (err, result) => {
      if(err) {
        //console.log(error);
          res.status(500).json({message: "Invalid Request"});
      } else {
        let inserted_id = result.user_id; // undefined
        console.log(inserted_id);
        res.status(200).json({message: ""});
      }
  });

And when i try to print user_id i get undefined. Please help me.

Body:
result.insertId will give inserted id. Use it like this:

connection.query(sql, (err, result) => {
      if(err) {

      } else {
          let inserted_id = result.insertId;
      }
 });


问:
I need to access my remote pc using my IP address , so i can control my PC remotly
I need to access my remote pc using my IP address , so i can control my PC remotly.
Plz help me

Thanks.

答: The easiest way would be to use VNC (for example tightVNC) or remote desktop. If you have a dynamic IP, you could use DynDns.org to provide a static URL for your IP.</p>

ContentLicense: CC BY-SA 3.0


问:
Align the green button at the end of each div in css
I have this "buy" (comprar) button that I'd like to put in the end of div so they would be align with each other "buy" button.

eg:

```<code>button button button
</code>```

not:

```<code>button            button
       button
</code>```

#content01{
 min-height:500px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
}

.produto{
  display: inline-block;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  vertical-align: top;
  padding-bottom:10px;
}

.comprar_button {
  background: green;
  padding:10px;
  color: #fff;
  text-align:center;
  font-weight:bold;
  vertical-align:bottom;
  align-self: flex-end;
}

.comprar_button a{
  color: #fff!important;
}

.comprar_button img{
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content01">

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text text some text some text some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text Some text Some text Some text Some text Some text Some text Some text Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

</div></code>```

https://jsfiddle.net/j72u8Lx5/

how can I align the "comprar" button?

答:
using flex I commented the changes I did in the code :
https://jsfiddle.net/3jenapsb

#content01{
 min-height:500px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
}

.produto{

  display: flex;/*added*/
  flex-direction:column;/*added*/
  align-items:center;/*added*/
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  vertical-align: top;
  padding-bottom:10px;
}

b{
  flex-grow:1;/*added*/
}

.comprar_button {
 background: green;
 padding:10px;
 color: #fff;
 text-align:center;
 font-weight:bold;
 vertical-align:bottom;
 width:150px;/*added*/
}
.comprar_button a{
 color: #fff!important;
}
.comprar_button img{
 width: 15px;
 height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content01">

<div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

<div class="produto">Some text text some text some text some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

<div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

<div class="produto">Some text Some text Some text Some text Some text Some text Some text Some text Some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

   </div></code>```

Body:
I have this "buy" (comprar) button that I'd like to put in the end of div so they would be align with each other "buy" button.

eg:

button button button

not:

button            button
       button

#content01{
 min-height:500px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
}

.produto{
  display: inline-block;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  vertical-align: top;
  padding-bottom:10px;
}

.comprar_button {
  background: green;
  padding:10px;
  color: #fff;
  text-align:center;
  font-weight:bold;
  vertical-align:bottom;
  align-self: flex-end;
}

.comprar_button a{
  color: #fff!important;
}

.comprar_button img{
  width: 15px;
  height: 15px;
}

Some text

$ 20.00

COMPRAR

Some text text some text some text some text

$ 20.00

COMPRAR

Some text

$ 20.00

COMPRAR

Some text Some text Some text Some text Some text Some text Some text Some text Some text

$ 20.00

COMPRAR

https://jsfiddle.net/j72u8Lx5/

how can I align the "comprar" button?

Body:
using flex I commented the changes I did in the code :
https://jsfiddle.net/3jenapsb

#content01{
 min-height:500px;
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
}

.produto{

  display: flex;/*added*/
  flex-direction:column;/*added*/
  align-items:center;/*added*/
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  vertical-align: top;
  padding-bottom:10px;
}

b{
  flex-grow:1;/*added*/
}

.comprar_button {
 background: green;
 padding:10px;
 color: #fff;
 text-align:center;
 font-weight:bold;
 vertical-align:bottom;
 width:150px;/*added*/
}
.comprar_button a{
 color: #fff!important;
}
.comprar_button img{
 width: 15px;
 height: 15px;
}

<div id="content01">

<div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

<div class="produto">Some text text some text some text some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

<div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

<div class="produto">Some text Some text Some text Some text Some text Some text Some text Some text Some text<br><br><br><b>$ 20.00</b><br><br>
  <br><span class="comprar_button">COMPRAR</span>
</div>

   </div>


问:
AWS API gateway timeouts
I have set up serverless environment on AWS using lambdas and api gateway.
I have a script what gets called whenever someone fills up information on contact form.
The script itself looks like this:

```<code>const rp = require('request-promise')
const sendEmail = require('./sendEmail')

    module.exports.run = async (event, context, callback) => {
      const body = JSON.parse(event.body)
      const { name, email, budget, message, attachment } = body
      if (!name) {
        return callback(null, {
          statusCode: 400,
          body: JSON.stringify({ message: 'Name is required' }),
        })
      }

      if (!email) {
        return callback(null, {
          statusCode: 400,
          body: JSON.stringify({ message: 'Email address is required' }),
        })
      }

      if (!message) {
        return callback(null, {
          statusCode: 400,
          body: JSON.stringify({ message: 'Message is required' }),
        })
      }

      return Promise.all([
        sendEmail({
          to: 'Example <user@example.com>',
          subject: 'Received submission',
          data:
            'Hello'
        }),
        sendEmail({
          to: `${name} <${email}>`,
          subject: 'Subject',
          data:
            'Example text',
        }),

      ])
        .then(() => {
          return callback(null, {
            statusCode: 200,
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Credentials': true,
            },
            body: JSON.stringify({ message: 'Great success' }),
          })
        })
        .catch(err => {
          return callback(null, {
            statusCode: 500,
            body: JSON.stringify({
              message: 'Oh no :( Message not delivered',
              error: err,
            }),
          })
        })
    }
</code>```

And this is my sendEmail class

```<code>const AWS = require('aws-sdk')

const ses = new AWS.SES()

module.exports = function({ to, subject, data, replyTo }) {
  return ses
    .sendEmail({
      Destination: { ToAddresses: [to] },
      Message: {
        Body: {
          Text: { Charset: 'UTF-8', Data: data },
        },
        Subject: {
          Data: subject,
          Charset: 'UTF-8',
        },
      },
      Source: 'Example <user@example.com>',
      ReplyToAddresses: [replyTo],
    })
    .promise()
}
</code>```

However it keeps hanging due to the timeout which are limited to five minutes on aws side, is there something i'm missing that it's taking longer than five minutes?

答:
I am seeing two issues here.

you are mixing callback and async syntax of lambda

you are mixing promise & async/await syntax

you can simply return the output, instead of of using callback. I have also changed the promise syntax to async/await.

```<code>const sendEmail = require('./sendEmail')

module.exports.run = async (event, context) => {
  const body = JSON.parse(event.body)
  const { name, email, budget, message, attachment } = body
  if (!name) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'Name is required' }),
    }
  }

  if (!email) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'Email address is required' }),
    }
  }

  if (!message) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'Message is required' }),
    }
  }

  try {
    await Promise.all([
      sendEmail({
        to: 'Example <user@example.com>',
        subject: 'Received submission',
        data:
          'Hello'
      }),
      sendEmail({
        to: `${name} <${email}>`,
        subject: 'Subject',
        data:
          'Example text',
      }),

    ]);

    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
      },
      body: JSON.stringify({ message: 'Great success' }),
    }
  } catch (err) {
    return {
      statusCode: 500,
      body: JSON.stringify({
        message: 'Oh no :( Message not delivered',
        error: err,
      }),
    }
  }
}
</code>```

Title: AWS API gateway timeouts

Body:
I have set up serverless environment on AWS using lambdas and api gateway.
I have a script what gets called whenever someone fills up information on contact form.
The script itself looks like this:

const rp = require('request-promise')
const sendEmail = require('./sendEmail')

    module.exports.run = async (event, context, callback) => {
      const body = JSON.parse(event.body)
      const { name, email, budget, message, attachment } = body
      if (!name) {
        return callback(null, {
          statusCode: 400,
          body: JSON.stringify({ message: 'Name is required' }),
        })
      }

      if (!email) {
        return callback(null, {
          statusCode: 400,
          body: JSON.stringify({ message: 'Email address is required' }),
        })
      }

      if (!message) {
        return callback(null, {
          statusCode: 400,
          body: JSON.stringify({ message: 'Message is required' }),
        })
      }

      return Promise.all([
        sendEmail({
          to: 'Example <user@example.com>',
          subject: 'Received submission',
          data:
            'Hello'
        }),
        sendEmail({
          to: `${name} <${email}>`,
          subject: 'Subject',
          data:
            'Example text',
        }),

      ])
        .then(() => {
          return callback(null, {
            statusCode: 200,
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Credentials': true,
            },
            body: JSON.stringify({ message: 'Great success' }),
          })
        })
        .catch(err => {
          return callback(null, {
            statusCode: 500,
            body: JSON.stringify({
              message: 'Oh no :( Message not delivered',
              error: err,
            }),
          })
        })
    }

And this is my sendEmail class

const AWS = require('aws-sdk')

const ses = new AWS.SES()

module.exports = function({ to, subject, data, replyTo }) {
  return ses
    .sendEmail({
      Destination: { ToAddresses: [to] },
      Message: {
        Body: {
          Text: { Charset: 'UTF-8', Data: data },
        },
        Subject: {
          Data: subject,
          Charset: 'UTF-8',
        },
      },
      Source: 'Example <user@example.com>',
      ReplyToAddresses: [replyTo],
    })
    .promise()
}

However it keeps hanging due to the timeout which are limited to five minutes on aws side, is there something i'm missing that it's taking longer than five minutes?

Body:
I am seeing two issues here.

you are mixing callback and async syntax of lambda

you are mixing promise & async/await syntax

you can simply return the output, instead of of using callback. I have also changed the promise syntax to async/await.

const sendEmail = require('./sendEmail')

module.exports.run = async (event, context) => {
  const body = JSON.parse(event.body)
  const { name, email, budget, message, attachment } = body
  if (!name) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'Name is required' }),
    }
  }

  if (!email) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'Email address is required' }),
    }
  }

  if (!message) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'Message is required' }),
    }
  }

  try {
    await Promise.all([
      sendEmail({
        to: 'Example <user@example.com>',
        subject: 'Received submission',
        data:
          'Hello'
      }),
      sendEmail({
        to: `${name} <${email}>`,
        subject: 'Subject',
        data:
          'Example text',
      }),

    ]);

    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
      },
      body: JSON.stringify({ message: 'Great success' }),
    }
  } catch (err) {
    return {
      statusCode: 500,
      body: JSON.stringify({
        message: 'Oh no :( Message not delivered',
        error: err,
      }),
    }
  }
}


问:
What am I missing in this Alert React Bootstrap example?
It's been a day and my head is bloody from beating it on this wall: two easy react-bootstrap Alert examples that are invisible. I manually edited the style and removed the 'fade' style (for the alert titled 'check it out'), and the alert shows. But they are both supposed to show by default.

What did I do wrong? I am new to React. But I did not expect such an easy example to go wrong.

```<code>import React, { useState } from 'react';
import { Button, FormGroup, FormControl, FormLabel } from 'react-bootstrap';
import { Alert } from 'react-bootstrap';
import '../styles/login.css';

const Login: React.FC<{}> = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

...

    return (
        <div className="Login">
            <form onSubmit={handleSubmit}>
                <FormGroup controlId="email">
                    <FormLabel>Email</FormLabel>
                    <FormControl
                        autoFocus
                        type="string"
                        value={email}
                        onChange={(e: any) => setEmail(e.target.value)} />
                </FormGroup>
                <FormGroup controlId="password">
                    <FormLabel>Password</FormLabel>
                    <FormControl
                        value={password}
                        onChange={(e: any) => setPassword(e.target.value)}
                        type="password" />
                </FormGroup>
                <Button block disabled={!validateForm()} type="submit">
                    Login
                </Button>

                <Alert key={1} variant="success">check it out!</Alert>

                <Alert show={true} variant="success">
                    <Alert.Heading>Oh snap! You got an error!</Alert.Heading>
                    <p>
                        Change this and that and try again. Duis mollis, est non commodo
                        luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.
                        Cras mattis consectetur purus sit amet fermentum.
                    </p>
                </Alert>
            </form>
        </div>
    );
}

export default Login;
</code>```

答:
Ok, well, the examples in the official documentation have fade true by default. This means they don't show. This isn't official, because the docs for react-bootstrap don't say this -- the docs for reactstrap do. Reactstrap is a competing package to react-boostrap.

So it seems the transition is 'fade' by default. Which means that a newb will use the example and see nothing at all.

The react-bootstrap docs do mention the transition group, but don't say that they're defaulted to false. They also don't tell how to express a transition inline. I was trying: transition={{Fade: {in: false}}. If you need to see that through, look here. I tried inline and through the  element, but no go.

If I switch to reactstrap, the example alert is shown with the below code:

```<code> <Alert color='primary' fade={false}>check it out!</Alert>
</code>```

Which seems to be a lot simpler than struggling with react-bootstrap beta. So I'll use reactstrap to alert.

Body:
It's been a day and my head is bloody from beating it on this wall: two easy react-bootstrap Alert examples that are invisible. I manually edited the style and removed the 'fade' style (for the alert titled 'check it out'), and the alert shows. But they are both supposed to show by default.

What did I do wrong? I am new to React. But I did not expect such an easy example to go wrong.

import React, { useState } from 'react';
import { Button, FormGroup, FormControl, FormLabel } from 'react-bootstrap';
import { Alert } from 'react-bootstrap';
import '../styles/login.css';

const Login: React.FC<{}> = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

...

    return (

            <form onSubmit={handleSubmit}>
                <FormGroup controlId="email">
                    <FormLabel>Email</FormLabel>
                    <FormControl
                        autoFocus
                        type="string"
                        value={email}
                        onChange={(e: any) => setEmail(e.target.value)} />
                </FormGroup>
                <FormGroup controlId="password">
                    <FormLabel>Password</FormLabel>
                    <FormControl
                        value={password}
                        onChange={(e: any) => setPassword(e.target.value)}
                        type="password" />
                </FormGroup>
                <Button block disabled={!validateForm()} type="submit">
                    Login
                </Button>

                <Alert key={1} variant="success">check it out!</Alert>

                <Alert show={true} variant="success">
                    <Alert.Heading>Oh snap! You got an error!</Alert.Heading>

                        Change this and that and try again. Duis mollis, est non commodo
                        luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.
                        Cras mattis consectetur purus sit amet fermentum.

                </Alert>
            </form>

    );
}

export default Login;

Body:
Ok, well, the examples in the official documentation have fade true by default. This means they don't show. This isn't official, because the docs for react-bootstrap don't say this -- the docs for reactstrap do. Reactstrap is a competing package to react-boostrap.

So it seems the transition is 'fade' by default. Which means that a newb will use the example and see nothing at all.

The react-bootstrap docs do mention the transition group, but don't say that they're defaulted to false. They also don't tell how to express a transition inline. I was trying: transition={{Fade: {in: false}}. If you need to see that through, look here. I tried inline and through the  element, but no go.

If I switch to reactstrap, the example alert is shown with the below code:

 <Alert color='primary' fade={false}>check it out!</Alert>

Which seems to be a lot simpler than struggling with react-bootstrap beta. So I'll use reactstrap to alert.


问:
Start-AzStorageBlobCopy across two storage accounts with UseConnectedAccount context
I have two storage accounts (A and B) and one identity (Id). I need to copy blob X from A->B but I'm having issues where the call to Start-AzStorageBlobCopy fails with 404 - The specified resource does not exist.

Some more context:

Id is assigned Storage Blob Data Reader role to the container where X is stored in A (source).

Id is assigned Storage Blob Data Contributor role to the resource group that has B (target)

I'm creating both the source and target storage context using the -UseConnectedAccount switch.

The source blob is definitely there, I verify within the same script via a call to Get-AzStorageBlob using the same context I use for the copy call.

I debugged with fiddler and I see that the request goes to the target storage account, I'm guessing the issue is the bearer token it's passed doesn't get propagated to the request against the source? Anyone know how to make this work?

I cannot give Id more access in A, and using SAS tokens will not work unless I can generate them on-the-fly which seems like I cannot do for A either with the permissions it has.

Here's an extract of the relevant commands I'm using:

$targetContext = New-AzStorageContext -StorageAccountName $targetAccountName -UseConnectedAccount
$srcContext = New-AzStorageContext -StorageAccountName $sourceAccountName -UseConnectedAccount

#Verify $sourceBlob has the metadata for the source
$sourceBlob = Get-AzStorageBlob -Blob $blobName -Container $containerName -Context $srcContext

#Verifies that can write to target context
Set-AzStorageBlobContent -Context $targetContext -Container "vhds" -File "c:\test.txt" -Blob "test"

# Fails with 404
Start-AzStorageBlobCopy -SrcContainer $containerName -SrcBlob $blobName -Context $srcContext -DestContext $targetContext -DestContainer $containerName -DestBlob $blobName -Force

```

答:
Answering my own question in case someone runs into it. Looks like this is not possible, based on the docs copying across storage accounts requires a SAS Token for the source.

https://learn.microsoft.com/en-us/rest/api/storageservices/copy-blob#authorization


答:
Assign display: flex also to your .produto DIVs, with flex-direction: column and align-items: center. Then add margin-top: auto to the .comprar_button to move it to the bottom of the container (and remove some other, superfluous stuff, see below):

#content01{
 min-height:500px;
 display: flex;
 flex-wrap: wrap;
}

.produto{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  padding-bottom:10px;
}

.comprar_button {
  background: green;
  padding:10px;
  color: #fff;
  font-weight:bold;
  margin-top: auto;
}

.comprar_button a{
  color: #fff!important;
}

.comprar_button img{
  width: 15px;
  height: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content01">

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text text some text some text some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text Some text Some text Some text Some text Some text Some text Some text Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

</div></code>```

Title: Align the green button at the end of each div in css

Body:
Assign display: flex also to your .produto DIVs, with flex-direction: column and align-items: center. Then add margin-top: auto to the .comprar_button to move it to the bottom of the container (and remove some other, superfluous stuff, see below):

#content01{
 min-height:500px;
 display: flex;
 flex-wrap: wrap;
}

.produto{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 2px solid #F6F6F6;
  width: 246px;
  text-align: center;
  padding-bottom:10px;
}

.comprar_button {
  background: green;
  padding:10px;
  color: #fff;
  font-weight:bold;
  margin-top: auto;
}

.comprar_button a{
  color: #fff!important;
}

.comprar_button img{
  width: 15px;
  height: 15px;
}

<div id="content01">

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text text some text some text some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

  <div class="produto">Some text Some text Some text Some text Some text Some text Some text Some text Some text<br><br><br><b>$ 20.00</b><br><br>
      <br><span class="comprar_button">COMPRAR</span>
  </div>

</div>


问:
R devtools not reading Windows path with spaces in it, not found in $PATH variable
I'm working with the devtools package in R, and I'm trying to use it to install a GitHub repo for my class. However, I have a path with spaces in it, and here is the error message I'm getting:

```<code>Installing package into ‘C:/Users/Kaelan McGurk/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
* installing *source* package 'buildings' ...
** using staged installation
** R
** data
*** moving datasets to lazyload DB
** byte-compile and prepare package for lazy loading
Fatal error: cannot open file 'C:\Users\Kaelan': No such file or directory
</code>```

But here is the output of Sys.getenv("PATH"):

```<code>C:\\Program Files\\R\\R-3.6.0\\bin\\x64;C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\PharosSystems\\Core;C:\\Program Files (x86)\\Skype\\Phone\\;C:\\Program Files\\PuTTY\\;C:\\Program Files (x86)\\Wolfram Research\\WolframScript\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Intel\\WiFi\\bin\\;C:\\Program Files\\Common Files\\Intel\\WirelessCommon\\;C:\\Program Files\\MySQL\\MySQL Shell 8.0\\bin\\;C:\\Users\\Kaelan McGurk\\Documents\\MATH335\\M335_WI20_McGurk_Kael\\%USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps
</code>```

So I'm not sure what's going on here,

How can I avoid the fatal error "cannot open file"

答:
First of all the %PATH% is not of much use in that case. Second - a solution for working with windows directory paths that I usually apply is running dir /X command in a windows cmd prompt, since that will show you short directory names (eg for 'Program Files' it will show you PROGRA~1).

Still this will not solve your current issue imho. But potentially the following could - I haven't tested it on a WIN machine for now but try the following (in R):

```<code>.libPaths('C:/Users/Kaelan~1/Documents/R/win-library/3.6')
</code>```

IMPORTANT replace Kaelan~1 here with whatever dir /X showed you as the short name for your directory. Then retry the package installation.

If that fixes your issue potentially put that line in your ~/.Rprofile for now, before you change your User account name to simply Kaelan ;-)

Body:
I'm working with the devtools package in R, and I'm trying to use it to install a GitHub repo for my class. However, I have a path with spaces in it, and here is the error message I'm getting:

Installing package into ‘C:/Users/Kaelan McGurk/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
* installing *source* package 'buildings' ...
** using staged installation
** R
** data
*** moving datasets to lazyload DB
** byte-compile and prepare package for lazy loading
Fatal error: cannot open file 'C:\Users\Kaelan': No such file or directory

But here is the output of Sys.getenv("PATH"):

C:\\Program Files\\R\\R-3.6.0\\bin\\x64;C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\PharosSystems\\Core;C:\\Program Files (x86)\\Skype\\Phone\\;C:\\Program Files\\PuTTY\\;C:\\Program Files (x86)\\Wolfram Research\\WolframScript\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Intel\\WiFi\\bin\\;C:\\Program Files\\Common Files\\Intel\\WirelessCommon\\;C:\\Program Files\\MySQL\\MySQL Shell 8.0\\bin\\;C:\\Users\\Kaelan McGurk\\Documents\\MATH335\\M335_WI20_McGurk_Kael\\%USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps

So I'm not sure what's going on here,

How can I avoid the fatal error "cannot open file"

Body:
First of all the %PATH% is not of much use in that case. Second - a solution for working with windows directory paths that I usually apply is running dir /X command in a windows cmd prompt, since that will show you short directory names (eg for 'Program Files' it will show you PROGRA~1).

Still this will not solve your current issue imho. But potentially the following could - I haven't tested it on a WIN machine for now but try the following (in R):

.libPaths('C:/Users/Kaelan~1/Documents/R/win-library/3.6')

IMPORTANT replace Kaelan~1 here with whatever dir /X showed you as the short name for your directory. Then retry the package installation.

If that fixes your issue potentially put that line in your ~/.Rprofile for now, before you change your User account name to simply Kaelan ;-)


问:
Dereference Operator Before an Array Element?
What does the notation in something like int y = *x[0] do, i.e. when you have a dereference operator right before an array element?

答: The array subscript operator has higher precedence than the dereference operator, so *x[0] dereferences element 0 of the array x.  This would make sense if you had an array of pointers, i.e. int *x[10].


问:
Vector capacity and reserve
Consider the following code snippet:

```<code>std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;
</code>```

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?

答:
If the capacity is 100, then the vector has space allocated for 100 elements. reserve(0) is a no-op, because reserve won't shrink the capacity.

reserve(n) will try to grow the allocation to enough space for at least n elements. There's no guarantee that it will succeed, it won't report failure and it may overallocate.

Don't call reserve unless you've measured your code with and without it and found it makes a significant difference. All other use of reserve is premature optimization.

Title: Vector capacity and reserve

Body:
Consider the following code snippet:

std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?


问:
Get value to the right of the decimal in python
If I print 5/4 I get 1.25. How do I just get the .25 part. </p>

```<code>print(5/4)
1.25
</code>```

答:
Not the most elegant solution but this will work    </p>

```<code>print(5/4-5//4)
</code>```

Body:
If I print 5/4 I get 1.25. How do I just get the .25 part.

print(5/4)
1.25

Body:
Not the most elegant solution but this will work

print(5/4-5//4)


问:
Do something after all asynchronous, nested, $.each database calls are completed
I'm trying to run a function after 1) all loops are completed and 2) all database calls within those loops are completed.

My database call functions (segmentDatabaseCall and stepDatabaseCall) all take some arguments, resolve a Promise and send the data once the call is complete. This is a (very) simplified version of my code:

```<code>let localData = {}

segmentDatabaseCall(argument) // Call the database
.then(segmentResult => { // Returns trip segments (array of objects)

  $.each(segmentResult, (segmentIndex, segmentValue) => { // For each trip segment...

    localData['something'] = segmentValue.something // Add some data to local data

    stepDatabaseCall(segmentValue.segment_id) // Call the database once per trip segment...
    .then(stepResult => { // Returns trip steps (array of objects)

      $.each(stepResult, (stepIndex, stepValue) => { // For each trip step...

        localData['something'][i]['something_else'] = stepValue.something_else // Add some data to local data

        // THIS DOESN'T WORK
        const segsDone = segmentIndex >= segmentResult.length - 1;
        const stepsDone = stepIndex >= stepResult.length - 1;
        if (segsDone && stepsDone) {
          // This if statement runs before all calls are finished 1 out of 3 times roughly
        }
      })
    })
  })
})
</code>```

Database call:

```<code>function databaseCall (argument) {
    return new Promise((resolve, reject) => {
        $.ajax({
          url: $phpUrl,
          type: 'post',
            data: {
              'argument': argument
            }
        })
        .done (function (data) {
            var resultJson = JSON.parse(data)
            resolve(resultJson)
        })
        .fail (function (error) {
            reject(error)
        })
    })
}
</code>```

I've tried using the answer here, but it runs before all calls are finished 1 in 3 times. I must be missing some counter there?

I also think there's a way to do this using Promise maps, but I can't get my head around it.

答:
Seeing that you are already using JQuery, you can wrap all of your asynchronous calls with the $.when function.

This will allow you to chain together all your promises and manage the completion of all promises with a single .done() function.

https://api.jquery.com/jQuery.when/

From the JQuery website:

```<code>$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
  if ( /Whip It/.test( data ) ) {
    alert( "We got what we came for!" );
  }
});
</code>```

Body:
I'm trying to run a function after 1) all loops are completed and 2) all database calls within those loops are completed.

My database call functions (segmentDatabaseCall and stepDatabaseCall) all take some arguments, resolve a Promise and send the data once the call is complete. This is a (very) simplified version of my code:

let localData = {}

segmentDatabaseCall(argument) // Call the database
.then(segmentResult => { // Returns trip segments (array of objects)

  $.each(segmentResult, (segmentIndex, segmentValue) => { // For each trip segment...

    localData['something'] = segmentValue.something // Add some data to local data

    stepDatabaseCall(segmentValue.segment_id) // Call the database once per trip segment...
    .then(stepResult => { // Returns trip steps (array of objects)

      $.each(stepResult, (stepIndex, stepValue) => { // For each trip step...

        localData['something'][i]['something_else'] = stepValue.something_else // Add some data to local data

        // THIS DOESN'T WORK
        const segsDone = segmentIndex >= segmentResult.length - 1;
        const stepsDone = stepIndex >= stepResult.length - 1;
        if (segsDone && stepsDone) {
          // This if statement runs before all calls are finished 1 out of 3 times roughly
        }
      })
    })
  })
})

Database call:

function databaseCall (argument) {
    return new Promise((resolve, reject) => {
        $.ajax({
          url: $phpUrl,
          type: 'post',
            data: {
              'argument': argument
            }
        })
        .done (function (data) {
            var resultJson = JSON.parse(data)
            resolve(resultJson)
        })
        .fail (function (error) {
            reject(error)
        })
    })
}

I've tried using the answer here, but it runs before all calls are finished 1 in 3 times. I must be missing some counter there?

I also think there's a way to do this using Promise maps, but I can't get my head around it.

Body:
Seeing that you are already using JQuery, you can wrap all of your asynchronous calls with the $.when function.

This will allow you to chain together all your promises and manage the completion of all promises with a single .done() function.

https://api.jquery.com/jQuery.when/

From the JQuery website:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
  if ( /Whip It/.test( data ) ) {
    alert( "We got what we came for!" );
  }
});


问:
unable to excute command without sudo root
remote user:ab
escalated user: UNIX

when i am doing copy module to /etc/profile.d/.its throwing error permission denied.
but with shell and command module.

```<code>sudo  cp    myscript.sh    /etc/profile.d/
</code>```

its working from UNIX user.i want to use ansible module rather than shell or command.here issue with sudo from UNIX user to execute command with sudo privileged.Become user i can't use root directly. Dont have access through unix user i can use sudo.

already used below details.

```<code>become=yes
become_method=sudo
become_user=unix
become_ask_pass=false
</code>```

答:
sudo cp means that it is running as root, not the user unix.

Try removing the line

become_user=unix

Body:
remote user:ab
escalated user: UNIX

when i am doing copy module to /etc/profile.d/.its throwing error permission denied.
but with shell and command module.

sudo  cp    myscript.sh    /etc/profile.d/

its working from UNIX user.i want to use ansible module rather than shell or command.here issue with sudo from UNIX user to execute command with sudo privileged.Become user i can't use root directly. Dont have access through unix user i can use sudo.

already used below details.

become=yes
become_method=sudo
become_user=unix
become_ask_pass=false


问:
I can't get expect to work with a specific string
I'm writing a bash script to create self-signed certificate.

The script works well until I have to sign the certificate. Indeed, i can't get my expect command to match the received string.

Here is the string my terminal returns :

```<code>Sign the certificate? [y/n]:
</code>```

And here are my commands :

/usr/bin/expect <<EOD
spawn sudo openssl ca -config CA/ca.cnf -policy policy_anything -out CA/newcerts/webserver.cert -infiles CA/certrequests/webserver.csr
expect {Enter pass phrase for ./CA/private/cakey.pem:} {send "${PEMpassword}\n"}
expect -re {Sign the certificate? [^:]*:} {send "y\n"}
expect -re {1 out of 1 certificate requests certified, commit? [^:]*:} {send "y\n"}
expect eof
EOD
```

<p>I'm not very familiar with expect nor regex but "[^:]*" worked for me until now for similar strings.</p>

<p>I have unsuccessfully tried those :</p>

```[?*]
\*
?:
[y/n]
\[y/n\]
"[y/n]"
[\w/\w]
[w+]
[\w+]
```

Thanks in advance for your suggestions !

答:
The problem may be that you begin the regex with

```<code>Sign the certificate? ...
</code>```

but ? is a special pattern character that means 0 or 1 times, so in this case you are matching the letter e 0 or 1 times. It will do that match, but then your regex continues with a space, which does not match the real ? character in the input.  To remove the special meaning from the ? precede it with a backslash, \?, or use . to match any character more loosely. Note, you have the same problem on the following line too.

Body:
I'm writing a bash script to create self-signed certificate.

The script works well until I have to sign the certificate. Indeed, i can't get my expect command to match the received string.

Here is the string my terminal returns :

Sign the certificate? [y/n]:

And here are my commands :

/usr/bin/expect <<EOD
spawn sudo openssl ca -config CA/ca.cnf -policy policy_anything -out CA/newcerts/webserver.cert -infiles CA/certrequests/webserver.csr
expect {Enter pass phrase for ./CA/private/cakey.pem:} {send "${PEMpassword}\n"}
expect -re {Sign the certificate? [^:]*:} {send "y\n"}
expect -re {1 out of 1 certificate requests certified, commit? [^:]*:} {send "y\n"}
expect eof
EOD

I'm not very familiar with expect nor regex but "[^:]*" worked for me until now for similar strings.

I have unsuccessfully tried those :

[?*]
\*
?:
[y/n]
\[y/n\]
"[y/n]"
[\w/\w]
[w+]
[\w+]

Thanks in advance for your suggestions !

Body:
The problem may be that you begin the regex with

Sign the certificate? ...

but ? is a special pattern character that means 0 or 1 times, so in this case you are matching the letter e 0 or 1 times. It will do that match, but then your regex continues with a space, which does not match the real ? character in the input.  To remove the special meaning from the ? precede it with a backslash, \?, or use . to match any character more loosely. Note, you have the same problem on the following line too.


问:
jsf dynamic change of managedbean
How can I dynamically change managed bean of "value" attribute? For example, I have h:inputText and, depending on typed-in text, managed bean must be #{studentBean.login} or #{lecturerBean.login}. In a simplified form:

```<code><h:inputText id="loginField" value="#{'nameofbean'.login}" />
</code>```

I tried to embed another el-expression instead of 'nameofbean':

```<code>value="#{{userBean.specifyLogin()}.login}"
</code>```

but it doesn't worked out.

答:
Polymorphism should rather be done in the model, not in the view.

E.g.

```<code><h:inputText value="#{person.login}" />
</code>```

with

```<code>public interface Person {
    public void login();
}
</code>```

and

```<code>public class Student implements Person {
    public void login() {
        // ...
    }
}
</code>```

and

```<code>public class Lecturer implements Person {
    public void login() {
        // ...
    }
}
</code>```

and finally in the managed bean

```<code>private Person person;

public String login() {
    if (isStudent) person = new Student(); // Rather use factory.
    // ...
    if (isLecturer) person = new Lecturer(); // Rather use factory.
    // ...
    person.login();
    // ...
    return "home";
}
</code>```

Otherwise you have to change the view everytime when you add/remove a different type of Person. This is not right.

Title: jsf dynamic change of managedbean

Body:
How can I dynamically change managed bean of "value" attribute? For example, I have h:inputText and, depending on typed-in text, managed bean must be #{studentBean.login} or #{lecturerBean.login}. In a simplified form:

<h:inputText id="loginField" value="#{'nameofbean'.login}" />

I tried to embed another el-expression instead of 'nameofbean':

value="#{{userBean.specifyLogin()}.login}"

but it doesn't worked out.

Body:
Polymorphism should rather be done in the model, not in the view.

E.g.

<h:inputText value="#{person.login}" />

with

public interface Person {
    public void login();
}

and

public class Student implements Person {
    public void login() {
        // ...
    }
}

and

public class Lecturer implements Person {
    public void login() {
        // ...
    }
}

and finally in the managed bean

private Person person;

public String login() {
    if (isStudent) person = new Student(); // Rather use factory.
    // ...
    if (isLecturer) person = new Lecturer(); // Rather use factory.
    // ...
    person.login();
    // ...
    return "home";
}

Otherwise you have to change the view everytime when you add/remove a different type of Person. This is not right.


问:
How do we show a page from our app but using a custom domain owned by a user
We host an angular app (e.g. render.our-app.com) hosted on now/zeit. This app allows a user to show a presentation. The presentationId needs to be included in the path e.g. https://render.our-app.com/. We are looking to be able use a custom domain owned by the user, to show a presentation we no redirects.

So for example, the user has a domain (website.mycompany.com) and we want to show the presentation under that custom domain but using our app.

website.mycompany.com => render.our-app.com/12345 (12345 = presentationId)

We are not sure how to do this properly. We tried to use a cname but we get an error saying:
404: NOT_FOUND
Code: DEPLOYMENT_NOT_FOUND

(The error is very now/zeit specific)

We thought that http://website.mycompany.com/12345 might work.

We are not sure how to do this :(

Thanks

答:
The steps involved probably would be:

Set up a virtual host on your server for website.mycompany.com (or maybe use a ServerAlias directive if you are on Apache. This is where your app will be hosted.

Edit the host file of the computer that will be used for the presentation, in that host file you add an entry for website.mycompany.com, that points to the IP address of your server. By doing so, you bypass the normal DNS resolution process. Rather than connect to the 'true' address, the PC will connect to your demo server.

There is a gotcha: SSL. You can create a self-signed certificate on the server, and then you add it to the list trusted certificates on the client (demo PC). This can be done the first time you launch your browser and get an alert about the self-signed certificate.


问:
S3 pre-signed URL upload by curl successes but it's empty
I try to upload file to S3 by pre-singed url with curl.

It returns success when I run following command

```<code>❯ curl -v -X PUT --upload-file [file directory] '[pre-sined url]'
*   Trying [port]...
* TCP_NODELAY set
* Connected to bucket-name.s3.region.amazonaws.com (ip address) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: C=US; ST=Washington; L=Seattle; O=Amazon.com, Inc.; CN=*.region.amazonaws.com
*  start date: Nov  9 00:00:00 2019 GMT
*  expire date: Dec 10 12:00:00 2020 GMT
*  subjectAltName: host "bukcet-name.s3.region.amazonaws.com" matched cert's "*.s3.region.amazonaws.com"
*  issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert Baltimore CA-2 G2
*  SSL certificate verify ok.
> PUT [pre-signed url] HTTP/1.1
> Host: bukcet-name.s3.region.amazonaws.com
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: image/png
> Content-Length: 145701
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< x-amz-id-2: hogehoge
< x-amz-request-id:hugahuga
< Date: Mon, 17 Feb 2020 08:09:01 GMT
< ETag: "hogehuga"
< Content-Length: 0
< Server: AmazonS3
<
* Connection #0 to host bukcet-name.s3.region.amazonaws.com left intact
* Closing connection 0
</code>```

But When I look at S3, file is not uploaded.

I want to know how to upload file correctly to S3.

[Update]

I added x-amz-acl: bucket-owner-full-control header in curl and set <AllowedHeader>x-amz-acl</AllowedHeader> in S3 bucket CORS.

```<code>curl -v -X PUT -H 'x-amz-acl: bucket-owner-full-control' --upload-file [file directory] '[pre-sined url]'
</code>```

but It returns error.

<Error>AccessDenied<Message>There were headers present in the request which were not signed</Message><HeadersNotSigned>x-amz-acl</HeadersNotSigned>

Also I wonder my presigned url does not have file name in directry path. Is it correct presigned url?

My implementaion to generate pre-signed url is like this:

```<code>    req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(key),
    })
    url, err := req.Presign(expires)
</code>```

DO I need to add ACL inside PutObjectInput struct?

答:
This isssue is resolved by adding file name in the end of s3 directory when it is generated.

For example(Golang):

```<code>
    req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String("hogehoge/fugafuga/filename"),
        Key:    aws.String(key),
    })
    url, err := req.Presign(expires)
</code>```

Body:
I try to upload file to S3 by pre-singed url with curl.

It returns success when I run following command

❯ curl -v -X PUT --upload-file [file directory] '[pre-sined url]'
*   Trying [port]...
* TCP_NODELAY set
* Connected to bucket-name.s3.region.amazonaws.com (ip address) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: C=US; ST=Washington; L=Seattle; O=Amazon.com, Inc.; CN=*.region.amazonaws.com
*  start date: Nov  9 00:00:00 2019 GMT
*  expire date: Dec 10 12:00:00 2020 GMT
*  subjectAltName: host "bukcet-name.s3.region.amazonaws.com" matched cert's "*.s3.region.amazonaws.com"
*  issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert Baltimore CA-2 G2
*  SSL certificate verify ok.
> PUT [pre-signed url] HTTP/1.1
> Host: bukcet-name.s3.region.amazonaws.com
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: image/png
> Content-Length: 145701
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< x-amz-id-2: hogehoge
< x-amz-request-id:hugahuga
< Date: Mon, 17 Feb 2020 08:09:01 GMT
< ETag: "hogehuga"
< Content-Length: 0
< Server: AmazonS3
<
* Connection #0 to host bukcet-name.s3.region.amazonaws.com left intact
* Closing connection 0

But When I look at S3, file is not uploaded.

I want to know how to upload file correctly to S3.

[Update]

I added x-amz-acl: bucket-owner-full-control header in curl and set <AllowedHeader>x-amz-acl</AllowedHeader> in S3 bucket CORS.

curl -v -X PUT -H 'x-amz-acl: bucket-owner-full-control' --upload-file [file directory] '[pre-sined url]'

but It returns error.

<Error>AccessDenied<Message>There were headers present in the request which were not signed</Message><HeadersNotSigned>x-amz-acl</HeadersNotSigned>

Also I wonder my presigned url does not have file name in directry path. Is it correct presigned url?

My implementaion to generate pre-signed url is like this:

    req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(key),
    })
    url, err := req.Presign(expires)

DO I need to add ACL inside PutObjectInput struct?

Body:
This isssue is resolved by adding file name in the end of s3 directory when it is generated.

For example(Golang):

    req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String("hogehoge/fugafuga/filename"),
        Key:    aws.String(key),
    })
    url, err := req.Presign(expires)


问:
histogram without vertical lines
When I create a histogram, it looks a lot like this:

```<code>set.seed(1)
x <- 1:100
y <- x + rnorm(50)
y=round(y)
hist(y)
</code>```

Is there a way to make a histogram look a bit like this? I can only get a histogram with bins, which I don't need for my plot.

I don't want the black bins, I actually only want the blue, green and red lines. Can stackoverflow point me in the right direction?

答:
Put your histogram in an object, and use type="s" to get the stepwise plot :

```<code>x <- rnorm(1000)
y <- hist(x)
plot(y$breaks,
      c(y$counts,0)
   ,type="s",col="blue")
</code>```

gives :

Title: histogram without vertical lines

Body:
When I create a histogram, it looks a lot like this:

set.seed(1)
x <- 1:100
y <- x + rnorm(50)
y=round(y)
hist(y)

Is there a way to make a histogram look a bit like this? I can only get a histogram with bins, which I don't need for my plot.

I don't want the black bins, I actually only want the blue, green and red lines. Can stackoverflow point me in the right direction?

Body:
Put your histogram in an object, and use type="s" to get the stepwise plot :

x <- rnorm(1000)
y <- hist(x)
plot(y$breaks,
      c(y$counts,0)
   ,type="s",col="blue")

gives :


问:
What is causing the error that swagger is already in the route collection for Web API 2?
I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.

My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.

In Package Console Manager run:

```<code>Install-Package Swashbuckle
</code>```

To get your Test Web API controller working:
1) Comment this out in the WebApi.config:

```<code>// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
</code>```

Now this URL:
http://localhost:33515/api/Test
brings back XML:

```<code><ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance"     xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
</code>```

In Global.asax Register() I call:

```<code> SwaggerConfig.Register();
</code>```

In AppStart.Swagger.Config Register() I put:

```<code>public class SwaggerConfig
{
    public static void Register()
    {
       var thisAssembly = typeof(SwaggerConfig).Assembly;
       GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1.0", "HRSA CHAFS");
                    c.IncludeXmlComments(GetXmlCommentsPath());
                })
              .EnableSwaggerUi(c =>
                {});
    }

    private static string GetXmlCommentsPath()
    {
        var path = String.Format(@"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
        return path;

    }
}
</code>```

Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."

I've been stuck on this for hours.
How do you get rid of this?

答:
I solved the problem by deleting the SwaggerConfig.cs file from the App_Start folder as I had already created it manually.
Take a look at this link, here also has more useful information:

A route named 'DefaultApi' is already in the route collection error

Body:
I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.

My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.

In Package Console Manager run:

Install-Package Swashbuckle

To get your Test Web API controller working:
1) Comment this out in the WebApi.config:

// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

Now this URL:
http://localhost:33515/api/Test
brings back XML:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance"     xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>

In Global.asax Register() I call:

 SwaggerConfig.Register();

In AppStart.Swagger.Config Register() I put:

public class SwaggerConfig
{
    public static void Register()
    {
       var thisAssembly = typeof(SwaggerConfig).Assembly;
       GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1.0", "HRSA CHAFS");
                    c.IncludeXmlComments(GetXmlCommentsPath());
                })
              .EnableSwaggerUi(c =>
                {});
    }

    private static string GetXmlCommentsPath()
    {
        var path = String.Format(@"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
        return path;

    }
}

Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."

I've been stuck on this for hours.
How do you get rid of this?


问:
directoryRoles returns Authorization_RequestDenied Even after successful authorization. Works on subsequent retry
My application accesses the directoryRoles resource via Microsoft Graph. This is done immediately after the Admin authorizes my client with the required scopes.

Usually, this flow works fine and calls to /directoryRoles returns a successful response. Intermittently, however, my application receives the following error:

```<code>{
  'error': {
    'innerError': {'date': '2020-02-18T20:06:49', 'request-id': <request_id>},
    'message': 'Insufficient privileges to complete the operation.',
    'code': u'Authorization_RequestDenied'
  }
}
</code>```

This happens even when the Admin has provided necessary authorization. I've also observed that in such cases, a retry after some time (say a min or two) returns success response.

Does this mean that it could take some random amount of time, spanning up to a minute or two, on the O365/Azure side to record the Admin's authorization for this resource?

Could there be some other explanation for such behavior?

Is retrying the API only solution in this case?

Would you have any other recommendations?

Appreciate any insight you could provide that would help me understand these intermittent errors.

答: Depending on the tenant's size and current load, it can sometimes take a moment or two for Azure AD to propagate consent for your application. This is normal and you should retry the request.</p>

Body:
My application accesses the directoryRoles resource via Microsoft Graph. This is done immediately after the Admin authorizes my client with the required scopes.

Usually, this flow works fine and calls to /directoryRoles returns a successful response. Intermittently, however, my application receives the following error:

{
  'error': {
    'innerError': {'date': '2020-02-18T20:06:49', 'request-id': <request_id>},
    'message': 'Insufficient privileges to complete the operation.',
    'code': u'Authorization_RequestDenied'
  }
}

This happens even when the Admin has provided necessary authorization. I've also observed that in such cases, a retry after some time (say a min or two) returns success response.

Does this mean that it could take some random amount of time, spanning up to a minute or two, on the O365/Azure side to record the Admin's authorization for this resource?

Could there be some other explanation for such behavior?

Is retrying the API only solution in this case?

Would you have any other recommendations?

Appreciate any insight you could provide that would help me understand these intermittent errors.


问:
Once I create a web app using Django + Python can I alter models?
If I am creating my first python web app using Django, am I able to at a later date, edit/change up models/views and have the program do so accordingly? Do I have to run a specific command to update my web app? Or Do I need to create the web application the way I want too right away?

I have been trying to google this, but am unable to come to a concrete answer. I am just using tutorials, but will want to add my own features at a later date, and want to make sure I do not need to create another app for example. Please remember, I am still fairly new.

答:
You can alter models.  Then you should use manage.py makemigrations to construct migrations which reflect the changes you made.  Use manage.py migrate to then apply the changes to the database.

It's important to notice that "this is the way it works."  You build your models, then make migrations both to initially create the corresponding tables and to make any subsequent changes to them.  (It is also possible to scrape from an existing database.)


问:
How to know if a project is spring boot or not
I went through a project structure in STS where I could see a MVC pattern where controller, service,Dao , entity classes were there. But looking at pom.xml got to know that it is a web application project. But how to confirm that it is not a spring boot application..?
I m new to spring boot. All I found is there were no starter dependencies in pom.xml or any dependency has word "boot" & there was not a main method where a spring boot project starts.
So my question is which particular dependency/ parameters differentiates spring boot application from a non spring boot application ?</p>

答:
In general in the first part of the pom.xml you can see this tag:</p>

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7.RELEASE</version>
    <relativePath />
    <!-- lookup parent from repository -->
</parent>
</code>```

Body:
In general in the first part of the pom.xml you can see this tag:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7.RELEASE</version>
    <relativePath />
    <!-- lookup parent from repository -->
</parent>


问:
check if email exsite in txt file using PHP
I'm using this code to check if the entered email is existe or not in text file

```<code>$handle = fopen("http://mywebsite/u.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = preg_replace('/\s+/', ' ', $line);
        if($line=$email){
            echo "email existe";
        }
    }

    fclose($handle);
} else {
    // error opening the file.
}
</code>```

the output is the same for exsiting emails and not exsiting email in the text file

email existeemail existeemail existe

the text file contains as a test emails

test@test.com

hello@world.com

test@t.com

if i did == it didn't enter the condition when the $line = $email

trying with

```<code>echo $line." ".$email;
</code>```

OUTPUT

test@test.com test@test.comtest@test.com test@test.comtest@test.com
  test@test.com

答:
I don't know if I understood you correctly, but here you have a slightly different solution to the problem

// File from http
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$handle = curl_exec($ch);
curl_close($ch);

// or
$handle = file_get_contents("u.txt");
//or
$handle = "test@test.com \n hello@world.com";

$find = "hello@world.com";

if (strpos($handle, $find) > -1){
    echo "Found" ;
} else{
    echo "Not Found";
}

```

Body:
I'm using this code to check if the entered email is existe or not in text file

$handle = fopen("http://mywebsite/u.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = preg_replace('/\s+/', ' ', $line);
        if($line=$email){
            echo "email existe";
        }
    }

    fclose($handle);
} else {
    // error opening the file.
}

the output is the same for exsiting emails and not exsiting email in the text file

email existeemail existeemail existe

the text file contains as a test emails

test@test.com

hello@world.com

test@t.com

if i did == it didn't enter the condition when the $line = $email

trying with

echo $line." ".$email;

OUTPUT

test@test.com test@test.comtest@test.com test@test.comtest@test.com
  test@test.com