问:
Error when passing setState in a React class component to an external function?
Assume data has already been cached in sessionStorage. I have hydrateStateWithSessionStorage in an external CacheService.js file. I import this file. When I try to pass this.setState to this function, I get this error:

Uncaught TypeError: Cannot read property 'updater' of undefined

How can I solve this? I could possibly use a the React hook useState and pass the setter function, but what if I want to use a class component instead of functional component? Or am I simply unable to pass setState because it implicitly uses the 'this' keyword in its implementation?

```<code>   hydrateStateWithSessionStorage(state, setState) {
    // for all items in state
    for (let key in state) {

        // if the key exists in localStorage
        if (sessionStorage.hasOwnProperty(key)) {
            // get the key's value from localStorage
            let value = sessionStorage.getItem(key);
            // console.log(value)
            // parse the localStorage string and setState
            try {
                value = JSON.parse(value);
                console.log('before')
                setState({ [key]: value });
                console.log('after')
            } catch (e) {
                // handle empty string
                setState({ [key]: value });
            }
        }
    }
}

//in the component consuming CacheService
//this.Cache = new CacheService(); //in the constructor

componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this.state, this.setState);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}
</code>```

答:
I would treat this function more of a check return sessionStorage  object if nothing return undefined. Send this.state into the fn() then check response and return the response.

```<code>componentDidMount() {
 const newState = hydrateState(this.state):

 !!newState && this.setState(newState)
}
</code>```

Just a brain dump..

Body:
Assume data has already been cached in sessionStorage. I have hydrateStateWithSessionStorage in an external CacheService.js file. I import this file. When I try to pass this.setState to this function, I get this error:

Uncaught TypeError: Cannot read property 'updater' of undefined

How can I solve this? I could possibly use a the React hook useState and pass the setter function, but what if I want to use a class component instead of functional component? Or am I simply unable to pass setState because it implicitly uses the 'this' keyword in its implementation?

   hydrateStateWithSessionStorage(state, setState) {
    // for all items in state
    for (let key in state) {

        // if the key exists in localStorage
        if (sessionStorage.hasOwnProperty(key)) {
            // get the key's value from localStorage
            let value = sessionStorage.getItem(key);
            // console.log(value)
            // parse the localStorage string and setState
            try {
                value = JSON.parse(value);
                console.log('before')
                setState({ [key]: value });
                console.log('after')
            } catch (e) {
                // handle empty string
                setState({ [key]: value });
            }
        }
    }
}

//in the component consuming CacheService
//this.Cache = new CacheService(); //in the constructor

componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this.state, this.setState);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}

Body:
I would treat this function more of a check return sessionStorage  object if nothing return undefined. Send this.state into the fn() then check response and return the response.

componentDidMount() {
 const newState = hydrateState(this.state):

 !!newState && this.setState(newState)
}

Just a brain dump..


来源: stackexchange

问:
Python argument missed if I pass $ inside string as input parameter
I am trying to pass some shell cmd into one of my python script so that I can run them toward hosts. However, when I pass them into the line, the $ is omitted for some reason. How can I avoid this?

I use parser and setup like this:

parser = argparse.ArgumentParser(description='check size', add_help=True)
parser.add_argument('-c', "--cmd", dest="cmd",type=str, help="Command to run Ex: df -h /boot/|grep -i boot|awk '{print \$4}' 2>/dev/null ")
```

<p>Ex:
This is working with a backslash</p>

```python3.4 disk_file_check.py -e env -op chksize -c "df -h /boot/|grep -i boot|awk {'print \$4'} 2>/dev/null"
```

<p>since anybody can use this script and all they should pass is just the command they want to use. but I want it works like this:</p>

```python3.4 disk_file_check.py -e env -op chksize -c "df -h /boot/|grep -i boot|awk {'print $4'} 2>/dev/null"
```

<p>But when I do this, The string is turned into: </p>

```df -h /boot/|grep -i boot|awk '{print }' 2>/dev/null

```

As you can see $ is cutting out and give me wrong result...

Any possible setting in argparse can do it?  or I should try diff way? Thanks

答: Thanks. I think I will not pass this through command line since shell exapnd it. Thanks for pointing that out.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to pass some shell cmd into one of my python script so that I can run them toward hosts. However, when I pass them into the line, the $ is omitted for some reason. How can I avoid this?

I use parser and setup like this:

parser = argparse.ArgumentParser(description='check size', add_help=True)
parser.add_argument('-c', "--cmd", dest="cmd",type=str, help="Command to run Ex: df -h /boot/|grep -i boot|awk '{print \$4}' 2>/dev/null ")

Ex:
This is working with a backslash

python3.4 disk_file_check.py -e env -op chksize -c "df -h /boot/|grep -i boot|awk {'print \$4'} 2>/dev/null"

since anybody can use this script and all they should pass is just the command they want to use. but I want it works like this:

python3.4 disk_file_check.py -e env -op chksize -c "df -h /boot/|grep -i boot|awk {'print $4'} 2>/dev/null"

But when I do this, The string is turned into:

df -h /boot/|grep -i boot|awk '{print }' 2>/dev/null

As you can see $ is cutting out and give me wrong result...

Any possible setting in argparse can do it?  or I should try diff way? Thanks


问:
How to combine multiple rows with multiple joins from multiple tables in mysql
I'm attempting to combine multiple rows into individual rows with multiple columns, where the data is from three tables. I followed the suggestions in MySQL pivot table but the question and answers do not account for multiple joins.

Here are the underlying tables:

```<code>table n
+------+----+------+
| name | id | code |
+------+----+------+
| foo  |  1 | NULL |
| bar  |  2 | z    |
| baz  |  3 | y    |
+------+----+------+

table ac
+------+----+
| code | id |
+------+----+
| h    |  1 |
| i    |  2 |
+------+----+

table c
+-----+------+-------+
| cid | code | desc  |
+-----+------+-------+
|   9 | h    | desch |
|   9 | i    | desci |
|   8 | z    | descz |
|   8 | y    | descy |
+-----+------+-------+
</code>```

Here are the expected results:

```<code>+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | desch |
| bar  | descz | desci |
| baz  | descy | null  |
+------+-------+-------+
</code>```

I can get pretty close to the results I want with:

```<code>select
n.name,
n.code as type8,
ac.code as type9
from n
left join ac
on ac.id=n.id
</code>```

but as expected, this yields the codes only:

```<code>+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | h     |
| bar  | z     | i     |
| baz  | y     | null  |
+------+-------+-------+
</code>```

and I'm interested in replacing the codes with the longer descriptions from table c.

答:
The first step is to use case to return multiple columns of data from multiple rows within the same table using the technique from pivot tables in mysql:

```<code>select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join c
on n.code=c.code
</code>```

This yields the correct results for type8 but nulls for type9:

```<code>+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | null  |
| bar  | descz | null  |
| baz  | descy | null  |
+------+-------+-------+
</code>```

The next step is to get the results for type9:

```<code>select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join ac
on ac.id=n.id
left join c
on c.code=ac.code
</code>```

This yields:

```<code>+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | desch |
| bar  | null  | desci |
| baz  | null  | null  |
+------+-------+-------+
</code>```

If these two results are unioned together with

```<code>select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join c
on n.code=c.code

union

