问:
unknown revision error when trying to pull repository from hg
I am trying to clone a repo from Mercurial. I entered the command: hg pull --rev=2500, it works.

However, when I try hg pull --rev 3000, it shows error: abort:unknown revision '3000'!

Anyone know how to fix this?

Thanks,
Jennifer.

答:
You just need to drop the --revision=number part.  But there's something odd here: hg pull is meant for copying changesets from a repository, not for cloning a repository.

To clone a repository means:

Make a new, empty repository.

Copy all1 the changesets from some other repository to this repository.

To pull from a repository means:

Copy all2 the changesets from some other repostory, that they have and I don't, to this repository.

Note how these two are similar but not identical.  The clone operation first makes a new, empty repository.  Step 2, fill the repository with (all) changesets from the other repository, matches step 1 of the pull action.  With a pull, we add only the changesets that they have that we don't, but since our new empty repository is empty, all changesets they have are ones that we don't.

Both operations involve calling up some other (existing) Mercurial repository.  The first one creates your repository while it makes this call; the second uses your existing repository, and makes this call.  Note that in both cases, the other repository here has its own changesets, which are on some set of branches, and that other repository numbers those changesets using its numbering.

Since you already have a repository, you apparently just want hg pull anyway.  See footnotes 1 and 2 for what the --rev=2500 is doing.

1Sometimes we don't need all of the changesets.  We can make a limited clone using only some of the changesets.  Cloning with -b branch tells Mercurial to omit changesets not required to obtain the changesets that are on the named branch.

2As before, we might not need all changesets.  We can tell the other Mercurial repository: Give me your changesets ending with your number 2500, for instance.  You're asking it for its changesets up to number 3000, and it simply does not have that many changesets at this point.


来源: stackexchange

问:
Cypress, how to check for text typed into a field?
I can verify text appears "somewhere" on the results page with

it.only('can verify an input element has certain text typed into it', function() {
  cy.visit('http://google.com')
  cy.get("input[name=q]").type('abc123{enter}')  // with or without the {enter}
  cy.contains('abc123') // Anywhere on the page :(
})
```
<p>but how can I verify the text I type <strong>in the input text box</strong>?</p>
<p>I tried chaining to the element with</p>
<pre class="lang-javascript prettyprint-override"><code>it.only('can verify an input element has certain text typed into it', function() {
  cy.visit('http://google.com')
  cy.get("input[name=q]").type('abc123{enter}')
  cy.get("input[name=q]").contains('abc123')
})
</code>```

but I get

CypressError: Timed out retrying: Expected to find content: 'abc123' within the element: <input.gLFyf.gsfi> but never did.
```

I tried cy.get("input[name=q]").contains('abc123') and

cy.contains('input[name=q]', 'abc123')

but both time out and fail.

答:
Change .contains to use .should('have.value'...

```<code>cy.get("input[name=q]").type('abc123{enter}')
cy.get("input[name=q]").should('have.value', 'abc123')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can verify text appears "somewhere" on the results page with

it.only('can verify an input element has certain text typed into it', function() {
  cy.visit('http://google.com')
  cy.get("input[name=q]").type('abc123{enter}')  // with or without the {enter}
  cy.contains('abc123') // Anywhere on the page :(
})

but how can I verify the text I type in the input text box?

I tried chaining to the element with

it.only('can verify an input element has certain text typed into it', function() {
  cy.visit('http://google.com')
  cy.get("input[name=q]").type('abc123{enter}')
  cy.get("input[name=q]").contains('abc123')
})

but I get

CypressError: Timed out retrying: Expected to find content: 'abc123' within the element: <input.gLFyf.gsfi> but never did.

I tried cy.get("input[name=q]").contains('abc123') and

cy.contains('input[name=q]', 'abc123')

but both time out and fail.

Body:
Change .contains to use .should('have.value'...

cy.get("input[name=q]").type('abc123{enter}')
cy.get("input[name=q]").should('have.value', 'abc123')


问:
Query to get last X minutes data with Mongodb
I'm trying to query my db that have this document format:

```<code>{
  "_id" : ObjectId("520b8b3f8bd94741bf006033"),
  "value" : 0.664,
  "timestamp" : ISODate("2013-08-14T13:48:35Z"),
  "cr" : ISODate("2013-08-14T13:50:55.834Z")
}
</code>```

I can get the last records from a datetime with this query:

```<code>db.mycol.find({timestamp:{$gt: ISODate("2013-08-14T13:48:00Z")}}).sort({x:1});
</code>```

But I'm trying to get a set with the value fields and timestamps from 18 minutes ago.

答:
You could also do below

```<code>  db.getCollection('collectionName').find({timestamp : {$gte: new Date().getTime()-(60*60*1000) } } )
</code>```

The above query ll give you records of timestamp b/w now and 60 mins. if you like more then 60 mins - say 2 hrs you could change expression to (2*60*60*1000)
for 30 mins (30*60*1000)

Body:
I'm trying to query my db that have this document format:

{
  "_id" : ObjectId("520b8b3f8bd94741bf006033"),
  "value" : 0.664,
  "timestamp" : ISODate("2013-08-14T13:48:35Z"),
  "cr" : ISODate("2013-08-14T13:50:55.834Z")
}

I can get the last records from a datetime with this query:

db.mycol.find({timestamp:{$gt: ISODate("2013-08-14T13:48:00Z")}}).sort({x:1});

But I'm trying to get a set with the value fields and timestamps from 18 minutes ago.

Body:
You could also do below

  db.getCollection('collectionName').find({timestamp : {$gte: new Date().getTime()-(60*60*1000) } } )

The above query ll give you records of timestamp b/w now and 60 mins. if you like more then 60 mins - say 2 hrs you could change expression to (2*60*60*1000)
for 30 mins (30*60*1000)


问:
download.file in R leaves out content
I used in R

```<code>download.file('https://www.census.gov/retail/marts/www/marts_current.xls', method='auto',
  destfile='C:/Users/<my name>/Desktop/test.xls')
</code>```

expecting to see the contents of marts_current.xls in test.xls but much of the content in the source file is left out.

Can someone help me understand why? How can I get the whole file?

答:
Excel xls files are binary files and care should be taken to download them as such. the default for download.files is to assume they are text files. You can control this with the mode= flag. Use

```<code>download.file('https://www.census.gov/retail/marts/www/marts_current.xls', method='auto',
  destfile='C:/Users/<my name>/Desktop/test.xls', mode="wb")
</code>```

Title: download.file in R leaves out content

Body:
I used in R

download.file('https://www.census.gov/retail/marts/www/marts_current.xls', method='auto',
  destfile='C:/Users/<my name>/Desktop/test.xls')

expecting to see the contents of marts_current.xls in test.xls but much of the content in the source file is left out.

Can someone help me understand why? How can I get the whole file?

Body:
Excel xls files are binary files and care should be taken to download them as such. the default for download.files is to assume they are text files. You can control this with the mode= flag. Use

download.file('https://www.census.gov/retail/marts/www/marts_current.xls', method='auto',
  destfile='C:/Users/<my name>/Desktop/test.xls', mode="wb")


问:
Substr in mongodb conditional aggregate
I have to count the employees with valid mail id suffix with '@test.com'. I tried below queries,

```<code>db.emp.aggregate([
        { $match: {} },
        { $addFields:{
          "validEmail":{$cond:[{$eq:[{"$substr":["$emp_email",9,-1]},"@test.com"]},1,0]}
           }
        }
    ])
</code>```

Here, the $substr operator is not returning the output in reverse way. My assumption is that -1 on the 3rd argument should substr with reverse way. It is not working.

I am using mongodb version lesser than 4.2 and not able to use $regexMatch. Is there any way to achieve this.

答:
You can simply use regex : </p>

```<code>db.collection.find({
  email: {
    $regex: ".+@test.com\\b",
  }
})
</code>```

Title: Substr in mongodb conditional aggregate

Body:
I have to count the employees with valid mail id suffix with '@test.com'. I tried below queries,

db.emp.aggregate([
        { $match: {} },
        { $addFields:{
          "validEmail":{$cond:[{$eq:[{"$substr":["$emp_email",9,-1]},"@test.com"]},1,0]}
           }
        }
    ])

Here, the $substr operator is not returning the output in reverse way. My assumption is that -1 on the 3rd argument should substr with reverse way. It is not working.

I am using mongodb version lesser than 4.2 and not able to use $regexMatch. Is there any way to achieve this.

Body:
You can simply use regex :

db.collection.find({
  email: {
    $regex: ".+@test.com\\b",
  }
})


问:
WordPress - Set User to Expire after a Certain Date
I am working on a site for a school program. During registration, students are going to be asked to select their graduation year from a dropdown. I want the system to check this value against the current time each time that they log in, and change their roles if the graduation date is past the current time. The code I wrote is below, however I am getting no errors either in logs or WP_DEBUG

```<code>/* Check if Student Has Graduated and Change Role */
add_action('wp_login', 'check_graduated', 10, 2);
function check_graduated($user_login, $user) {
    /* Ger User Id */
    $user_id = $user -> $id;

    /* Check if Graduation Date exists in DB */
    if($grad_year = get_user_meta($user_id, 'user_registration_user_graduation_date', true)) {
        $current_date = time();

        /* Convert Grad Year to Time */
        $grad_date_str = "07/01/" . $grad_year;
        $grad_date = stringtotime($grad_date_str);

        /* Change User Role if Today is Past The Graduation Date */
        if($current_date > $grad_date) {
            change_user_role($user_id, 'former_student', 'student');
        }
    }
}

function change_user_role($id, $new_role, $old_role) {
    $user = new WP_User( $id );
    $user -> remove_role( $old_role );
    $user -> add_role ( $new_role );
}
</code>```

In the Usermeta table of the database, the following exists:

```<code>|----------------------------------------------------------------------------------|
|  UMETA_ID  |  USER_ID  |                 META_KEY                 |  META_VALUE  |
|----------------------------------------------------------------------------------|
|     36     |     2     |  user_registration_user_graduation_date  |     2016     |
|----------------------------------------------------------------------------------|
</code>```

Like I said, no errors show up when logging in with the user with ID 2. Am I missing something or just dumb?

答:
You may want to look at this function  $grad_date = stringtotime($grad_date_str);

It should be

 $grad_date = strtotime($grad_date_str);
```

https://www.php.net/manual/en/function.strtotime.php

Other wise, you should be fairly close.

Body:
I am working on a site for a school program. During registration, students are going to be asked to select their graduation year from a dropdown. I want the system to check this value against the current time each time that they log in, and change their roles if the graduation date is past the current time. The code I wrote is below, however I am getting no errors either in logs or WP_DEBUG

/* Check if Student Has Graduated and Change Role */
add_action('wp_login', 'check_graduated', 10, 2);
function check_graduated($user_login, $user) {
    /* Ger User Id */
    $user_id = $user -> $id;

    /* Check if Graduation Date exists in DB */
    if($grad_year = get_user_meta($user_id, 'user_registration_user_graduation_date', true)) {
        $current_date = time();

        /* Convert Grad Year to Time */
        $grad_date_str = "07/01/" . $grad_year;
        $grad_date = stringtotime($grad_date_str);

        /* Change User Role if Today is Past The Graduation Date */
        if($current_date > $grad_date) {
            change_user_role($user_id, 'former_student', 'student');
        }
    }
}

function change_user_role($id, $new_role, $old_role) {
    $user = new WP_User( $id );
    $user -> remove_role( $old_role );
    $user -> add_role ( $new_role );
}

In the Usermeta table of the database, the following exists:

|----------------------------------------------------------------------------------|
|  UMETA_ID  |  USER_ID  |                 META_KEY                 |  META_VALUE  |
|----------------------------------------------------------------------------------|
|     36     |     2     |  user_registration_user_graduation_date  |     2016     |
|----------------------------------------------------------------------------------|

Like I said, no errors show up when logging in with the user with ID 2. Am I missing something or just dumb?

Body:
You may want to look at this function  $grad_date = stringtotime($grad_date_str);

It should be

 $grad_date = strtotime($grad_date_str);

https://www.php.net/manual/en/function.strtotime.php

Other wise, you should be fairly close.


问:
Lower Login button to very bottom of my web app
I was wondering how do I position my Login button at the bottom centre of the screen and have the image displayed over it? I want this to be essentially the homepage. My image is not displaying either for some reason.

Code:

```<code><div class="container-fluid">
  <img alt="Sportly logo" src="~@/assets/sportly.png">
    <div class="row">
        <div class="col-md-12">
            <h3>Login</h3>
            <button class="btn btn-primary"
                @click="signIn">

               <i class="fa fa-twitter"></i>
                    Sign In with Twitter
                </button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    methods: {
        signIn () {
            this.$store.dispatch('signIn')
        }
    }
}
</script>