select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join ac
on ac.id=n.id
left join c
on c.code=ac.code
</code>```

the rows still need to be combined:

```<code>+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| bar  | descz | null  |
| baz  | descy | null  |
| foo  | null  | null  |
| foo  | null  | desch |
| bar  | null  | desci |
| baz  | null  | null  |
+------+-------+-------+
</code>```

Finally, I was able to achieve the expected results by using the aggregating technique for removing nulls from a unioned query:

```<code>select
n.name,
min(type8), min(type9)
from
(select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join c
on n.code=c.code

union
select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join ac
on ac.id=n.id
left join c
on c.code=ac.code) as n
group by n.name
</code>```

which yields the results as expected:

```<code>+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | desch |
| bar  | descz | desci |
| baz  | descy | null  |
+------+-------+-------+
</code>```

Body:
I'm attempting to combine multiple rows into individual rows with multiple columns, where the data is from three tables. I followed the suggestions in MySQL pivot table but the question and answers do not account for multiple joins.

Here are the underlying tables:

table n
+------+----+------+
| name | id | code |
+------+----+------+
| foo  |  1 | NULL |
| bar  |  2 | z    |
| baz  |  3 | y    |
+------+----+------+

table ac
+------+----+
| code | id |
+------+----+
| h    |  1 |
| i    |  2 |
+------+----+

table c
+-----+------+-------+
| cid | code | desc  |
+-----+------+-------+
|   9 | h    | desch |
|   9 | i    | desci |
|   8 | z    | descz |
|   8 | y    | descy |
+-----+------+-------+

Here are the expected results:

+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | desch |
| bar  | descz | desci |
| baz  | descy | null  |
+------+-------+-------+

I can get pretty close to the results I want with:

select
n.name,
n.code as type8,
ac.code as type9
from n
left join ac
on ac.id=n.id

but as expected, this yields the codes only:

+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | h     |
| bar  | z     | i     |
| baz  | y     | null  |
+------+-------+-------+

and I'm interested in replacing the codes with the longer descriptions from table c.

Body:
The first step is to use case to return multiple columns of data from multiple rows within the same table using the technique from pivot tables in mysql:

select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join c
on n.code=c.code

This yields the correct results for type8 but nulls for type9:

+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | null  |
| bar  | descz | null  |
| baz  | descy | null  |
+------+-------+-------+

The next step is to get the results for type9:

select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join ac
on ac.id=n.id
left join c
on c.code=ac.code

This yields:

+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | desch |
| bar  | null  | desci |
| baz  | null  | null  |
+------+-------+-------+

If these two results are unioned together with

select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join c
on n.code=c.code

union

select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join ac
on ac.id=n.id
left join c
on c.code=ac.code

the rows still need to be combined:

+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| bar  | descz | null  |
| baz  | descy | null  |
| foo  | null  | null  |
| foo  | null  | desch |
| bar  | null  | desci |
| baz  | null  | null  |
+------+-------+-------+

Finally, I was able to achieve the expected results by using the aggregating technique for removing nulls from a unioned query:

select
n.name,
min(type8), min(type9)
from
(select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join c
on n.code=c.code

union
select
n.name,
case when c.cid=8 then c.desc end as type8,
case when c.cid=9 then c.desc end as type9
from n
left join ac
on ac.id=n.id
left join c
on c.code=ac.code) as n
group by n.name

which yields the results as expected:

+------+-------+-------+
| name | type8 | type9 |
+------+-------+-------+
| foo  | null  | desch |
| bar  | descz | desci |
| baz  | descy | null  |
+------+-------+-------+


问:
Foreach-object returning 'cannot index into a null array', but works fine when I copy each line of the loop
I have a script that I've been conceptualizing and it sort of became centered around this idea of throwing lining up arrays into hash tables, and then call on them with a foreach-object $_ index in order to run through a command or output, with the least amount of redundant code written.

I have tried this idea so many different times, it just doesn't seem to work. Not sure if I'm just being rather dumb, or if there's something else I'm missing here.

I'm able to get other hash tables and arrays to work with this method, but this one is giving me problems.

i'll break it down.

```<code>The first array will be the first line
The second array will be the 2nd line...
so on and so forth until the 6th.
</code>```

each line has several values, but each of those values that correspond to the same item as the one above and below it... think of an excel spreadsheet... sort of like that.

at the end of this array/hashtable, I try to collect each one into...

```<code>$control = ( 0..5 | % { first[$_] ; second[$_] ; third[$_] ; fourth[$_] ; fifth[$_] ; sixth[$_] } )
</code>```

I've tried every permutation I can think of, with an at sign, without one, throwing control into the curlies, using parenthesis instead of curlies, using commas, this just doesn't seem to want to work. I have also tried placing an empty control=() before doing the loop by itself, nothing seems to work... I can't seem to get away from this error "index outside the bounds of the array"

...and just when I think I've gotten it to work, I call on the variable and it's empty. Nada.

So for now, this seems to work, but it sucks...

```<code>$Control = @{ 0 = ( $first[0] , $second[0] , $third[0] , $fourth[0] , $fifth[0] );
              1 = ( $first[1] , $second[1] , $third[1] , $fourth[1] , $fifth[1] );
              2 = ( $first[2] , $second[2] , $third[2] , $fourth[2] , $fifth[2] );
              3 = ( $first[3] , $second[3] , $third[3] , $fourth[3] , $fifth[3] );
              4 = ( $first[4] , $second[4] , $third[4] , $fourth[4] , $fifth[4] );
              5 = ( $first[5] , $second[5] , $third[5] , $fourth[5] , $fifth[5] );
              6 = ( $first[6] , $second[6] , $third[6] , $fourth[6] , $fifth[6] )}
</code>```

I'm looking to do this with the least amount of code, i'm just not sure why this one doesn't work.

By the way, if I call on $control[0] or what have you after the fact, the desired end result is to print those variables to the screen ........

Index was outside the bounds of the array. x5 thousand times...

答:
I figured it out.

```<code>$control=@( 0..5 )

0..5 | % { $control[$_]=@($first[$_];$second[$_];$third[$_];$fourth[$_];$fifth[$_])}
</code>```

can't believe it took me that long to realize I had to put the array into the empty field above... im glad i solved it but feel silly for not trying that sooner.

Body:
I have a script that I've been conceptualizing and it sort of became centered around this idea of throwing lining up arrays into hash tables, and then call on them with a foreach-object $_ index in order to run through a command or output, with the least amount of redundant code written.

I have tried this idea so many different times, it just doesn't seem to work. Not sure if I'm just being rather dumb, or if there's something else I'm missing here.

I'm able to get other hash tables and arrays to work with this method, but this one is giving me problems.

i'll break it down.

The first array will be the first line
The second array will be the 2nd line...
so on and so forth until the 6th.

each line has several values, but each of those values that correspond to the same item as the one above and below it... think of an excel spreadsheet... sort of like that.

at the end of this array/hashtable, I try to collect each one into...

$control = ( 0..5 | % { first[$_] ; second[$_] ; third[$_] ; fourth[$_] ; fifth[$_] ; sixth[$_] } )

I've tried every permutation I can think of, with an at sign, without one, throwing control into the curlies, using parenthesis instead of curlies, using commas, this just doesn't seem to want to work. I have also tried placing an empty control=() before doing the loop by itself, nothing seems to work... I can't seem to get away from this error "index outside the bounds of the array"

...and just when I think I've gotten it to work, I call on the variable and it's empty. Nada.

So for now, this seems to work, but it sucks...

$Control = @{ 0 = ( $first[0] , $second[0] , $third[0] , $fourth[0] , $fifth[0] );
              1 = ( $first[1] , $second[1] , $third[1] , $fourth[1] , $fifth[1] );
              2 = ( $first[2] , $second[2] , $third[2] , $fourth[2] , $fifth[2] );
              3 = ( $first[3] , $second[3] , $third[3] , $fourth[3] , $fifth[3] );
              4 = ( $first[4] , $second[4] , $third[4] , $fourth[4] , $fifth[4] );
              5 = ( $first[5] , $second[5] , $third[5] , $fourth[5] , $fifth[5] );
              6 = ( $first[6] , $second[6] , $third[6] , $fourth[6] , $fifth[6] )}

I'm looking to do this with the least amount of code, i'm just not sure why this one doesn't work.

By the way, if I call on $control[0] or what have you after the fact, the desired end result is to print those variables to the screen ........

Index was outside the bounds of the array. x5 thousand times...

Body:
I figured it out.

$control=@( 0..5 )

0..5 | % { $control[$_]=@($first[$_];$second[$_];$third[$_];$fourth[$_];$fifth[$_])}

can't believe it took me that long to realize I had to put the array into the empty field above... im glad i solved it but feel silly for not trying that sooner.


问:
How to use CSS counter increment for dynamic page numbers
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="SetupMainTable">
  <thead>
    <tr>
       <td colspan="4">Company Name</td>
       <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
       <td colspan="1"><div class="page-number"></div></td>
    </tr>
  </thead>
</table>  </code>```

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

答:
Apply counter-reset: page; to the parent element that holds all of the page number elements. Also note, that based on your snippet, it appears you want .page-number (class), not #page-number (id). id attributes are unique throughout the document, while class attributes can be repeated the same identifier.

table {
  text-align: center;
  counter-reset: page;
}

.large-font {
  font-size: 25px;
}