<style scoped>
h3 {
    font-weight: 700;

}
button {
    background-color: #1dcaff;
    border: 1px solid  #1dcaff;

}
div button:hover {
    background-color: #00aced;
    border: 1px solid  #00aced;

}
</style>
</code>```

答:
I used position: fixed + bottom: XXpx to send the div to the bottom of the page, width: 100% + margin: 0 auto + text-align: center to center the elements, and position: relative + z-index: 1 to overlap the login button and the image. Here are the results:

h3 {
  font-weight: 700;
}
button {
  background-color: #1dcaff;
  border: 1px solid  #1dcaff;
}
div button:hover {
  background-color: #00aced;
  border: 1px solid  #00aced;
}
.loginarea {
  position: fixed;
  bottom: 20px; /* Distance from window bottom */
  width: 100%;
}
.loginarea .center {
  margin: 0 auto;
  width: 200px; /* Width of logo */
}
.loginarea .logo {
  position: relative;
  display: block;
}
.loginarea .row {
  position: absolute;
  text-align: center;
  width: 200px; /* Width of logo */
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid loginarea">
  <div class="center">
    <div class="row">
      <div class="col-md-12 logindiv">
        <h3>Login</h3>
        <button class="btn btn-primary"
          @click="signIn">
          <i class="fa fa-twitter"></i>
          Sign In with Twitter
        </button>
      </div>
    </div>
    <img class="logo" alt="Sportly logo" src="http://placekitten.com/200/100">
  </div>
</div></code>```

Body:
I was wondering how do I position my Login button at the bottom centre of the screen and have the image displayed over it? I want this to be essentially the homepage. My image is not displaying either for some reason.

Code:

Login

            <button class="btn btn-primary"
                @click="signIn">

                    Sign In with Twitter
                </button>

</template>

Body:
I used position: fixed + bottom: XXpx to send the div to the bottom of the page, width: 100% + margin: 0 auto + text-align: center to center the elements, and position: relative + z-index: 1 to overlap the login button and the image. Here are the results:

h3 {
  font-weight: 700;
}
button {
  background-color: #1dcaff;
  border: 1px solid  #1dcaff;
}
div button:hover {
  background-color: #00aced;
  border: 1px solid  #00aced;
}
.loginarea {
  position: fixed;
  bottom: 20px; /* Distance from window bottom */
  width: 100%;
}
.loginarea .center {
  margin: 0 auto;
  width: 200px; /* Width of logo */
}
.loginarea .logo {
  position: relative;
  display: block;
}
.loginarea .row {
  position: absolute;
  text-align: center;
  width: 200px; /* Width of logo */
  z-index: 1;
}

<div class="container-fluid loginarea">
  <div class="center">
    <div class="row">
      <div class="col-md-12 logindiv">
        <h3>Login</h3>
        <button class="btn btn-primary"
          @click="signIn">
          <i class="fa fa-twitter"></i>
          Sign In with Twitter
        </button>
      </div>
    </div>
    <img class="logo" alt="Sportly logo" src="http://placekitten.com/200/100">
  </div>
</div>


问:
UITableView support for right to left languages
how to change a table view layout to be from right to left (including its transition to a detail view: the transition must also be from right to left) ?
thanx in advance.</p>

答:
There is no single property  nigher in UITableView nor UITableViewCell to change the right to left OR left to right, If you want it in your application, you will have make an custom UITableViewCell and layout the views (components of your cell) right to left.

Check the below SO post

Right to Left Alignment for UITableView

How to create a right to left UITableView?

ContentLicense: CC BY-SA 3.0


问:
How to conditionally render a React component that uses hooks
The following (albeit contrived) component violates react-hooks/rules-of-hooks (via eslint)

```<code>function Apple(props){
  const {seeds} = props;
  if(!seeds){
    return null;
  }
  const [bitesTaken, setBitesTaken] = useState(0);
  return <div>{bitesTaken}</div>
}

</code>```

with the following error
React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

I understand that hooks need to be called in the same order, but this kind of conditional rendering (so long as no hooks are invoked before the return, does not prevent the hooks from being called in the same order.  I think the eslint rule is too strict, but maybe there's a better way.

What is the best way to conditionally render a component which uses hooks?

答:
You can't conditionally use hooks, so move the hook above the condition.

```<code>function Apple(props){
  const {seeds} = props;
  const [bitesTaken, setBitesTaken] = useState(0);
  if(!seeds){
    return null;
  }
  return <div>{bitesTaken}</div>
}
</code>```

You can also simplify the rendering like this:

```<code>function Apple(props) {
  const { seeds } = props
  const [bitesTaken, setBitesTaken] = useState(0)
  return !!seeds && <div>{bitesTaken}</div>
}
</code>```

If seeds is falsey, then false will be returned (which renders as nothing), otherwise, the div will be returned.

I've added the double exclamation point to seeds to turn it into a boolean, because if seeds is undefined then nothing is returned from render and React throws an error.

Body:
The following (albeit contrived) component violates react-hooks/rules-of-hooks (via eslint)

function Apple(props){
  const {seeds} = props;
  if(!seeds){
    return null;
  }
  const [bitesTaken, setBitesTaken] = useState(0);
  return
{bitesTaken}

}

with the following error
React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

I understand that hooks need to be called in the same order, but this kind of conditional rendering (so long as no hooks are invoked before the return, does not prevent the hooks from being called in the same order.  I think the eslint rule is too strict, but maybe there's a better way.

What is the best way to conditionally render a component which uses hooks?

Body:
You can't conditionally use hooks, so move the hook above the condition.

function Apple(props){
  const {seeds} = props;
  const [bitesTaken, setBitesTaken] = useState(0);
  if(!seeds){
    return null;
  }
  return <div>{bitesTaken}</div>
}

You can also simplify the rendering like this:

function Apple(props) {
  const { seeds } = props
  const [bitesTaken, setBitesTaken] = useState(0)
  return !!seeds && <div>{bitesTaken}</div>
}

If seeds is falsey, then false will be returned (which renders as nothing), otherwise, the div will be returned.

I've added the double exclamation point to seeds to turn it into a boolean, because if seeds is undefined then nothing is returned from render and React throws an error.


问:
prevent concurrent request from a user
I have a question about concurrent request a user from different browser

Imagine we have balance in wallet for just buy one product, if a user request a product at the same time with two different browser, can user buy a product two times? if it is possible, how can I prevent the second action?

example:

user A balance : 100$

```<code>user A ---->  mozila ----> request ----> product A50(price 100$)
user A ---->  chrome ----> request ----> product A50(price 100$)
</code>```

above request happen at the same time after that some process the amount of wallet decrease

答:
You should perform these operations in SQL TRANSACTIONs having an appropriate isolation level.  All of the operations performed within the transaction will be "all or nothing," which means that all of the changes take effect if you COMMIT and none of them do if you instead ROLLBACK.  Furthermore, if two transactions attempt to touch the same row, one of them will either be forced to wait or will be turned away.  Also, the other transaction will not see anything that hasn't yet been committed.

For instance, if you want to "deduct money from the user's account and apply it to an order," you would perform both updates in one transaction.  So, "if everything worked, both updates happened instantaneously."  And, "if it didn't work and the transaction was rolled back, nothing changed anywhere."

But it's important that you also test the user's balance within the same transaction!  (Otherwise, there would be a "race" between testing the balance and proceeding with the sale.)  Your logic might be something like this pseudocode:

```<code> BEGIN TRANSACTION with proper isolation level
 Retrieve user's account.
 If there isn't enough money:
     ROLLBACK
     exit
 Else:
     UPDATE user account to withdraw money.
     UPDATE the invoice to show payment.
     INSERT a new entry into the (financial ...) transaction log table.
     COMMIT
</code>```

This works as intended because the entire set of operations that occurs within the transaction is "atomic."

SQL servers vary slightly in their implementation of transactions but here is a web-page on the topic (covering MS SQL Server):

https://www.sqlserverlogexplorer.com/types-of-transaction-isolation-level/

Title: prevent concurrent request from a user

Body:
I have a question about concurrent request a user from different browser

Imagine we have balance in wallet for just buy one product, if a user request a product at the same time with two different browser, can user buy a product two times? if it is possible, how can I prevent the second action?

example:

user A balance : 100$

user A ---->  mozila ----> request ----> product A50(price 100$)
user A ---->  chrome ----> request ----> product A50(price 100$)

above request happen at the same time after that some process the amount of wallet decrease

Body:
You should perform these operations in SQL TRANSACTIONs having an appropriate isolation level.  All of the operations performed within the transaction will be "all or nothing," which means that all of the changes take effect if you COMMIT and none of them do if you instead ROLLBACK.  Furthermore, if two transactions attempt to touch the same row, one of them will either be forced to wait or will be turned away.  Also, the other transaction will not see anything that hasn't yet been committed.

For instance, if you want to "deduct money from the user's account and apply it to an order," you would perform both updates in one transaction.  So, "if everything worked, both updates happened instantaneously."  And, "if it didn't work and the transaction was rolled back, nothing changed anywhere."

But it's important that you also test the user's balance within the same transaction!  (Otherwise, there would be a "race" between testing the balance and proceeding with the sale.)  Your logic might be something like this pseudocode:

 BEGIN TRANSACTION with proper isolation level
 Retrieve user's account.
 If there isn't enough money:
     ROLLBACK
     exit
 Else:
     UPDATE user account to withdraw money.
     UPDATE the invoice to show payment.
     INSERT a new entry into the (financial ...) transaction log table.
     COMMIT

This works as intended because the entire set of operations that occurs within the transaction is "atomic."

SQL servers vary slightly in their implementation of transactions but here is a web-page on the topic (covering MS SQL Server):

https://www.sqlserverlogexplorer.com/types-of-transaction-isolation-level/


问:
MongoDB query subdocument for records that don't match criteria
I currently have the following query:

```<code>db.getCollection('conversations').aggregate([
{
  $lookup: {
    foreignField: "c_ID",
    from: "messages",
    localField: "_id",
    as: "messages"
  }
},
{
  "$unwind": "$messages"
},
{
  "$sort": {
    "messages.t": -1
  }
},
{
  "$group": {
    "_id": "$_id",
    "lastMessage": {
      "$first": "$messages"
    },
    "allFields": {
      "$first": "$$ROOT"
    }
  }
},
{
  "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$allFields",
        {
          "lastMessage": "$lastMessage"
        }
      ]
    }
  }
},
{
  $project: {
    messages: 0
  }
},
{
  $match: {
    "members.uID": "1",
    //"lastMessage.t": { $gt: ISODate("2020-02-04 20:38:02.154Z") }
  }
},
{
  $sort: { "lastMessage.t": 1 }
},
{
  $limit: 10
},
{
  $project: {
    members: {
      $slice: [ {
        $filter: {
          input : "$members", as : "member", cond : {
            $ne : ["$$member.uID" , "1"]
          }
        }
      }, 3 ]
    }
  }
},
</code>```

])

However, I also have a field for each member, named "l", which contains a timestamp. It means someone has left a conversation and thus represents the leave date. I don't want anyone who left before the current timestamp (e.g. 1582056056) to be included in the members list. How can I do this?

EDIT:

conversations document

```<code>{
    "_id" : ObjectId("5e35f2c840713a43aeeeb3d9"),
    "members" : [
        {
            "uID" : "1",
            "j" : 1580580922
        },
        {
            "uID" : "4",
            "j" : 1580580922,
            “l”: 1580581982
        },
        {
            "uID" : "5",
            "j" : 1580580922
        }
    ]
}
</code>```

messages document

```<code>{
    "_id" : ObjectId("5e35ee5f40713a43aeeeb1c5"),
    "c_ID" : ObjectId("5e35f2c840713a43aeeeb3d9"),
    "fromID" : "1",
    "msg" : "What's up?",
    "t" : 1580591922,
    "d" : {
        "4" : 1580592039
    },
    "r" : {
        "4" : 1580592339
    }
}
</code>```

答:
We can exclude them during $filter stage with $and and $or operators.

```<code>member.uID != 1 && (member.l == undefined || lastMessage.t < member.l)
</code>```

Take a look query below.

```<code>db.conversations.aggregate([
  {
    $lookup: {
      from: "messages",
      foreignField: "c_ID",
      localField: "_id",
      as: "messages"
    }
  },
  {
    "$unwind": "$messages"
  },
  {
    "$sort": {
      "messages.t": -1
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "lastMessage": {
        "$first": "$messages"
      },
      "allFields": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$allFields",
          {
            "lastMessage": "$lastMessage"
          }
        ]
      }
    }
  },
  {
    $project: {
      messages: 0
    }
  },
  {
    $match: {
      "members.uID": "1"
    }
  },
  {
    $sort: {
      "lastMessage.t": 1
    }
  },
  {
    $limit: 10
  },
  {
    $project: {
      members: {
        $slice: [
          {
            $filter: {
              input: "$members",
              as: "member",
              cond: {
                $and: [
                  {
                    $ne: [
                      "$$member.uID",
                      "1"
                    ]
                  },
                  {
                    $or: [
                      {
                        $eq: [
                          "$$member.l",
                          undefined
                        ]
                      },
                      {
                        $lt: [
                          "$lastMessage.t",
                          "$$member.l"
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          },
          3
        ]
      }
    }
  }
])
</code>```