@media screen {
  .page-number:before {
    counter-increment: page;
    content: "Page " counter(page);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td colspan="4">Company Name</td>
    <td colspan="5" class="right large-font">Daily Time Ticket</td>
    <td colspan="1">
      <div class="page-number"></div>
    </td>
  </tr>
  <tr>
    <td colspan="4">Company Name</td>
    <td colspan="5" class="right large-font">Daily Time Ticket</td>
    <td colspan="1">
      <div class="page-number"></div>
    </td>
  </tr>
  <tr>
    <td colspan="4">Company Name</td>
    <td colspan="5" class="right large-font">Daily Time Ticket</td>
    <td colspan="1">
      <div class="page-number"></div>
    </td>
  </tr>
</table></code>```

Body:
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }

       Company Name
       Daily Time Ticket

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

Body:
Apply counter-reset: page; to the parent element that holds all of the page number elements. Also note, that based on your snippet, it appears you want .page-number (class), not #page-number (id). id attributes are unique throughout the document, while class attributes can be repeated the same identifier.

table {
  text-align: center;
  counter-reset: page;
}

.large-font {
  font-size: 25px;
}

@media screen {
  .page-number:before {
    counter-increment: page;
    content: "Page " counter(page);
  }
}

<table>
  <tr>
    <td colspan="4">Company Name</td>
    <td colspan="5" class="right large-font">Daily Time Ticket</td>
    <td colspan="1">
      <div class="page-number"></div>
    </td>
  </tr>
  <tr>
    <td colspan="4">Company Name</td>
    <td colspan="5" class="right large-font">Daily Time Ticket</td>
    <td colspan="1">
      <div class="page-number"></div>
    </td>
  </tr>
  <tr>
    <td colspan="4">Company Name</td>
    <td colspan="5" class="right large-font">Daily Time Ticket</td>
    <td colspan="1">
      <div class="page-number"></div>
    </td>
  </tr>
</table>


问:
Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method failed
We have recently upgraded our MVC3 application to MVC5 (rather, we are attempting to do so now).

The application runs successfully on some machines, but not mine. It also won't run on the web server.

I have compared the versions of the System.Web.* dlls with those on the working machine and they appear to be the same.

I have also followed the fixes from the other threads I found, with to no avail. I will have to search again to find those that I tried, but here is the first one that I remember.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

What else would I need to change/update to prevent this problem?

Here is the error and stack trace:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:

```<code>System.MethodAccessException: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed.
</code>```

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

```<code>[MethodAccessException: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed.]
   System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule() +96
   System.Web.WebPages.Administration.PreApplicationStartCode.Start() +41

[InvalidOperationException: The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +547
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +521

[HttpException (0x80004005): The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9931916
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
</code>```

UPDATE

Here is some info from my web.config

```<code><compilation debug="true" targetFramework="4.5.2">
  <assemblies>
    <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  ...
 </assemblies>
</compilation>
<runtime>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Data" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Xml" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Windows.Forms" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Drawing" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Services" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Abstractions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Routing" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Deployment" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
</assemblyBinding>
</code>```

答: for me, I solved it by removing the reference for System.Web.Administration.dll in the project. This site, pointed me to the right direction https://codedump.io/share/d2rw80bGmlwc/1/methodaccessexception-inside-systemwebwebpages-migrating-mvc-3-to-mvc-5</p>

ContentLicense: CC BY-SA 3.0

Body:
We have recently upgraded our MVC3 application to MVC5 (rather, we are attempting to do so now).

The application runs successfully on some machines, but not mine. It also won't run on the web server.

I have compared the versions of the System.Web.* dlls with those on the working machine and they appear to be the same.

I have also followed the fixes from the other threads I found, with to no avail. I will have to search again to find those that I tried, but here is the first one that I remember.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

What else would I need to change/update to prevent this problem?

Here is the error and stack trace:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:

System.MethodAccessException: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[MethodAccessException: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed.]
   System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule() +96
   System.Web.WebPages.Administration.PreApplicationStartCode.Start() +41

[InvalidOperationException: The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +547
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +521

[HttpException (0x80004005): The pre-application start initialization method Start on type System.Web.WebPages.Administration.PreApplicationStartCode threw an exception with the following error message: Attempt by security transparent method 'System.Web.WebPages.Administration.SiteAdmin.RegisterAdminModule()' to access security critical method 'System.Web.WebPages.ApplicationPart..ctor(System.Reflection.Assembly, System.String)' failed..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9931916
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

UPDATE

Here is some info from my web.config

<compilation debug="true" targetFramework="4.5.2">
  <assemblies>
    <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  ...
 </assemblies>
</compilation>
<runtime>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Data" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Xml" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Windows.Forms" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Drawing" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Services" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Abstractions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Routing" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Deployment" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
</assemblyBinding>


问:
When I use my php post function, It deletes my session cookie without my control
I set a user cookie when my user logs in to the page and it works correctly. Also, I put a script to all my pages to check cookies. But when I use a php post script, my cookie is being deleted and system automatically send me back to login page. Have you got any idea about that situation?

I have tried to set cookie again in my post.php scripts but it doesn't work.

'

```<code><?php
    include 'config.php';

$blok_header = filter_input(INPUT_POST,'blok_header');
$blok_text = filter_input(INPUT_POST,'blok_text');
$Sayfa_Linkleri = filter_input(INPUT_POST,'Sayfa_Linkleri');

$sl = $_GET["Sayfa_Linkleri"];
    // Veritabanına Ekleyelim.

$guncelle = mysqli_query($conn,"UPDATE example_table
  SET blok_header = '$blok_header' , blok_text = '$blok_text', Sayfa_Linkleri = '$Sayfa_Linkleri' ,guncelle = '$now'
  WHERE Sayfa_Linkleri='$sl'") ;

if($guncelle){
      header("location: http://example.com/example-admin/admin/example_edit.php?Sayfa_Linkleri=".$sl);
}
else{
    echo "Bir Sorun Oluştu";
}
?>
</code>```

'

```<code><?php
</code>```

if(htmlspecialchars($_COOKIE["kullanici"]) == null)
{

```<code>header("refresh:1;url=http://www.example.com/example-admin");
</code>```

}
?>

答:
```<code><?php
include 'config.php';
</code>```

if($_SERVER["REQUEST_METHOD"] == "POST") {

```<code>  $myusername = mysqli_real_escape_string($conn,$_POST['username']);
  $mypassword = mysqli_real_escape_string($conn,$_POST['password']);

  $sql = "SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
  $result = mysqli_query($conn,$sql);
  $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
  $active = $row['active'];

  $count = mysqli_num_rows($result);

  $cookie_name = "kullanici";
  $cookie_value = $myusername;

  if($count == 1) {
     header("location: admin/");
     echo"<div class=\"alert\">
     <span class=\"closebtn\" onclick=\"this.parentElement.style.display='none';\">×</span>
     <strong>Hoşgeldiniz!</strong> Giriş başarılı.
   </div>";
   setcookie($cookie_name, $cookie_value, time() + (86400), "/");
  }else {
     header("location: index.php");
     echo"<div class=\"alert\">
     <span class=\"closebtn\" onclick=\"this.parentElement.style.display='none';\">×</span>
     <strong>Hata</strong> Kullanıcı adı veya şifre hatalı.
   </div>";
  }
</code>```

}
?>

Body:
I set a user cookie when my user logs in to the page and it works correctly. Also, I put a script to all my pages to check cookies. But when I use a php post script, my cookie is being deleted and system automatically send me back to login page. Have you got any idea about that situation?

I have tried to set cookie again in my post.php scripts but it doesn't work.

'

<?php
    include 'config.php';

$blok_header = filter_input(INPUT_POST,'blok_header');
$blok_text = filter_input(INPUT_POST,'blok_text');
$Sayfa_Linkleri = filter_input(INPUT_POST,'Sayfa_Linkleri');

$sl = $_GET["Sayfa_Linkleri"];
    // Veritabanına Ekleyelim.

$guncelle = mysqli_query($conn,"UPDATE example_table
  SET blok_header = '$blok_header' , blok_text = '$blok_text', Sayfa_Linkleri = '$Sayfa_Linkleri' ,guncelle = '$now'
  WHERE Sayfa_Linkleri='$sl'") ;

if($guncelle){
      header("location: http://example.com/example-admin/admin/example_edit.php?Sayfa_Linkleri=".$sl);
}
else{
    echo "Bir Sorun Oluştu";
}
?>

'

<?php

if(htmlspecialchars($_COOKIE["kullanici"]) == null)
{

header("refresh:1;url=http://www.example.com/example-admin");

}
?>

Body:
<?php
include 'config.php';

if($_SERVER["REQUEST_METHOD"] == "POST") {

  $myusername = mysqli_real_escape_string($conn,$_POST['username']);
  $mypassword = mysqli_real_escape_string($conn,$_POST['password']);

  $sql = "SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
  $result = mysqli_query($conn,$sql);
  $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
  $active = $row['active'];

  $count = mysqli_num_rows($result);

  $cookie_name = "kullanici";
  $cookie_value = $myusername;

  if($count == 1) {
     header("location: admin/");
     echo"<div class=\"alert\">
     <span class=\"closebtn\" onclick=\"this.parentElement.style.display='none';\">&times;</span>
     <strong>Hoşgeldiniz!</strong> Giriş başarılı.
   </div>";
   setcookie($cookie_name, $cookie_value, time() + (86400), "/");
  }else {
     header("location: index.php");
     echo"<div class=\"alert\">
     <span class=\"closebtn\" onclick=\"this.parentElement.style.display='none';\">&times;</span>
     <strong>Hata</strong> Kullanıcı adı veya şifre hatalı.
   </div>";
  }

}
?>


问:
Laravel 504 gateway timeout
I have a script in Laravel platform which process thousands of records , and it's timing out issue. I want to avoid update settings on server like php.ini file.

Is there any way to chunk all records in small pieces and use them in further processing until all records will be used.

I have thousands of records which are getting Price from another server.

So,

1-10 records works fine.

1-100 records works fine.

More than 500 records script stuck and gives error like below.

405 nginx server not allowed

My Route is like :-  example.com/updateAllKeywords

Below code is getting keyword to fetch keywords'price from eBay API

```<code>        $keywordCollection = Keywords::all();

        Keywords::chunk(100, function ($keywordCollection) use($request,$keywordCollection,$defaultStartDate,$ignoredItems,$response) {
            foreach ($keywordCollection->toArray() as $keyword_result) {
                $response = $this->apirequest($request, $keyword_result['id'], $keyword_result, $defaultStartDate, $ignoredItems);
            }
        });
</code>```

This is api request function:

```<code> /**
 * Call Finding API for Active List items
 *
 * @return API Response
 */
public function apirequest(Request $request, $id, $keyword_result, $defaultStartDate, $ignoredItems) {

    try {

        /* Request */
        $request = new Types\FindItemsAdvancedRequest();

        /* 1) default 100 items being displayed without pagination */
        $request->paginationInput = new Types\PaginationInput();
        $request->paginationInput->entriesPerPage = Config::get('constants.paginationoptions.entries_per_page');

        /* 2) ItemFilter for three conditions NEW ,NEWOTHER,USED */
        $itemFilterForConditions = new Types\ItemFilter();
        $itemFilterForConditions->name = 'Condition';
        $itemFilterForConditions->value = ['1000', '1500', '3000'];

        /* 3) ItemFilter for hide duplicate items */
        $itemFilterduplicate = new Types\ItemFilter();
        $itemFilterduplicate->name = 'HideDuplicateItems';
        $itemFilterduplicate->value[] = 'true';

        /* 4) pull items before given date / days */
        $itemFilterStartDateFrom = new Types\ItemFilter();
        $itemFilterStartDateFrom->name = 'StartTimeFrom';
        $itemFilterStartDateFrom->value[] = date('Y-m-d\TH:i:s\Z', mktime(0, 0, 0, date('m'), date('d') - $defaultStartDate['defaultStartDate'], date('y')));

        /* Exclude Keywords/MPN by set Priced Percentage */
        if (!empty($keyword_result['price']) && ($defaultStartDate['exclusionPercentage'] > 0)) {
            $percentageAmount = $keyword_result['price'] * ($defaultStartDate['exclusionPercentage'] / 100);
            $percentageAmount = floor($percentageAmount).substr($percentageAmount-floor($percentageAmount),1,2+1);
            $itemFilterPriced = new Types\ItemFilter();
            $itemFilterPriced->name = 'MinPrice';
            $itemFilterPriced->value[] = $percentageAmount;
        }

        $itemFilter = (isset($itemFilterPriced)) ? [$itemFilterForConditions, $itemFilterduplicate, $itemFilterStartDateFrom, $itemFilterPriced] : [$itemFilterForConditions, $itemFilterduplicate, $itemFilterStartDateFrom];

        $request->itemFilter = $itemFilter;

        /* 5) Request KEYWORD/MPN to filter Items Active Lists */
        $searchKeyword = (!empty($keyword_result['exclusions'])) ? $keyword_result['keyword'] . " -" . "(" . trim($keyword_result['exclusions']) . ")" : $keyword_result['keyword'];
        $request->keywords = $searchKeyword;

        /* 6) Request For sorting Items by Lowest To Highest Itemprice Price + Shipping Price */
        $request->sortOrder = 'PricePlusShippingLowest';

        /* 7) Request For Keyword Search Including the Item Descriptions,Title and Subtitle */
        $request->descriptionSearch = ($defaultStartDate['advancedExclusions'] == 1) ? true : false;

        $service = $this->index();

        /* Response returned by $request */
        $response = $this->apiresponse($request, $service, $id, $keyword_result['keyword'], $ignoredItems);

        return $response;

    } catch (\Exception $e) {
        echo json_encode(array('ack' => 'Failure', 'msg' => $e->getMessage()));
        exit;
    }
}

public function apiresponse($request, $service, $id, $keyword, $ignoredItems) {

            try {

                $response = $service->findItemsAdvanced($request);

                /* fetch all ignored Items */

                $newItems = array();
                $newOtherItems = array();
                $usedItems = array();
                $errors = "";

                if ($response->ack == "Success") {
                    $results = $response->searchResult->item;

                    ob_start();

                    foreach ($results as $item) {

                        if ($item->listingInfo->buyItNowAvailable == '1') {
                            $itemPrice = $item->listingInfo->buyItNowPrice->value;
                        } elseif (($item->listingInfo->listingType == 'Auction') && ($item->sellingStatus->currentPrice->value == 0)) {
                            $itemResponse = $this->getItemDetails($item->itemId);
                            $itemPrice = isset($itemResponse) ? $itemResponse : 0;
                        } else {
                            $itemPrice = $item->sellingStatus->currentPrice->value;
                        }

                        /* check for ignored items */
                        if (!in_array($item->itemId, $ignoredItems)) {

                            /* check for NEW Condition (conditionId = 1000) */
                            if ($item->condition->conditionId == '1000') {
                                $newItems[] = array(
                                    'keywordId' => $id,
                                    'conditionId' => (string) $item->condition->conditionId,
                                    'itemId' => $item->itemId,
                                    'title' => $item->title,
                                    'price' => $itemPrice,
                                    'itemURL' => $item->viewItemURL,
                                    'galleryURL' => isset($item->galleryURL) ? $item->galleryURL : '',
                                );
                            }
                            /* check for NEW OTHER Condition (conditionId = 1500) */ elseif ($item->condition->conditionId == '1500') {
                                $newOtherItems[] = array(
                                    'keywordId' => $id,
                                    'conditionId' => (string) $item->condition->conditionId,
                                    'itemId' => $item->itemId,
                                    'title' => $item->title,
                                    'price' => $itemPrice,
                                    'itemURL' => $item->viewItemURL,
                                    'galleryURL' => isset($item->galleryURL) ? $item->galleryURL : '',
                                );
                            }
                            /* check for USED Condition (conditionId = 3000) */ elseif ($item->condition->conditionId == '3000') {
                                $usedItems[] = array(
                                    'keywordId' => $id,
                                    'conditionId' => (string) $item->condition->conditionId,
                                    'itemId' => $item->itemId,
                                    'title' => $item->title,
                                    'price' => $itemPrice,
                                    'itemURL' => $item->viewItemURL,
                                    'galleryURL' => isset($item->galleryURL) ? $item->galleryURL : '',
                                );
                            }
                        }

                        ob_flush();
                    }

                    $newItems = array_slice($newItems, 0, 20);
                    $newOtherItems = array_slice($newOtherItems, 0, 20);
                    $usedItems = array_slice($usedItems, 0, 20);

                    $insertItems = array_merge($newItems, $newOtherItems, $usedItems);

                    /* clean up items */
                    Items::where('keywordId', $id)->delete();

                    /* save pulled items */
                    $items = Items::insert($insertItems);
                } elseif ($response->ack == "Failure") {
                    foreach ($response->errorMessage->error as $error) {
                        $errors .= "%s: %s\n\n" . $error->severity === Enums\ErrorSeverity::C_ERROR ? '<b>Error</b> ' : '<b>Warning</b> ' . $error->message;
                    }
                }

                /* save API log fot the keyword */
                $this->setapilog($request, $response, $keyword);

                if (!empty($errors)) {
                    echo json_encode(array('ack' => 'Failure', 'msg' => $errors));
                    exit;
                } else {
                    return true;
                }
            } catch (\Exception $e) {
                echo json_encode(array('ack' => 'Failure', 'msg' => $e->getMessage()));
                exit;
            }
        }
</code>```

Any information on this would be greatly appreciated. Thanks!

答:
Create this has a job Laravel Queues
Put your function in the handle method.

```<code>$response = $this->apiRequest(...);
</code>```

Dispatch your job from say your controller

```<code>foreach ($keywordCollection as $key => $keywordResult) {
   ProcessJob::dispatch($keywordResult)->delay($key * 2);
}
</code>```

This way you are implementing exponential backoff such that as your array increases you increase your wait time to make the next api request.

Title: Laravel 504 gateway timeout

Body:
I have a script in Laravel platform which process thousands of records , and it's timing out issue. I want to avoid update settings on server like php.ini file.

Is there any way to chunk all records in small pieces and use them in further processing until all records will be used.

I have thousands of records which are getting Price from another server.

So,

1-10 records works fine.

1-100 records works fine.

More than 500 records script stuck and gives error like below.

405 nginx server not allowed

My Route is like :-  example.com/updateAllKeywords

Below code is getting keyword to fetch keywords'price from eBay API

        $keywordCollection = Keywords::all();

        Keywords::chunk(100, function ($keywordCollection) use($request,$keywordCollection,$defaultStartDate,$ignoredItems,$response) {
            foreach ($keywordCollection->toArray() as $keyword_result) {
                $response = $this->apirequest($request, $keyword_result['id'], $keyword_result, $defaultStartDate, $ignoredItems);
            }
        });

This is api request function:

 /**
 * Call Finding API for Active List items
 *
 * @return API Response
 */
public function apirequest(Request $request, $id, $keyword_result, $defaultStartDate, $ignoredItems) {

    try {

        /* Request */
        $request = new Types\FindItemsAdvancedRequest();

        /* 1) default 100 items being displayed without pagination */
        $request->paginationInput = new Types\PaginationInput();
        $request->paginationInput->entriesPerPage = Config::get('constants.paginationoptions.entries_per_page');

        /* 2) ItemFilter for three conditions NEW ,NEWOTHER,USED */
        $itemFilterForConditions = new Types\ItemFilter();
        $itemFilterForConditions->name = 'Condition';
        $itemFilterForConditions->value = ['1000', '1500', '3000'];

        /* 3) ItemFilter for hide duplicate items */
        $itemFilterduplicate = new Types\ItemFilter();
        $itemFilterduplicate->name = 'HideDuplicateItems';
        $itemFilterduplicate->value[] = 'true';

        /* 4) pull items before given date / days */
        $itemFilterStartDateFrom = new Types\ItemFilter();
        $itemFilterStartDateFrom->name = 'StartTimeFrom';
        $itemFilterStartDateFrom->value[] = date('Y-m-d\TH:i:s\Z', mktime(0, 0, 0, date('m'), date('d') - $defaultStartDate['defaultStartDate'], date('y')));

        /* Exclude Keywords/MPN by set Priced Percentage */
        if (!empty($keyword_result['price']) && ($defaultStartDate['exclusionPercentage'] > 0)) {
            $percentageAmount = $keyword_result['price'] * ($defaultStartDate['exclusionPercentage'] / 100);
            $percentageAmount = floor($percentageAmount).substr($percentageAmount-floor($percentageAmount),1,2+1);
            $itemFilterPriced = new Types\ItemFilter();
            $itemFilterPriced->name = 'MinPrice';
            $itemFilterPriced->value[] = $percentageAmount;
        }

        $itemFilter = (isset($itemFilterPriced)) ? [$itemFilterForConditions, $itemFilterduplicate, $itemFilterStartDateFrom, $itemFilterPriced] : [$itemFilterForConditions, $itemFilterduplicate, $itemFilterStartDateFrom];

        $request->itemFilter = $itemFilter;

        /* 5) Request KEYWORD/MPN to filter Items Active Lists */
        $searchKeyword = (!empty($keyword_result['exclusions'])) ? $keyword_result['keyword'] . " -" . "(" . trim($keyword_result['exclusions']) . ")" : $keyword_result['keyword'];
        $request->keywords = $searchKeyword;

        /* 6) Request For sorting Items by Lowest To Highest Itemprice Price + Shipping Price */
        $request->sortOrder = 'PricePlusShippingLowest';

        /* 7) Request For Keyword Search Including the Item Descriptions,Title and Subtitle */
        $request->descriptionSearch = ($defaultStartDate['advancedExclusions'] == 1) ? true : false;

        $service = $this->index();

        /* Response returned by $request */
        $response = $this->apiresponse($request, $service, $id, $keyword_result['keyword'], $ignoredItems);

        return $response;

    } catch (\Exception $e) {
        echo json_encode(array('ack' => 'Failure', 'msg' => $e->getMessage()));
        exit;
    }
}

public function apiresponse($request, $service, $id, $keyword, $ignoredItems) {

            try {

                $response = $service->findItemsAdvanced($request);

                /* fetch all ignored Items */

                $newItems = array();
                $newOtherItems = array();
                $usedItems = array();
                $errors = "";

                if ($response->ack == "Success") {
                    $results = $response->searchResult->item;

                    ob_start();

                    foreach ($results as $item) {

                        if ($item->listingInfo->buyItNowAvailable == '1') {
                            $itemPrice = $item->listingInfo->buyItNowPrice->value;
                        } elseif (($item->listingInfo->listingType == 'Auction') && ($item->sellingStatus->currentPrice->value == 0)) {
                            $itemResponse = $this->getItemDetails($item->itemId);
                            $itemPrice = isset($itemResponse) ? $itemResponse : 0;
                        } else {
                            $itemPrice = $item->sellingStatus->currentPrice->value;
                        }

                        /* check for ignored items */
                        if (!in_array($item->itemId, $ignoredItems)) {

                            /* check for NEW Condition (conditionId = 1000) */
                            if ($item->condition->conditionId == '1000') {
                                $newItems[] = array(
                                    'keywordId' => $id,
                                    'conditionId' => (string) $item->condition->conditionId,
                                    'itemId' => $item->itemId,
                                    'title' => $item->title,
                                    'price' => $itemPrice,
                                    'itemURL' => $item->viewItemURL,
                                    'galleryURL' => isset($item->galleryURL) ? $item->galleryURL : '',
                                );
                            }
                            /* check for NEW OTHER Condition (conditionId = 1500) */ elseif ($item->condition->conditionId == '1500') {
                                $newOtherItems[] = array(
                                    'keywordId' => $id,
                                    'conditionId' => (string) $item->condition->conditionId,
                                    'itemId' => $item->itemId,
                                    'title' => $item->title,
                                    'price' => $itemPrice,
                                    'itemURL' => $item->viewItemURL,
                                    'galleryURL' => isset($item->galleryURL) ? $item->galleryURL : '',
                                );
                            }
                            /* check for USED Condition (conditionId = 3000) */ elseif ($item->condition->conditionId == '3000') {
                                $usedItems[] = array(
                                    'keywordId' => $id,
                                    'conditionId' => (string) $item->condition->conditionId,
                                    'itemId' => $item->itemId,
                                    'title' => $item->title,
                                    'price' => $itemPrice,
                                    'itemURL' => $item->viewItemURL,
                                    'galleryURL' => isset($item->galleryURL) ? $item->galleryURL : '',
                                );
                            }
                        }

                        ob_flush();
                    }

                    $newItems = array_slice($newItems, 0, 20);
                    $newOtherItems = array_slice($newOtherItems, 0, 20);
                    $usedItems = array_slice($usedItems, 0, 20);

                    $insertItems = array_merge($newItems, $newOtherItems, $usedItems);

                    /* clean up items */
                    Items::where('keywordId', $id)->delete();

                    /* save pulled items */
                    $items = Items::insert($insertItems);
                } elseif ($response->ack == "Failure") {
                    foreach ($response->errorMessage->error as $error) {
                        $errors .= "%s: %s\n\n" . $error->severity === Enums\ErrorSeverity::C_ERROR ? 'Error ' : 'Warning ' . $error->message;
                    }
                }

                /* save API log fot the keyword */
                $this->setapilog($request, $response, $keyword);

                if (!empty($errors)) {
                    echo json_encode(array('ack' => 'Failure', 'msg' => $errors));
                    exit;
                } else {
                    return true;
                }
            } catch (\Exception $e) {
                echo json_encode(array('ack' => 'Failure', 'msg' => $e->getMessage()));
                exit;
            }
        }

Any information on this would be greatly appreciated. Thanks!

Body:
Create this has a job Laravel Queues
Put your function in the handle method.

$response = $this->apiRequest(...);

Dispatch your job from say your controller

foreach ($keywordCollection as $key => $keywordResult) {
   ProcessJob::dispatch($keywordResult)->delay($key * 2);
}

This way you are implementing exponential backoff such that as your array increases you increase your wait time to make the next api request.


问:
setting storage connection string dynamically Azure function V1
I am following a design in which I am not saving any storage connection string in config file rather we should get it from azure key vault.We have implemented this in web jobs.

I am using Microsoft.NET.Sdk.Functions 1.0.11. and net framework 4.6.1.

in the applications settings of function app we have to set AzureWebJobsStorage.

How can I dynamically set the value to the storage settings in function app code?

答:
have you considered using Azure management api?
https://learn.microsoft.com/en-us/rest/api/appservice/webapps/updateapplicationsettings</p>


问:
php create certificate signing request into file error/warning
I need to create a certificate signing request to file but last line give error when run:

```<code>Warning: openssl_csr_export_to_file() expects parameter 1 to be resource, boolean given
</code>```

Any idea? this is the code, it's php 7.04 - wamp.

```<code>    <?php
    $subject = array(
    "commonName" => "example.com",
    );
    $private_key = openssl_pkey_new(array(
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
    ));

    $csr = openssl_csr_new($subject, $private_key, array('digest_alg' =>
    'sha384') );
     openssl_pkey_export_to_file($private_key, 'example-priv.key');
     // Along with the subject, the CSR contains the public key corresponding to
     // the private key
    openssl_csr_export_to_file($csr, 'example-csr.pem');
</code>```

答:
Improved but not sure yet if all steps result in correct keys/files (someone can look at it?):</p>

```<code><?php
echo '```'; error_reporting(E_ALL); ini_set('display_errors', '1');

$dn = array(
    "countryName" => "GB",
    "stateOrProvinceName" => "Greater London",
    "localityName" => "London",
    "organizationName" => "XY Ltd",
    "emailAddress" => "ab@xy.com"
);

$Configs = array(
    'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
    'digest_alg' => 'sha2',
    'x509_extensions' => 'v3_ca',
    'req_extensions' => 'v3_req',
    'encrypt_key' => true,
    'encrypt_key_cipher' => OPENSSL_CIPHER_3DES
);

$privateKey = openssl_pkey_new([
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
]);

openssl_pkey_export($privateKey, $privKey, null, [
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
]);

$a_key = openssl_pkey_get_details($privateKey);

// print_r($a_key);
// print_r($privKey); // Just to test output

file_put_contents('keys/public.key', $a_key['key']);
file_put_contents('keys/private.pem', $privKey);

$csr = openssl_csr_new($dn, $private_key, $Configs);
// var_dump($csr);

openssl_csr_export_to_file($csr, 'C:/wamp/www/php/keys/public.csr' );

openssl_free_key($privateKey);
</code>```

Body:
I need to create a certificate signing request to file but last line give error when run:

Warning: openssl_csr_export_to_file() expects parameter 1 to be resource, boolean given

Any idea? this is the code, it's php 7.04 - wamp.

    <?php
    $subject = array(
    "commonName" => "example.com",
    );
    $private_key = openssl_pkey_new(array(
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
    ));

    $csr = openssl_csr_new($subject, $private_key, array('digest_alg' =>
    'sha384') );
     openssl_pkey_export_to_file($private_key, 'example-priv.key');
     // Along with the subject, the CSR contains the public key corresponding to
     // the private key
    openssl_csr_export_to_file($csr, 'example-csr.pem');

Body:
Improved but not sure yet if all steps result in correct keys/files (someone can look at it?):

<?php
echo '<pre>'; error_reporting(E_ALL); ini_set('display_errors', '1');

$dn = array(
    "countryName" => "GB",
    "stateOrProvinceName" => "Greater London",
    "localityName" => "London",
    "organizationName" => "XY Ltd",
    "emailAddress" => "ab@xy.com"
);

$Configs = array(
    'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
    'digest_alg' => 'sha2',
    'x509_extensions' => 'v3_ca',
    'req_extensions' => 'v3_req',
    'encrypt_key' => true,
    'encrypt_key_cipher' => OPENSSL_CIPHER_3DES
);

$privateKey = openssl_pkey_new([
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
]);

openssl_pkey_export($privateKey, $privKey, null, [
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
]);

$a_key = openssl_pkey_get_details($privateKey);

// print_r($a_key);
// print_r($privKey); // Just to test output

file_put_contents('keys/public.key', $a_key['key']);
file_put_contents('keys/private.pem', $privKey);

$csr = openssl_csr_new($dn, $private_key, $Configs);
// var_dump($csr);

openssl_csr_export_to_file($csr, 'C:/wamp/www/php/keys/public.csr' );

openssl_free_key($privateKey);


问:
How bacnet device reply Iam message
I been trying to understand how bacnet java works on device reply “iam” message to the respective call

For example:
1.  Device 5678 send broadcast message with new whois message(device id 1234)
2.  Device 1234 replies “iam” message to device 5678.

Questions
How device 1234 send “iam” message to 5678?
Which part of JAVA code does that??

I'm happy for any input on the subject.

Best regards
Sorc

答:
On the basis that the Who-Is broadcast contains the SADR/source address, the receiving devices knows where to send it's response - if it did want to give a unicast/directed response.

You then have to listen out for the UDP (- UDP/IP -) response, and then you have to parse it, for the Object ID.

Title: How bacnet device reply Iam message


问:
Reducing number of Line Breaks/chr(10) in a Cell
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

```<code>HELLO

WORLD

GOODBYE
</code>```

will be modified to:

```<code>HELLO

WORLD

GOODBYE
</code>```

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

```<code> myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString
</code>```

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

```<code>for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""
</code>```

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

答:
You can use Regular Expressions.

The regex pattern below removes any line that contains zero to any number of spaces, along with its terminating crlf, and also removes the crlf at the end of the final word.

```<code>Option Explicit
Sub trimXSLF()
    Dim myRng As Range, myCell As Range, WS As Worksheet
    Dim RE As Object
    Const sPat As String = "^\s*[\x0A\x0D]+|[\x0A\x0D](?!\s*\S+\s*)"
    Const sRepl As String = ""

Set WS = Worksheets("sheet4") 'or whatever
With WS
    Set myRng = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .MultiLine = True
    .Pattern = sPat

    For Each myCell In myRng
        myCell = .Replace(myCell.Value2, sRepl)
    Next myCell

End With
End Sub
</code>```

If myRng is large (tens of thousands of rows), the macro could run the process over a VBA array for speed.

Body:
I have an excel sheet that has cells with variable amounts of line breaks and I want to reduce it so that there is only one line break between each new line.

For example

HELLO

WORLD

GOODBYE

will be modified to:

HELLO

WORLD

GOODBYE

I've been banging my head over this for hours and have come up with a few ways but none are very efficient or produce the best results.

This is made especially difficult because I'm working with a dataset that has spaces preceeding the Line Breaks.

And so a regular parse doesn't work as well.

I've tried to replace all the instances of chr(10) in the cell with ~ to make it easier to work with, however i'm still not getting it to an exact amount. I'm wondering if there are better ways.

here is what I have so far:

 myString = Replace(myString, Chr(10), "~")

    Do While InStr(myString, "~~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "~~", "~")
        Next k
    Loop

    Do While InStr(myString, "   ~") > 0
        str1 = Split(myString, "~")
        For k = 0 To UBound(str1)
        myString = Replace(myString, "  ~", "")
        Next k
    Loop

myString = Replace(myString, "   ~", " ~")
myString = Replace(myString, " ~", "~")
myString = Replace(myString, "~", Chr(10))

Cells(2, 2).Value = myString

So i'm using a few do while loops to catch instances of different types of line breaks (or in this case, tildes) but I don't think this is the best way to tackle this.

I was thinking of ways to loop through the characters in the cell, and if there is an instance where there is more than one chr(10), replace it with "".

So the psuedocode would look like:

for i to len(mystring)
    if mystring(i) = chr(10) AND myString(i+1) = chr(10) Then
       myString(i + 1) = ""

but unfortunately I don't think this is possible through vba.

If anyone is kind enough to help me adjust my current code or assist me with the aforementioned psuedocode, it would be greatly appreciated!

Body:
You can use Regular Expressions.

The regex pattern below removes any line that contains zero to any number of spaces, along with its terminating crlf, and also removes the crlf at the end of the final word.

Option Explicit
Sub trimXSLF()
    Dim myRng As Range, myCell As Range, WS As Worksheet
    Dim RE As Object
    Const sPat As String = "^\s*[\x0A\x0D]+|[\x0A\x0D](?!\s*\S+\s*)"
    Const sRepl As String = ""

Set WS = Worksheets("sheet4") 'or whatever
With WS
    Set myRng = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = True
    .MultiLine = True
    .Pattern = sPat

    For Each myCell In myRng
        myCell = .Replace(myCell.Value2, sRepl)
    Next myCell

End With
End Sub

If myRng is large (tens of thousands of rows), the macro could run the process over a VBA array for speed.


问:
Get a subscollection of a collection with a where query
How do I get a subcollection of a collection with a where query? This is what I've done so far:

```<code>  getTasksByUserId(userId) {
    this.logger.debug(`Getting tasks by user id ${userId}`);
    if (userId) {
      return this.afs.collection('tasks', ref => ref.where('createdBy', '==', userId)).valueChanges();
    }
  }
</code>```

My collection looks like this:

I'd like to also get the contents of features and tags in one query.

答:
Firestore read operations (including queries) return documents from a single collection only. If you need to return results from multiple collections, you'll to perform at least one read operation for the documents from each of those collections.

Consider if you really need the features and tags to be in subcollections, or whether they could also be (nested) fields in the document in the top-level tasks collection. If you do need them to be in the subcollections (for example for querying them), consider duplicating the data both in the task document, and in the subcollections.

Body:
How do I get a subcollection of a collection with a where query? This is what I've done so far:

  getTasksByUserId(userId) {
    this.logger.debug(`Getting tasks by user id ${userId}`);
    if (userId) {
      return this.afs.collection('tasks', ref => ref.where('createdBy', '==', userId)).valueChanges();
    }
  }

My collection looks like this:

I'd like to also get the contents of features and tags in one query.


问:
Why are there 3 pythons installed on my computer?
When I try to see the version of python installed on my computer, I see the followings:

```<code>(base) dhcp76:bin me$ python -V
</code>```

Python 2.7.16 :: Anaconda, Inc.

```<code>(base) dhcp76:bin me$ python2 -V
</code>```

Python 2.7.16

```<code>(base) dhcp76:bin me$ python3 -V
</code>```

Python 3.7.3

Would this cause any issue? I have also installed anaconda3, but python3 doesn't point to that, and I don't know how to make it point to anaconda3.

So, my questions:

Would having 2 python versions both by brew and anaconda cause problems? If yes, should I remove one of them? (I prefer anaconda)

I installed pytorch using this link: http://deeplizard.com/learn/video/UWlFM0R_x6I, and now when I do import torch in all three version it works!! How is this possible if this links only installs using pip3?

Thanks!

答:
Yes, having different version of Python can cause significant headache when you're installing python packages.

For example, if you install a package with Brew, your Anaconda installation might not be able to find it and vice-versa.

I had numerous consistency issues with maintaining all these different version of Python before I decided to completely uninstall all of them and only keep MacPorts as my general package manager.

When you use sudo pip install that could be using a different python than when you use python -m pip install which could be different from pip3 install ... etc.

There are lots of tradeoffs to each package manager.

Brew is good for people who want to get up to speed on a project quickly.

Anaconda has a great interface that allows you to minimize command line interface interactions and abstracts away some configuration stuff.

Macports has way more packages actively maintained than Brew, but requires more setup. For me, it was worth it because I've never had Python package dependency issues anymore. (Though that was also due to learning how to properly use virtualenvwrapper too.)

Most of the time, if you are fully aware of which pip/python you're calling, then you can avoid any issues and have all three.

However realistically, you may lose track of which Python versions are available with which packages in which system paths.

If things get bad, you might encounter situations where you try to pip install a package, and your system will say it already exists, but you may not be able to import <package> from python <file>.py or Terminal.

Body:
When I try to see the version of python installed on my computer, I see the followings:

(base) dhcp76:bin me$ python -V

Python 2.7.16 :: Anaconda, Inc.

(base) dhcp76:bin me$ python2 -V

Python 2.7.16

(base) dhcp76:bin me$ python3 -V

Python 3.7.3

Would this cause any issue? I have also installed anaconda3, but python3 doesn't point to that, and I don't know how to make it point to anaconda3.

So, my questions:

Would having 2 python versions both by brew and anaconda cause problems? If yes, should I remove one of them? (I prefer anaconda)

I installed pytorch using this link: http://deeplizard.com/learn/video/UWlFM0R_x6I, and now when I do import torch in all three version it works!! How is this possible if this links only installs using pip3?

Thanks!


问:
Regex for specific number
I need regular expression for ID number,
it's 9 numbers and the first number must be 4 or 9 or 8.

can some one help ?

答:
You can use the following regex:</p>

```<code>^[489][0-9]{8}$
</code>```

Title: Regex for specific number

Body:
You can use the following regex:

^[489][0-9]{8}$


问:
Compacting multiple similar if statements in C#
I would like to make some code for a game a little more compact. Here is the original.

```<code>if (killPosX != 0) // float x position you would like the object to be destroyed at
{
    killX = true;  // automatically makes the value of killX true
}

if (killPosY != 0) // float y position you would like the object to be destroyed at
{
    killY = true;  // automatically makes the value of killY true
}

if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
    killT = true;  // automatically makes the value of killT true
}
</code>```

And I want to turn it into something like this:

```<code>if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}
</code>```

How would I do that?

答:
I can't think of a way to do it as you suggest but it might be a little neater and more compact to use a variation of the approach hellium suggested:

```<code>public void fnc(ref bool t1, float t2) { t1 |= !Mathf.Approximately( t2, 0 ); }

fnc(ref KillX, KillPosX);
fnc(ref KillY, KillPosY);
fnc(ref KillT, KillPosT);
</code>```

You could of course wrap it in a method which uses arrays as parameters but unless you need a generic way to do this for variable sized arrays, the setup cost is bulkier than just using discrete calls.

Body:
I would like to make some code for a game a little more compact. Here is the original.

if (killPosX != 0) // float x position you would like the object to be destroyed at
{
    killX = true;  // automatically makes the value of killX true
}

if (killPosY != 0) // float y position you would like the object to be destroyed at
{
    killY = true;  // automatically makes the value of killY true
}

if (killPosT != 0) // float position in time you would like the object to be destroyed at
{
    killT = true;  // automatically makes the value of killT true
}

And I want to turn it into something like this:

if ([killPosX, killPosY, killPosT] != 0)
{
    [killPosX, killPosY, killPosT] = true;
}

How would I do that?

Body:
I can't think of a way to do it as you suggest but it might be a little neater and more compact to use a variation of the approach hellium suggested:

public void fnc(ref bool t1, float t2) { t1 |= !Mathf.Approximately( t2, 0 ); }

fnc(ref KillX, KillPosX);
fnc(ref KillY, KillPosY);
fnc(ref KillT, KillPosT);

You could of course wrap it in a method which uses arrays as parameters but unless you need a generic way to do this for variable sized arrays, the setup cost is bulkier than just using discrete calls.


问:
Why can I not make the text in these Bootstrap 4 nav pills black?
I'm making a grid using Bootstrap rows and columns inside a nav pill. So far I have the text showing up correctly, but for some reason I can't set the text in the first nav pill black.

I've tried moving the class for black text into different div elements/its own div element to no avail. Regardless, the first nav pill always shows up in the gray text. I've also made the black text class have an important property, but this changes nothing.

my code:

.active {
  color: #bdc3c7;
}

.black-text {
  color: #000000 !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-md-12 w-100">

    <ul class="nav nav-pills nav-justified mb-3" id="pills-tab" role="tablist">
      <br>
      <li class="nav-item">
        Mentors
      </li>
      <li class="nav-item">
        Members
      </li>
    </ul>

    <div class="tab-content" id="pills-tabContent">
      <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">
        <div class="row">
          <div class="col-md-6">
            <p><strong>Sean</strong> is sean</p>
          </div>
          <div class="col-md-6">
            <p><strong>Bean</strong> is bean</p>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <p><strong>Sean Bean</strong> is sean bean</p>
          </div>
        </div>
      </div>

      <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">
        <div class="row black-text">
          <div class="col-md-6">
            <p><strong>Sean</strong> is sean</p>
          </div>
          <div class="col-md-6">
            <p><strong>Bean</strong> is bean</p>
          </div>
        </div>
        <div class="row black-text">
          <div class="col-md-6">
            <p><strong>Sean Bean</strong> is sean bean</p>
          </div>
          <div class="col-md-6">
            <p><strong>Bean Sean</strong> is bean sean</p>
          </div>
        </div>
      </div>

    </div>
  </div>
</div></code>```

I expected all nav pills to display black text, but only the second one does.

答: You can do this by adding a class to your ul class. Here is a link for someone attempting the same thing. Changing color of Twitter bootstrap Nav-Pills</p>

Body:
I'm making a grid using Bootstrap rows and columns inside a nav pill. So far I have the text showing up correctly, but for some reason I can't set the text in the first nav pill black.

I've tried moving the class for black text into different div elements/its own div element to no avail. Regardless, the first nav pill always shows up in the gray text. I've also made the black text class have an important property, but this changes nothing.

my code:

.active {
  color: #bdc3c7;
}

.black-text {
  color: #000000 !important;
}

        Mentors

        Members

Sean is sean

Bean is bean

Sean Bean is sean bean

Sean is sean

Bean is bean

Sean Bean is sean bean

Bean Sean is bean sean

I expected all nav pills to display black text, but only the second one does.


问:
“bad interpreter: Operation not permitted” Error on El Capitan
My team is writing a Mac OS application that needs to call a shell script in an external directory.

The application works fine on Yosemite (10.10.3). However, if I run it on El Capitan (10.11.2), the application gets errors like this from the script:

```<code>/bin/bash: <path-to-script>: /bin/sh: bad interpreter: Operation not permitted
</code>```

I can trigger this error on a simple script like this:

```<code>#!/bin/sh
echo "Hello World!"
</code>```

I do not get an error if I run the scripts manually from the Terminal.

The application opens the script directory using a filechooser. I confirmed that the application can read other files from this directory.

Changing /bin/sh to /bin/bash or a copy of /bin/sh on a different path gives the same error with the new interpreter path.

A coworker tested this issue on a El Capitan machine with System Integrity Protection disabled, but he got the same error.

I am installing the test application from a .pkg file. The entitlements are:

```<code><key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.files.bookmarks.app-scope</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
</code>```

Adding the com.apple.security.files.user-selected.executable entitlement did not make a difference

If I try to run the .app that is generated in an intermediate step in the package build, I am able to run the script with no errors.

The question below describes a similar error. However, I checked both the application and the script, and I found that neither one had the com.apple.quarantine attribute set.

Mac OS: /usr/bin/env: bad interpreter: Operation not permitted

https://apple.stackexchange.com/questions/49589/bash-applications-mvim-bin-sh-bad-interpreter-operation-not-permitted

--- UPDATE ----

We added two more in PKG entitlement list:

```<code><key>com.apple.security.scripting-targets</key>
<true/>
<key>com.apple.security.temporary-exception.apple-events</key>
<true/>
</code>```

We tried to run the simple .sh file by an AppleScript (.scpt) file (stored in application directory), we also confirmed that the .sh file nor the .scpt file has any extended attribute as well, but we still have that error.

Following shows ls -@Oel commands on both AppleScript and shell script file respectively.

```<code>$ ls -@Oel TestMXMLCall.scpt
-rwxrwxrwx  1 root  wheel  - 2302 Jun 15 03:12 TestMXMLCall.scpt
$ ls -@Oel /usr/local/bin/mxmlc
-rwxr-xr-x  1 santanukarar  staff  - 2190 Jun 15 01:17 /usr/local/bin/mxmlc
</code>```

答:
try this:
    $ ls -l@ whereverthescriptis
If it says it's got com.apple.quarantine, that's the problem.  Run one of these on it, from least dangerous to most:

```<code>$ xattr -d com.apple.quarantine whereverthescriptis   # delete that attr
$ xattr -c whereverthescriptis    # delete ALL the attrs on file
$ xattr -c *         # on every file in this dir
$ xattr -cr .        # and all subdirectories
</code>```

Body:
My team is writing a Mac OS application that needs to call a shell script in an external directory.

The application works fine on Yosemite (10.10.3). However, if I run it on El Capitan (10.11.2), the application gets errors like this from the script:

/bin/bash: <path-to-script>: /bin/sh: bad interpreter: Operation not permitted

I can trigger this error on a simple script like this:

#!/bin/sh
echo "Hello World!"

I do not get an error if I run the scripts manually from the Terminal.

The application opens the script directory using a filechooser. I confirmed that the application can read other files from this directory.

Changing /bin/sh to /bin/bash or a copy of /bin/sh on a different path gives the same error with the new interpreter path.

A coworker tested this issue on a El Capitan machine with System Integrity Protection disabled, but he got the same error.

I am installing the test application from a .pkg file. The entitlements are:

<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.files.bookmarks.app-scope</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>

Adding the com.apple.security.files.user-selected.executable entitlement did not make a difference

If I try to run the .app that is generated in an intermediate step in the package build, I am able to run the script with no errors.

The question below describes a similar error. However, I checked both the application and the script, and I found that neither one had the com.apple.quarantine attribute set.

Mac OS: /usr/bin/env: bad interpreter: Operation not permitted

https://apple.stackexchange.com/questions/49589/bash-applications-mvim-bin-sh-bad-interpreter-operation-not-permitted

--- UPDATE ----

We added two more in PKG entitlement list:

<key>com.apple.security.scripting-targets</key>
<true/>
<key>com.apple.security.temporary-exception.apple-events</key>
<true/>

We tried to run the simple .sh file by an AppleScript (.scpt) file (stored in application directory), we also confirmed that the .sh file nor the .scpt file has any extended attribute as well, but we still have that error.

Following shows ls -@Oel commands on both AppleScript and shell script file respectively.

$ ls -@Oel TestMXMLCall.scpt
-rwxrwxrwx  1 root  wheel  - 2302 Jun 15 03:12 TestMXMLCall.scpt
$ ls -@Oel /usr/local/bin/mxmlc
-rwxr-xr-x  1 santanukarar  staff  - 2190 Jun 15 01:17 /usr/local/bin/mxmlc

Body:
try this:
    $ ls -l@ whereverthescriptis
If it says it's got com.apple.quarantine, that's the problem.  Run one of these on it, from least dangerous to most:

$ xattr -d com.apple.quarantine whereverthescriptis   # delete that attr
$ xattr -c whereverthescriptis    # delete ALL the attrs on file
$ xattr -c *         # on every file in this dir
$ xattr -cr .        # and all subdirectories


问:
How to evolve a dataclass in python?
I'm interested to use dataclass as the syntax is shorter than attr. However I can't find a shortcut that provides the API to evolve it, using e.g. the following code:

```<code>@dataclass
class AB(object):
    a: int = 1
    b: int = 2

AB().evolve(b=3)

result = AB(a=1, b=3)
</code>```

Is it easy to find an out-of-the-box replacement? or to implement it on my own?

答:
The dataclasses.replace() function is roughly equivalent to the attr.evolve() function.

Usage example based on your code:

```<code>import dataclasses
from dataclasses import dataclass

@dataclass
class AB(object):
    a: int = 1
    b: int = 2

ab_object = AB()
another_ab_object = dataclasses.replace(ab_object, b=3)

print(ab_object)
# Output: AB(a=1, b=2)
print(another_ab_object)
# Output: AB(a=1, b=3)
</code>```

Title: How to evolve a dataclass in python?

Body:
I'm interested to use dataclass as the syntax is shorter than attr. However I can't find a shortcut that provides the API to evolve it, using e.g. the following code:

@dataclass
class AB(object):
    a: int = 1
    b: int = 2

AB().evolve(b=3)

result = AB(a=1, b=3)

Is it easy to find an out-of-the-box replacement? or to implement it on my own?

Body:
The dataclasses.replace() function is roughly equivalent to the attr.evolve() function.

Usage example based on your code:

import dataclasses
from dataclasses import dataclass

@dataclass
class AB(object):
    a: int = 1
    b: int = 2

ab_object = AB()
another_ab_object = dataclasses.replace(ab_object, b=3)

print(ab_object)
# Output: AB(a=1, b=2)
print(another_ab_object)
# Output: AB(a=1, b=3)