MongoPlayground

Body:
I currently have the following query:

db.getCollection('conversations').aggregate([
{
  $lookup: {
    foreignField: "c_ID",
    from: "messages",
    localField: "_id",
    as: "messages"
  }
},
{
  "$unwind": "$messages"
},
{
  "$sort": {
    "messages.t": -1
  }
},
{
  "$group": {
    "_id": "$_id",
    "lastMessage": {
      "$first": "$messages"
    },
    "allFields": {
      "$first": "$$ROOT"
    }
  }
},
{
  "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$allFields",
        {
          "lastMessage": "$lastMessage"
        }
      ]
    }
  }
},
{
  $project: {
    messages: 0
  }
},
{
  $match: {
    "members.uID": "1",
    //"lastMessage.t": { $gt: ISODate("2020-02-04 20:38:02.154Z") }
  }
},
{
  $sort: { "lastMessage.t": 1 }
},
{
  $limit: 10
},
{
  $project: {
    members: {
      $slice: [ {
        $filter: {
          input : "$members", as : "member", cond : {
            $ne : ["$$member.uID" , "1"]
          }
        }
      }, 3 ]
    }
  }
},

])

However, I also have a field for each member, named "l", which contains a timestamp. It means someone has left a conversation and thus represents the leave date. I don't want anyone who left before the current timestamp (e.g. 1582056056) to be included in the members list. How can I do this?

EDIT:

conversations document

{
    "_id" : ObjectId("5e35f2c840713a43aeeeb3d9"),
    "members" : [
        {
            "uID" : "1",
            "j" : 1580580922
        },
        {
            "uID" : "4",
            "j" : 1580580922,
            “l”: 1580581982
        },
        {
            "uID" : "5",
            "j" : 1580580922
        }
    ]
}

messages document

{
    "_id" : ObjectId("5e35ee5f40713a43aeeeb1c5"),
    "c_ID" : ObjectId("5e35f2c840713a43aeeeb3d9"),
    "fromID" : "1",
    "msg" : "What's up?",
    "t" : 1580591922,
    "d" : {
        "4" : 1580592039
    },
    "r" : {
        "4" : 1580592339
    }
}

Body:
We can exclude them during $filter stage with $and and $or operators.

member.uID != 1 && (member.l == undefined || lastMessage.t < member.l)

Take a look query below.

db.conversations.aggregate([
  {
    $lookup: {
      from: "messages",
      foreignField: "c_ID",
      localField: "_id",
      as: "messages"
    }
  },
  {
    "$unwind": "$messages"
  },
  {
    "$sort": {
      "messages.t": -1
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "lastMessage": {
        "$first": "$messages"
      },
      "allFields": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$allFields",
          {
            "lastMessage": "$lastMessage"
          }
        ]
      }
    }
  },
  {
    $project: {
      messages: 0
    }
  },
  {
    $match: {
      "members.uID": "1"
    }
  },
  {
    $sort: {
      "lastMessage.t": 1
    }
  },
  {
    $limit: 10
  },
  {
    $project: {
      members: {
        $slice: [
          {
            $filter: {
              input: "$members",
              as: "member",
              cond: {
                $and: [
                  {
                    $ne: [
                      "$$member.uID",
                      "1"
                    ]
                  },
                  {
                    $or: [
                      {
                        $eq: [
                          "$$member.l",
                          undefined
                        ]
                      },
                      {
                        $lt: [
                          "$lastMessage.t",
                          "$$member.l"
                        ]
                      }
                    ]
                  }
                ]
              }
            }
          },
          3
        ]
      }
    }
  }
])

MongoPlayground


问:
Cart and Cart Item relations in Django Rest Framework
```<code>models.py

class Cart(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="cart")
    create_date = models.DateTimeField(auto_now_add=True)

class Item(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE,related_name='items')
    product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='product')
    quantity = models.IntegerField(default=1)
</code>```

```<code>serializers.py

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['user','status']

class ItemSerializer(serializers.ModelSerializer):
    cart = CartSerializer()
    class Meta:
        model = Item
        fields = ['cart', 'product', 'quantity']
</code>```

```<code>urls.py

urlpatterns = [
    path('add/', AddItem.as_view(),name='add'),
]
</code>```

```<code>views.py

class AddItem(CreateAPIView):
    serializer_class = ItemSerializer
    permission_classes = [IsAuthenticated]
</code>```

How can I connect the "cart" in Item without asking it directly in Django Rest Framework? I'm sending {"product":1,"quantity":1}, however it asks for "cart" to be sent. I can't figure out how to make DRF automatically resolve it as it's connected to the cart.

答: Because you used ModelSerializer and define cart in fields list inside ItemSerializer. Serializer validate methods checks your data based on your model. You can find details here</p>

Body:
models.py

class Cart(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="cart")
    create_date = models.DateTimeField(auto_now_add=True)

class Item(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE,related_name='items')
    product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='product')
    quantity = models.IntegerField(default=1)

serializers.py

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['user','status']

class ItemSerializer(serializers.ModelSerializer):
    cart = CartSerializer()
    class Meta:
        model = Item
        fields = ['cart', 'product', 'quantity']

urls.py

urlpatterns = [
    path('add/', AddItem.as_view(),name='add'),
]

views.py

class AddItem(CreateAPIView):
    serializer_class = ItemSerializer
    permission_classes = [IsAuthenticated]

How can I connect the "cart" in Item without asking it directly in Django Rest Framework? I'm sending {"product":1,"quantity":1}, however it asks for "cart" to be sent. I can't figure out how to make DRF automatically resolve it as it's connected to the cart.


问:
"Declare" clause before "Begin" clause in CREATE PROCEDURE
I wonder whether there is any difference between these two options of declaring variables in stored procedures? Any drawbacks?</p>

```<code>CREATE PROCEDURE dbo.HelloWorld
AS
    DECLARE @message NVARCHAR(30)
BEGIN
    SET @message = 'Hello World!'
    SELECT @message
END
GO

CREATE PROCEDURE dbo.HelloWorld2
AS
BEGIN
    DECLARE @message NVARCHAR(30)
    SET @message = 'Hello World!'
    SELECT @message
END
GO
</code>```

答:
No difference.  A stored procedure body is simply zero-or-more TSQL statements, and is terminated by the end of the batch containing the CREATE PROCEDURE: it's the GO that ends the procedure not the END.  This is why CREATE PROCEDURE must be the only statement in the batch.

The BEGIN..END around the stored procedure body is purely conventional, but is a strongly-recommended best-practice.

If you want to implement a pattern with forward declaration of variables ahead of a BEGIN..END block you may.  But it's unnecessary to declare all your variables at the top, and in languages that don't require forward declaration, it's typically considered poor form.

Body:
I wonder whether there is any difference between these two options of declaring variables in stored procedures? Any drawbacks?

CREATE PROCEDURE dbo.HelloWorld
AS
    DECLARE @message NVARCHAR(30)
BEGIN
    SET @message = 'Hello World!'
    SELECT @message
END
GO

CREATE PROCEDURE dbo.HelloWorld2
AS
BEGIN
    DECLARE @message NVARCHAR(30)
    SET @message = 'Hello World!'
    SELECT @message
END
GO


问:
JUnit test IndexOutOfBoundsException
I have a problem with my method get(int index) when index is out of bounds. I do not know how to throw the exception in a correct way in order to pass the test below.

```<code>    public E get(int index) throws IndexOutOfBoundsException {

    Node<E> tempNode = head;
    for (int i = 0; i < index; i++) {
        if (index < 0) {
            throw new IndexOutOfBoundsException();
        }
        if (index > size) {
            throw new IndexOutOfBoundsException();
        }

        tempNode = tempNode.getmNextNode();
    }
    return tempNode.getmElement();
}
</code>```

My JUnit test code:

```<code>/**
 * Create a single linked list containing 5 elements and try to get an
 * element using a too large index.
 * Assert that an IndexOutOfBoundsException is thrown by the get() method.
 */
@Test
public void testGetByTooLargeIndexFromListWith5Elements() {

    int listSize = 5;
    // First create an ArrayList with string elements that constitutes the test data
    ArrayList<Object> arrayOfTestData = generateArrayOfTestData(listSize);
    // Then create a single linked list consisting of the elements of the ArrayList
    ISingleLinkedList<Object> sll = createSingleLinkedListOfTestData(arrayOfTestData);

    // Index out of range => IndexOutOfBoundException
    try {
        sll.get(sll.size());
    }
    catch (IndexOutOfBoundsException e) {
        System.out.println("testGetByTooLargeIndexFromListWith5Elements - IndexOutOfBoundException catched - " + e.getMessage());
        assertTrue(true);
    }
    catch (Exception e) {
        fail("testGetByTooLargeIndexFromListWith5Elements - test failed. The expected exception was not catched");
    }
}
</code>```

答:
The proper way to verify this behavior depends on if you are using JUnit 4 or 5.

For JUnit 4, you annotate your test method with the expected exception:

```<code>@Test(expected = IndexOutOfBoundsException.class)
public void testGetByTooLargeIndexFromListWith5Elements() {...}
</code>```

JUnit 5 uses assertThrows, like so:

```<code>org.junit.jupiter.api.Assertions
  .assertThrows(IndexOutOfBoundsException.class, () -> sll.get(sll.size()));
</code>```

Title: JUnit test IndexOutOfBoundsException

Body:
I have a problem with my method get(int index) when index is out of bounds. I do not know how to throw the exception in a correct way in order to pass the test below.

    public E get(int index) throws IndexOutOfBoundsException {

    Node<E> tempNode = head;
    for (int i = 0; i < index; i++) {
        if (index < 0) {
            throw new IndexOutOfBoundsException();
        }
        if (index > size) {
            throw new IndexOutOfBoundsException();
        }

        tempNode = tempNode.getmNextNode();
    }
    return tempNode.getmElement();
}

My JUnit test code:

/**
 * Create a single linked list containing 5 elements and try to get an
 * element using a too large index.
 * Assert that an IndexOutOfBoundsException is thrown by the get() method.
 */
@Test
public void testGetByTooLargeIndexFromListWith5Elements() {

    int listSize = 5;
    // First create an ArrayList with string elements that constitutes the test data
    ArrayList<Object> arrayOfTestData = generateArrayOfTestData(listSize);
    // Then create a single linked list consisting of the elements of the ArrayList
    ISingleLinkedList<Object> sll = createSingleLinkedListOfTestData(arrayOfTestData);

    // Index out of range => IndexOutOfBoundException
    try {
        sll.get(sll.size());
    }
    catch (IndexOutOfBoundsException e) {
        System.out.println("testGetByTooLargeIndexFromListWith5Elements - IndexOutOfBoundException catched - " + e.getMessage());
        assertTrue(true);
    }
    catch (Exception e) {
        fail("testGetByTooLargeIndexFromListWith5Elements - test failed. The expected exception was not catched");
    }
}

Body:
The proper way to verify this behavior depends on if you are using JUnit 4 or 5.

For JUnit 4, you annotate your test method with the expected exception:

@Test(expected = IndexOutOfBoundsException.class)
public void testGetByTooLargeIndexFromListWith5Elements() {...}

JUnit 5 uses assertThrows, like so:

org.junit.jupiter.api.Assertions
  .assertThrows(IndexOutOfBoundsException.class, () -> sll.get(sll.size()));


问:
Extract either two or three words and exclude duplicates and accronyms
I have a group of names worded in a bizarre fashion. Here is a sample:

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

```<code>df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)
</code>```

This is what I'm getting returned

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

To be clear, goal would be to have this:

```<code>Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster
</code>```

data

```<code>df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)
</code>```

答:
What about:

```<code>(?<=[a-z])[A-Z](?=[.\sA-Z]).*
</code>```

Check here. Without experience in R I'm unsure if this would be accepted. Also, there may be neater patterns as I'm rather new to RegEx.

I've also included a (possibly unlikely) sample: Sammy J. WatkinsJ.S. Watkins

Body:
I have a group of names worded in a bizarre fashion. Here is a sample:

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)

This is what I'm getting returned

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

To be clear, goal would be to have this:

Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster

data

df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)

Body:
What about:

(?<=[a-z])[A-Z](?=[.\sA-Z]).*

Check here. Without experience in R I'm unsure if this would be accepted. Also, there may be neater patterns as I'm rather new to RegEx.

I've also included a (possibly unlikely) sample: Sammy J. WatkinsJ.S. Watkins


问:
How to make a div with glassy and semi transparent effect?
I want to give a div a glassy reflection appearance as well as a semi transparent effect. How can I combine these two effects so that the div will look like a glassy transparent gadget? Is there a way to do this?

The div's bgcolor is lightskyblue and no background image is set yet.

答:
I was curious if I could do this and haven't found a good example so I'll update this for 2020.

screenshot

I did it in few ways:

diagonal transparent-opaque alternating gradient for reflection

backdrop-filter: blur( - not for all browsers, not firefox default in 2020

or javascript clone and filter: blur( effect

// for only bottom div

const pre = document.getElementsByTagName("pre")[0];
const background = document.getElementsByClassName("background")[0];
const glossy3 = document.getElementsByClassName("glossy3")[0];
// clone it
var blurit = pre.cloneNode(true);
// make it blurit class
blurit.classList.add("blurit");
// attach to background too
background.appendChild(blurit);

const redraw = async () => {
  // get dimentions of glossy3 div
  const size = glossy3.getBoundingClientRect();
  const presize = pre.getBoundingClientRect();
  const divScrolledY = background.scrollTop
 // apply these dimentions to blured background clip-path (crop)
  blurit.style.clipPath = `inset(
   ${size.top + divScrolledY}px
    ${presize.width - size.right}px
    ${presize.height - size.bottom - divScrolledY}px
    ${size.left}px
    round ${ window.innerWidth * 0.02 }px
  )`;
  // 10 milisecond pause
  await new Promise(res => setTimeout(res, 10));
  // call yourself recursively via browser friendly method
  window.requestAnimationFrame(redraw);
}
/* call it once to loop forever - better than any timer */
redraw();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.glossy1 {

   /* blurs background */

  backdrop-filter: blur(4px) brightness(1.1) contrast(0.9) saturate(1.1);

  /* uses transparent background for glare */
  --col1: rgba(255,255,255, 0.3);
  --col2: rgba(255,255,255, 0.8);

  background: linear-gradient(-45deg,  var(--col1) 0%, var(--col2) 33%, var(--col1) 66%, var(--col2) 100%);

  /* background-color does nothing while gradient is up but this works for another tint: */
  box-shadow: inset 0 0 0 100vw rgba(0, 0, 150, 0.05);

  /* at same div level need this */
  z-index: 2;
}

.glossy2 {

  /* blue tint */
  box-shadow: inset 0 0 0 100vw rgba(20, 20, 150, 0.09);

  /* uses transparent background for glare */
  --col1: rgba(255,255,255, 0.80);
  --col2: rgba(255,255,255, 0.99);

  background: linear-gradient(-45deg,  var(--col1) 0%, var(--col2) 33%, var(--col1) 66%, var(--col2) 100%);

 /* background-color does nothing while gradient is up but this works for another tint: */
  box-shadow: inset 0 0 0 100vw rgba(0, 0, 150, 0.05);

  /* at same div level need this */
  z-index: 2;
}

.glossy3 {
  z-index: 2;

  /* blue tint */
  box-shadow: inset 0 0 0 100vw rgba(20, 20, 150, 0.09);

  /* uses transparent background for glare  */
  --col1: rgba(255,255,255, 0.3);
  --col2: rgba(255,255,255, 0.8);

  background: linear-gradient(-45deg,  var(--col1) 0%, var(--col2) 33%, var(--col1) 66%, var(--col2) 100%);
}

/* js adds on clipPath on top of this to crop it only under glossy3 */
.blurit {
  position: absolute;
  top: 0;
  left: 0;
  /* more supported filter */

  color: black;
  z-index: 1;
  filter: blur(4px) brightness(1) contrast(1) saturate(0.9);
  /* blocks other pre layer */
  background-color: rgba(255,255,255, 0.9);
}

@supports (backdrop-filter: blur(1px)) {
  .glossy {
    /* can put stuff here */
  }
}

@supports not (backdrop-filter: blur(1px)) {
  .glossy {
    /* can put stuff here */
  }
}

.irrelevant {
  /* irrelevant stuff */
  top: 50%;
  left: 50%;
  display: block;
  position: fixed;
  box-sizing: border-box; /* includes padding in calculation */
  transform: translate(-50%, -50%);

  /* styling because why not */
  padding: calc(2 * (1vw + 1vh));
  font-size: calc(1.5 * (1vw + 1vh));
  text-align: center;
  border-radius: 2vw;
  width: 80%;
}

.irrelevant1 {
  top: 20%;
}

.irrelevant3 {
  top: 80%;
}

/* making background with text and random image so can see div effects better */
body, html {

  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  font-size: calc(1 * (1vw + 1vh));
  background-color: lightblue;
  overflow-x: hidden;
  overflow-y: hidden;
}

.background,
.background::before {
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
}

.background::before {
  content: "";
  background-image: url("https://i.imgur.com/up3AMmC.jpg");
  background-repeat: repeat;
  background-size: cover;
  background-position: center;
  opacity: 0.25;
  z-index: -2;
}

.background {
  overflow-y: scroll;
}

pre {
  /* color: transparent; */
  margin: 0;
  padding: 0;
}</code>```

  backdrop-filter blur effect

  for chrome and others

  firefox not support by default yet (2020)

  basic glare gradient only

  even firefox can do

  javascript with blur on cloned layer

  + glare gradient

  even firefox can do

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris cursus dui eu lacus pretium malesuada. Suspendisse potenti. Maecenas sit amet vestibulum quam. Suspendisse iaculis sed sem venenatis mattis. Vestibulum sed imperdiet justo. Nunc pharetra ante vitae ligula faucibus ullamcorper. Proin rutrum leo est, eu convallis arcu rutrum vel.

Duis congue enim quis mauris tincidunt ornare. Nullam vehicula diam vel erat ornare, et posuere enim dapibus. Vestibulum aliquam semper tortor, vel fringilla eros faucibus in. Suspendisse potenti. Nam aliquam mi nisl, eu porta eros auctor maximus. Proin tempus vestibulum nisi, a hendrerit quam varius a. Donec dui massa, rhoncus ut commodo non, eleifend vitae mauris. Nam pharetra lobortis magna eget pretium. Donec non gravida velit, et malesuada massa. Nullam iaculis, neque tincidunt cursus maximus, nisl ligula mattis felis, ac molestie lectus eros sed dolor. Nullam vel condimentum justo. Aliquam scelerisque eget metus non ornare.

In nulla tellus, consectetur vitae mattis sed, imperdiet luctus odio. Pellentesque metus dolor, maximus posuere rutrum et, condimentum quis erat. Donec rhoncus metus sit amet tortor lobortis tincidunt. Praesent arcu orci, fermentum auctor eros id, bibendum aliquam diam. Curabitur aliquet vel massa ac cursus. Mauris molestie convallis nisi, sit amet vestibulum turpis consectetur quis. Vivamus ut convallis enim. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc quis lectus vitae turpis dictum elementum.

Nullam ultricies mi in rhoncus vestibulum. In ultrices convallis enim, ut pretium urna elementum nec. Cras quam leo, consequat non elit dapibus, ultricies consectetur est. Vivamus bibendum justo a felis rutrum tincidunt. Morbi sit amet nulla porttitor, tempus lacus eget, sollicitudin velit. Nunc non nulla turpis. Sed dictum dictum eros, sagittis fermentum felis pretium a. Etiam a nunc ante. Cras pharetra mi eros, a aliquam mi faucibus in.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.
  ```
</div></code>```

https://jsfiddle.net/8hkawmvo/6/

Body:
I was curious if I could do this and haven't found a good example so I'll update this for 2020.

screenshot

I did it in few ways:

diagonal transparent-opaque alternating gradient for reflection

backdrop-filter: blur( - not for all browsers, not firefox default in 2020

or javascript clone and filter: blur( effect

// for only bottom div

const pre = document.getElementsByTagName("pre")[0];
const background = document.getElementsByClassName("background")[0];
const glossy3 = document.getElementsByClassName("glossy3")[0];
// clone it
var blurit = pre.cloneNode(true);
// make it blurit class
blurit.classList.add("blurit");
// attach to background too
background.appendChild(blurit);

const redraw = async () => {
  // get dimentions of glossy3 div
  const size = glossy3.getBoundingClientRect();
  const presize = pre.getBoundingClientRect();
  const divScrolledY = background.scrollTop
 // apply these dimentions to blured background clip-path (crop)
  blurit.style.clipPath = `inset(
   ${size.top + divScrolledY}px
    ${presize.width - size.right}px
    ${presize.height - size.bottom - divScrolledY}px
    ${size.left}px
    round ${ window.innerWidth * 0.02 }px
  )`;
  // 10 milisecond pause
  await new Promise(res => setTimeout(res, 10));
  // call yourself recursively via browser friendly method
  window.requestAnimationFrame(redraw);
}
/* call it once to loop forever - better than any timer */
redraw();

.glossy1 {

   /* blurs background */

  backdrop-filter: blur(4px) brightness(1.1) contrast(0.9) saturate(1.1);

  /* uses transparent background for glare */
  --col1: rgba(255,255,255, 0.3);
  --col2: rgba(255,255,255, 0.8);

  background: linear-gradient(-45deg,  var(--col1) 0%, var(--col2) 33%, var(--col1) 66%, var(--col2) 100%);

  /* background-color does nothing while gradient is up but this works for another tint: */
  box-shadow: inset 0 0 0 100vw rgba(0, 0, 150, 0.05);

  /* at same div level need this */
  z-index: 2;
}

.glossy2 {

  /* blue tint */
  box-shadow: inset 0 0 0 100vw rgba(20, 20, 150, 0.09);

  /* uses transparent background for glare */
  --col1: rgba(255,255,255, 0.80);
  --col2: rgba(255,255,255, 0.99);

  background: linear-gradient(-45deg,  var(--col1) 0%, var(--col2) 33%, var(--col1) 66%, var(--col2) 100%);

 /* background-color does nothing while gradient is up but this works for another tint: */
  box-shadow: inset 0 0 0 100vw rgba(0, 0, 150, 0.05);

  /* at same div level need this */
  z-index: 2;
}

.glossy3 {
  z-index: 2;

  /* blue tint */
  box-shadow: inset 0 0 0 100vw rgba(20, 20, 150, 0.09);

  /* uses transparent background for glare  */
  --col1: rgba(255,255,255, 0.3);
  --col2: rgba(255,255,255, 0.8);

  background: linear-gradient(-45deg,  var(--col1) 0%, var(--col2) 33%, var(--col1) 66%, var(--col2) 100%);
}

/* js adds on clipPath on top of this to crop it only under glossy3 */
.blurit {
  position: absolute;
  top: 0;
  left: 0;
  /* more supported filter */

  color: black;
  z-index: 1;
  filter: blur(4px) brightness(1) contrast(1) saturate(0.9);
  /* blocks other pre layer */
  background-color: rgba(255,255,255, 0.9);
}

@supports (backdrop-filter: blur(1px)) {
  .glossy {
    /* can put stuff here */
  }
}

@supports not (backdrop-filter: blur(1px)) {
  .glossy {
    /* can put stuff here */
  }
}

.irrelevant {
  /* irrelevant stuff */
  top: 50%;
  left: 50%;
  display: block;
  position: fixed;
  box-sizing: border-box; /* includes padding in calculation */
  transform: translate(-50%, -50%);

  /* styling because why not */
  padding: calc(2 * (1vw + 1vh));
  font-size: calc(1.5 * (1vw + 1vh));
  text-align: center;
  border-radius: 2vw;
  width: 80%;
}

.irrelevant1 {
  top: 20%;
}

.irrelevant3 {
  top: 80%;
}

/* making background with text and random image so can see div effects better */
body, html {

  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  font-size: calc(1 * (1vw + 1vh));
  background-color: lightblue;
  overflow-x: hidden;
  overflow-y: hidden;
}

.background,
.background::before {
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
}

.background::before {
  content: "";
  background-image: url("https://i.imgur.com/up3AMmC.jpg");
  background-repeat: repeat;
  background-size: cover;
  background-position: center;
  opacity: 0.25;
  z-index: -2;
}

.background {
  overflow-y: scroll;
}

pre {
  /* color: transparent; */
  margin: 0;
  padding: 0;
}

<div class="glossy1 irrelevant1 irrelevant">
  backdrop-filter blur effect <br>
  for chrome and others<br>
  firefox not support by default yet (2020)
</div>

<div class="glossy2 irrelevant2 irrelevant">
  basic glare gradient only<br>
  even firefox can do
</div>

<div class="glossy3 irrelevant3 irrelevant">
  javascript with blur on cloned layer <br>
  + glare gradient<br>
  even firefox can do
</div>

<!-- background stuff -->
<div class="background">
  <pre style="white-space: pre-line; ">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris cursus dui eu lacus pretium malesuada. Suspendisse potenti. Maecenas sit amet vestibulum quam. Suspendisse iaculis sed sem venenatis mattis. Vestibulum sed imperdiet justo. Nunc pharetra ante vitae ligula faucibus ullamcorper. Proin rutrum leo est, eu convallis arcu rutrum vel.

Duis congue enim quis mauris tincidunt ornare. Nullam vehicula diam vel erat ornare, et posuere enim dapibus. Vestibulum aliquam semper tortor, vel fringilla eros faucibus in. Suspendisse potenti. Nam aliquam mi nisl, eu porta eros auctor maximus. Proin tempus vestibulum nisi, a hendrerit quam varius a. Donec dui massa, rhoncus ut commodo non, eleifend vitae mauris. Nam pharetra lobortis magna eget pretium. Donec non gravida velit, et malesuada massa. Nullam iaculis, neque tincidunt cursus maximus, nisl ligula mattis felis, ac molestie lectus eros sed dolor. Nullam vel condimentum justo. Aliquam scelerisque eget metus non ornare.

In nulla tellus, consectetur vitae mattis sed, imperdiet luctus odio. Pellentesque metus dolor, maximus posuere rutrum et, condimentum quis erat. Donec rhoncus metus sit amet tortor lobortis tincidunt. Praesent arcu orci, fermentum auctor eros id, bibendum aliquam diam. Curabitur aliquet vel massa ac cursus. Mauris molestie convallis nisi, sit amet vestibulum turpis consectetur quis. Vivamus ut convallis enim. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc quis lectus vitae turpis dictum elementum.

Nullam ultricies mi in rhoncus vestibulum. In ultrices convallis enim, ut pretium urna elementum nec. Cras quam leo, consequat non elit dapibus, ultricies consectetur est. Vivamus bibendum justo a felis rutrum tincidunt. Morbi sit amet nulla porttitor, tempus lacus eget, sollicitudin velit. Nunc non nulla turpis. Sed dictum dictum eros, sagittis fermentum felis pretium a. Etiam a nunc ante. Cras pharetra mi eros, a aliquam mi faucibus in.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.

Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus non aliquam leo. Fusce faucibus volutpat magna et tempor. Praesent in lorem a tortor pulvinar laoreet. Curabitur sit amet justo non massa aliquet pulvinar id vitae sem. Maecenas ullamcorper, felis sed volutpat aliquam, mauris odio pharetra diam, in vestibulum ante tellus vitae est. Suspendisse efficitur massa leo, non maximus risus molestie quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas tempus venenatis est vel sagittis. Fusce scelerisque mauris purus, a ornare est semper eget. Fusce commodo malesuada libero, imperdiet ullamcorper nibh rutrum quis. Donec quis ex eu diam varius pretium ut eget diam. Vivamus in interdum enim.
  </pre>
</div>

https://jsfiddle.net/8hkawmvo/6/


答: Instead of using a try-catch block in JUnit tests, just add to the test annotation. Update @Test to @Test(expected = IndexOutOfBoundsException.class.

Title: JUnit test IndexOutOfBoundsException


问:
Is Future.wait trully asynchonous in Dart?
I need to wait for many Future to complete their computation, a bunch of HTTP requests, I don't want to await all of them in order as this will result in each Future being evaluated in order, one after the other, kinda synchronously, which is wasteful as some Future might complete sooner than others.

I can't find in the docs of Future.wait is truly asynchronous, firing all the Future at the same time, or if its the same as calling them one after the other, waiting for the previous to complete to call the next.

In a nushell: I am looking for the best performant way to get the results of many HTTP requests in Dart.

答:
If you check the implementation of the Future.wait method in:

https://github.com/dart-lang/sdk/blob/a75ffc89566a1353fb1a0f0c30eb805cc2e8d34c/sdk/lib/async/future.dart#L354-L443

You can actually see it goes through each Future in the input list and runs the then method which a method to be run when the Future completes:

```<code>      for (var future in futures) {
        int pos = remaining;
        future.then((T value) {
        ...
</code>```

You could therefore say that all Future instances are "started" at the same time since each completed Future will end up checking if there are more futures to wait for.

However, please note that Dart is single threaded with a job queue behind the scene, so unless some of the work are done in Isolate instances, each job will end up running in serial. More details about this can be found here:

https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a

But yes, if you have a bunch if Future's which can be handles in any order it makes sense to use the Future.wait method.

Body:
If you check the implementation of the Future.wait method in:

https://github.com/dart-lang/sdk/blob/a75ffc89566a1353fb1a0f0c30eb805cc2e8d34c/sdk/lib/async/future.dart#L354-L443

You can actually see it goes through each Future in the input list and runs the then method which a method to be run when the Future completes:

      for (var future in futures) {
        int pos = remaining;
        future.then((T value) {
        ...

You could therefore say that all Future instances are "started" at the same time since each completed Future will end up checking if there are more futures to wait for.

However, please note that Dart is single threaded with a job queue behind the scene, so unless some of the work are done in Isolate instances, each job will end up running in serial. More details about this can be found here:

https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a

But yes, if you have a bunch if Future's which can be handles in any order it makes sense to use the Future.wait method.


问:
jQuery selector optimization

Be specific on the right-hand side of your selector, and less specific on the left.

```<code>// unoptimized
$('div.data .gonzalez');

// optimized
$('.data td.gonzalez');
</code>```

Quote Source

Could someone explain why the less specific left is faster as a CSS selector?

Is this a Sizzle thing or does the same apply for document.querySelectorAll ?

Are there any speed gains using "similarly optimised" CSS selectors in CSS files?

答:
The book sort of mentions this in passing, but I'm fairly certain that advice is specific to Sizzle (the jQuery selector engine), not generally. Your mileage may vary, but a browser that implements querySelectorAll is unlikely to show a real-world difference.

Sizzle works inside-out when appropriate, and so may look for td.gonzales and then look to see if it's within a .data, rather than the other way around. I remember when Sizzle first came out, this was a bit of a surprise, but it actually worked out better. So you can see why the more specific the right-hand side of the descendant selector, the better.

Here's a test case, try that in IE7 and you'll see a marked preference for the more specific right-hand side. But try it in a modern browser and you should seem basically no difference.

This is all micro-optimization, though, and pretty much useless in the absence of a real-world problem to solve, because it varies dramatically based on the elements on your page. Useful to remember if you actually have a slow selector causing you trouble on older browsers, perhaps, but other than that...

Title: jQuery selector optimization

Body:
Be specific on the right-hand side of your selector, and less specific on the left.

// unoptimized
$('div.data .gonzalez');

// optimized
$('.data td.gonzalez');

Quote Source

Could someone explain why the less specific left is faster as a CSS selector?

Is this a Sizzle thing or does the same apply for document.querySelectorAll ?

Are there any speed gains using "similarly optimised" CSS selectors in CSS files?


问:
Express deprecated res.redirect(url, status): Use res.redirect(status, url) instead
I am trying to send a post request and i get this error Express deprecated res.redirect(url, status): Use res.redirect(status, url) instead</p>

```<code>app.post("/blogs/:id/likes", isLoggedIn,function(req, res){
//lookup Campground using ID
Blog.findById(req.params.id, function(err, blog){
   if(err){
       console.log(err);
       res.redirect("/blogs");
   } else {
           //add username and id to comment
     var userIndex = blog.likes.indexOf(req.user._id);
if (userIndex > -1) {
blog.likes.splice(userIndex, 1);
} else {
blog.likes.push(req.user);
}
blog.save();

           res.redirect('/blogs/' + blog._id, {blog_id: req.params.id});

   }
});
});
</code>```

答:
Use the res.render method if you want to pass something to your view which accepts (view, locals, callback).

```<code>res.render('/blogs/' + blog._id, {blog_id: req.params.id});
</code>```

res.redirect can only take (status, path).

More info on Express 5x api ⭐

Body:
I am trying to send a post request and i get this error Express deprecated res.redirect(url, status): Use res.redirect(status, url) instead

app.post("/blogs/:id/likes", isLoggedIn,function(req, res){
//lookup Campground using ID
Blog.findById(req.params.id, function(err, blog){
   if(err){
       console.log(err);
       res.redirect("/blogs");
   } else {
           //add username and id to comment
     var userIndex = blog.likes.indexOf(req.user._id);
if (userIndex > -1) {
blog.likes.splice(userIndex, 1);
} else {
blog.likes.push(req.user);
}
blog.save();

           res.redirect('/blogs/' + blog._id, {blog_id: req.params.id});

   }
});
});

Body:
Use the res.render method if you want to pass something to your view which accepts (view, locals, callback).

res.render('/blogs/' + blog._id, {blog_id: req.params.id});

res.redirect can only take (status, path).

More info on Express 5x api ⭐


问:
Is there any command to toggle enable auto text wrapping?
By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.</p>

答:
Add the following to have CTRL+W toggle wrapping. You can change it to some other key if you don't want w to be it.

```<code>map <C-w> :set wrap!<CR>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Add the following to have CTRL+W toggle wrapping. You can change it to some other key if you don't want w to be it.

map <C-w> :set wrap!<CR>


问:
NGINX - Error 502 unless User-Agent header is set
I have a very strange issue with NGINX.

We're routing to different servers based on the URL. This all works completely fine. Using a browser, everything works great.

The weird thing is when I try to make a GET request to the API from a tool (like Postman, Insomnia, Curl, etc.) If the User-Agent header is not spoofed to a browser, I get a 502 Bad Gateway error.

Why is this happening? I need to call this API programmatically from another back-end, but I must set the User-Agent header otherwise it will fail. (Setting the user-agent to "curl" does not work browser)

Here's my NGINX config

```<code>    server {
        listen 443 ssl;
        server_name 10.10.10.10;
        ssl_certificate /https/10.10.10.10.crt;
        ssl_certificate_key /https/10.10.10.10.key;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:!aNULL:!MD5;

    access_log              /var/log/nginx/10.10.10.10-access.log;
    error_log               /var/log/nginx/10.10.10.10-error.log error;

        location /abc {
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Frame-Options SAMEORIGIN;
                proxy_pass http://10.3.0.2:80;
        }

        location /def {
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Frame-Options SAMEORIGIN;
                proxy_pass http://10.3.0.3:80;
        }
}
</code>```

Requests from the browser work completely fine.

Request from Insomnia WITH User-Agent spoofed (works great!)

Request from Insomnia WITHOUT User-Agent spoofed (error 502!?)

Note: I'm setting the cookies in this request as they're used by the server on the back-end. Not sure if this is related to the user-agent issue...

Thank you!

答:
Sorry. Found it. Rookie mistake on my end! It was not a problem with nginx at all.

The Flask server actually had a line to serve a "change your browser" message if the user wasn't on Chrome, to avoid browser compatibility issues. Unfortunately, the browser_splash file was deleted, so it just wasn't serving anything in that case. Didn't notice that this got committed:

```<code>if request.user_agent.browser != 'chrome':
  return render_template('browser_splash.html')
</code>```

Body:
I have a very strange issue with NGINX.

We're routing to different servers based on the URL. This all works completely fine. Using a browser, everything works great.

The weird thing is when I try to make a GET request to the API from a tool (like Postman, Insomnia, Curl, etc.) If the User-Agent header is not spoofed to a browser, I get a 502 Bad Gateway error.

Why is this happening? I need to call this API programmatically from another back-end, but I must set the User-Agent header otherwise it will fail. (Setting the user-agent to "curl" does not work browser)

Here's my NGINX config

    server {
        listen 443 ssl;
        server_name 10.10.10.10;
        ssl_certificate /https/10.10.10.10.crt;
        ssl_certificate_key /https/10.10.10.10.key;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:!aNULL:!MD5;

    access_log              /var/log/nginx/10.10.10.10-access.log;
    error_log               /var/log/nginx/10.10.10.10-error.log error;

        location /abc {
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Frame-Options SAMEORIGIN;
                proxy_pass http://10.3.0.2:80;
        }

        location /def {
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Frame-Options SAMEORIGIN;
                proxy_pass http://10.3.0.3:80;
        }
}

Requests from the browser work completely fine.

Request from Insomnia WITH User-Agent spoofed (works great!)

Request from Insomnia WITHOUT User-Agent spoofed (error 502!?)

Note: I'm setting the cookies in this request as they're used by the server on the back-end. Not sure if this is related to the user-agent issue...

Thank you!

Body:
Sorry. Found it. Rookie mistake on my end! It was not a problem with nginx at all.

The Flask server actually had a line to serve a "change your browser" message if the user wasn't on Chrome, to avoid browser compatibility issues. Unfortunately, the browser_splash file was deleted, so it just wasn't serving anything in that case. Didn't notice that this got committed:

if request.user_agent.browser != 'chrome':
  return render_template('browser_splash.html')


问:
subclassing classes in Cocoa
My question is : Why Apple prohibit some classes to be subclassed, for example MKMapView ?

What is the reason to do this please ?

thanks for your answers

答:
The short answer is that although they look like normal classes, they probably aren't. This means that subclassing them without some knowledge of how they're implemented probably won't do what you're expecting.

There are some, like the collection classes, that you can subclass but you need to follow some documented rules. And there are others that they just say "don't." I've seen developers ignore this advice only to find that their app breaks on the next iOS update.

The good news is that the way that these classes are implemented usually means that if you're trying to subclass them you're probably doing it wrong. Cocoa heavily relies on delegates and composition, which means that you tend to subclass system components far less often than you would in other frameworks such as Java and .Net.

Title: subclassing classes in Cocoa


问:
How to provide a global .htpassword file to multiple Docker Swarm Stacks?
I am running around 20 service stacks on a docker swarm host that all expose their individual https frontends which are protected by basic auth using Traefik (same username and password for all services).

I would love to centrally manage the .htpassword file or username/passwordHash, so that if there is a requirement for a password change, I can do it once and it will affect all services immediately or after redeployment. I am using Swarmpit to orchestrate Docker Swarm.

I looked into Docker Secrets and Docker Configs but both seem to be immutable if actively used by a running service. I also thought about environment variables, but I cannot really find my way through.

How should I go about this?

答:
You can potentially do this with a shared volume, placing the file in one volume and having all the containers mount that volume. If the swarm containers are spread across multiple nodes, you would need to either mount a network volume (e.g. NFS), or update the volume on each host individually.

This sort of use case is precisely what a docker secret or docker config are designed to solve. You inject the contents of the file into the secret/config, and docker automatically deploys that to each node where the service is being run.

Yes, these are immutable. And you won't hot swap these in an existing container. When you make the change and it's managed by swarm, you will get a rolling update of the services. What I've done to manage this in my environment is to inject a version number of the secret/config as an environment variable, and update that variable using a script. I've got that script and example usage up here: https://github.com/sudo-bmitch/docker-config-update


问:
WordPress - Set User to Expire after a Certain Date
I am working on a site for a school program. During registration, students are going to be asked to select their graduation year from a dropdown. I want the system to check this value against the current time each time that they log in, and change their roles if the graduation date is past the current time. The code I wrote is below, however I am getting no errors either in logs or WP_DEBUG

```<code>/* Check if Student Has Graduated and Change Role */
add_action('wp_login', 'check_graduated', 10, 2);
function check_graduated($user_login, $user) {
    /* Ger User Id */
    $user_id = $user -> $id;

    /* Check if Graduation Date exists in DB */
    if($grad_year = get_user_meta($user_id, 'user_registration_user_graduation_date', true)) {
        $current_date = time();

        /* Convert Grad Year to Time */
        $grad_date_str = "07/01/" . $grad_year;
        $grad_date = stringtotime($grad_date_str);

        /* Change User Role if Today is Past The Graduation Date */
        if($current_date > $grad_date) {
            change_user_role($user_id, 'former_student', 'student');
        }
    }
}

function change_user_role($id, $new_role, $old_role) {
    $user = new WP_User( $id );
    $user -> remove_role( $old_role );
    $user -> add_role ( $new_role );
}
</code>```

In the Usermeta table of the database, the following exists:

```<code>|----------------------------------------------------------------------------------|
|  UMETA_ID  |  USER_ID  |                 META_KEY                 |  META_VALUE  |
|----------------------------------------------------------------------------------|
|     36     |     2     |  user_registration_user_graduation_date  |     2016     |
|----------------------------------------------------------------------------------|
</code>```

Like I said, no errors show up when logging in with the user with ID 2. Am I missing something or just dumb?

答: do you have a method called stringtotime? I think php's time conversion function is strtotime. typo?</p>

Body:
I am working on a site for a school program. During registration, students are going to be asked to select their graduation year from a dropdown. I want the system to check this value against the current time each time that they log in, and change their roles if the graduation date is past the current time. The code I wrote is below, however I am getting no errors either in logs or WP_DEBUG

/* Check if Student Has Graduated and Change Role */
add_action('wp_login', 'check_graduated', 10, 2);
function check_graduated($user_login, $user) {
    /* Ger User Id */
    $user_id = $user -> $id;

    /* Check if Graduation Date exists in DB */
    if($grad_year = get_user_meta($user_id, 'user_registration_user_graduation_date', true)) {
        $current_date = time();

        /* Convert Grad Year to Time */
        $grad_date_str = "07/01/" . $grad_year;
        $grad_date = stringtotime($grad_date_str);

        /* Change User Role if Today is Past The Graduation Date */
        if($current_date > $grad_date) {
            change_user_role($user_id, 'former_student', 'student');
        }
    }
}

function change_user_role($id, $new_role, $old_role) {
    $user = new WP_User( $id );
    $user -> remove_role( $old_role );
    $user -> add_role ( $new_role );
}

In the Usermeta table of the database, the following exists:

|----------------------------------------------------------------------------------|
|  UMETA_ID  |  USER_ID  |                 META_KEY                 |  META_VALUE  |
|----------------------------------------------------------------------------------|
|     36     |     2     |  user_registration_user_graduation_date  |     2016     |
|----------------------------------------------------------------------------------|

Like I said, no errors show up when logging in with the user with ID 2. Am I missing something or just dumb?