问:
Android Mobile Vision API detect mouth is open
I am exploring wonderful mobile vision apis, I am working on Face Tracker example and looking for a solution where I can find out whether mouth is open or not. e.g. person is yawning. There is not direct way like face.getIsLeftEyeOpenProbability();

So I am thinking that I need to find out x,y coordinates of both left and right mouth find out the difference and figure out whether mouse is open or not. I am not sure if this will work or not.

But is there any other way we can find out whether mouth is open or closed ?

答:
Mobile Vision API does not give direct support for Mouth open/close detection. But this code may help you. I have tested and working charm on my device.

```<code> @Override
    public void draw(Canvas canvas) {

        Face face = mFace;

        if (face == null) {
            return;
        }

        if ((contains(face.getLandmarks(), 11) != 99)
                && (contains(face.getLandmarks(), 5) != 99)
                && (contains(face.getLandmarks(), 6) != 99)
                ) {

            Log.i(TAG, "draw: Mouth Open >> found all the points");

            /**
             * for bottom mouth
             */
            int cBottomMouthX;
            int cBottomMouthY;
            if (FaceTrackerActivity.mIsFrontFacing) {
                cBottomMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().x);
                cBottomMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().y);

                Log.i(TAG, "draw: Condition Bottom mouth >> cBottomMouthX >> " + cBottomMouthX + "    cBottomMouthY >> " + cBottomMouthY);

            } else {
                cBottomMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().x);
                cBottomMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().y);
            }
            canvas.drawCircle(cBottomMouthX, cBottomMouthY, 10, mPaint);

            /**
             * for left mouth
             */
            int cLeftMouthX;
            int cLeftMouthY;
            if (FaceTrackerActivity.mIsFrontFacing) {
                cLeftMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().x);
                cLeftMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().y);

                Log.i(TAG, "draw: Condition LEft mouth >> cLeftMouthX >> " + cLeftMouthX + "    cLeftMouthY >> " + cLeftMouthY);

            } else {
                cLeftMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().x);
                cLeftMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().y);
            }
            canvas.drawCircle(cLeftMouthX, cLeftMouthY, 10, mPaint);

            /**
             * for Right mouth
             */
            int cRightMouthX;
            int cRightMouthY;
            if (FaceTrackerActivity.mIsFrontFacing) {
                cRightMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().x);
                cRightMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().y);

                Log.i(TAG, "draw: Condition Right mouth >> cRightMouthX >> " + cRightMouthX + "    cRightMouthY >> " + cRightMouthY);

            } else {
                cRightMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().x);
                cRightMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().y);
            }
            canvas.drawCircle(cRightMouthX, cRightMouthY, 10, mPaint);

            float centerPointX = (cLeftMouthX + cRightMouthX) / 2;
            float centerPointY = ((cLeftMouthY + cRightMouthY) / 2) - 20;

            canvas.drawCircle(centerPointX, centerPointY, 10, mPaint);

            float differenceX = centerPointX - cBottomMouthX;
            float differenceY = centerPointY - cBottomMouthY;

            Log.i(TAG, "draw: difference X >> " + differenceX + "     Y >> " + differenceY);

            if (differenceY < (-60)) {
                Log.i(TAG, "draw: difference - Mouth is OPENED ");
            } else {
                Log.i(TAG, "draw: difference - Mouth is CLOSED ");
            }
         }
     }
</code>```

And here is an another method.

```<code>int contains(List<Landmark> list, int name) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).getType() == name) {
            return i;
        }
    }
    return 99;
}
</code>```

P.S - This code will find find center point cordinates of Left and Right mouth and find the difference between Bottom mouth cordinates and center points cordinates.

Body:
Mobile Vision API does not give direct support for Mouth open/close detection. But this code may help you. I have tested and working charm on my device.

 @Override
    public void draw(Canvas canvas) {

        Face face = mFace;

        if (face == null) {
            return;
        }

        if ((contains(face.getLandmarks(), 11) != 99)
                && (contains(face.getLandmarks(), 5) != 99)
                && (contains(face.getLandmarks(), 6) != 99)
                ) {

            Log.i(TAG, "draw: Mouth Open >> found all the points");

            /**
             * for bottom mouth
             */
            int cBottomMouthX;
            int cBottomMouthY;
            if (FaceTrackerActivity.mIsFrontFacing) {
                cBottomMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().x);
                cBottomMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().y);

                Log.i(TAG, "draw: Condition Bottom mouth >> cBottomMouthX >> " + cBottomMouthX + "    cBottomMouthY >> " + cBottomMouthY);

            } else {
                cBottomMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().x);
                cBottomMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 0)).getPosition().y);
            }
            canvas.drawCircle(cBottomMouthX, cBottomMouthY, 10, mPaint);

            /**
             * for left mouth
             */
            int cLeftMouthX;
            int cLeftMouthY;
            if (FaceTrackerActivity.mIsFrontFacing) {
                cLeftMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().x);
                cLeftMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().y);

                Log.i(TAG, "draw: Condition LEft mouth >> cLeftMouthX >> " + cLeftMouthX + "    cLeftMouthY >> " + cLeftMouthY);

            } else {
                cLeftMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().x);
                cLeftMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 5)).getPosition().y);
            }
            canvas.drawCircle(cLeftMouthX, cLeftMouthY, 10, mPaint);

            /**
             * for Right mouth
             */
            int cRightMouthX;
            int cRightMouthY;
            if (FaceTrackerActivity.mIsFrontFacing) {
                cRightMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().x);
                cRightMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().y);

                Log.i(TAG, "draw: Condition Right mouth >> cRightMouthX >> " + cRightMouthX + "    cRightMouthY >> " + cRightMouthY);

            } else {
                cRightMouthX = (int) translateX(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().x);
                cRightMouthY = (int) translateY(face.getLandmarks().get(contains(face.getLandmarks(), 11)).getPosition().y);
            }
            canvas.drawCircle(cRightMouthX, cRightMouthY, 10, mPaint);

            float centerPointX = (cLeftMouthX + cRightMouthX) / 2;
            float centerPointY = ((cLeftMouthY + cRightMouthY) / 2) - 20;

            canvas.drawCircle(centerPointX, centerPointY, 10, mPaint);

            float differenceX = centerPointX - cBottomMouthX;
            float differenceY = centerPointY - cBottomMouthY;

            Log.i(TAG, "draw: difference X >> " + differenceX + "     Y >> " + differenceY);

            if (differenceY < (-60)) {
                Log.i(TAG, "draw: difference - Mouth is OPENED ");
            } else {
                Log.i(TAG, "draw: difference - Mouth is CLOSED ");
            }
         }
     }

And here is an another method.

int contains(List<Landmark> list, int name) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).getType() == name) {
            return i;
        }
    }
    return 99;
}

P.S - This code will find find center point cordinates of Left and Right mouth and find the difference between Bottom mouth cordinates and center points cordinates.


来源: stackexchange

问:
angucomplete-alto auto populate based in other input
i have 2 autocomplete select box with a particular feature, basically in the first autocomplate i have a input that accepts a code, and in this code is related with a label. So basically when i select the code of the first input it autofills the second input with the selected object related. But in the second input haves also a autocomplete feature since the code is not a required field.

Bit there is a detail in the first input (code), the code is always 2 charecters, not more or less, but the user can insert more than 2 charecters.
In my code it works fine, but there is a detail, the input 1 (code) it autoselects the object and the first input removes the extra charecters of the user, but i need to have them there. How do i customize it?

Module that im using for autocomplete is this one Angucomplete-Alt

My code is:

```<code><div angucomplete-alt
                                  id="flight_code"

                                  placeholder="flight code"
                                  pause="100"
                                  selected-object="claim.flight_details.flight_code"
                                  local-data="airlines"
                                  local-search="localSearch"
                                  search-fields="code_airline"
                                  title-field="code_airline"
                                  minlength="2"
                                  input-name="operating_airline"
                                  input-class="form-control form-control-small"
                                  match-class="highlight"
                                  field-required="false">

<div angucomplete-alt
                                   local-search="localSearch"
                                  id="operating_airline"
                                  placeholder="Search airline"
                                  pause="100"
                                  selected-object="claim.flight_details.operating_airline"
                                  local-data="airlines"
                                  search-fields="label"
                                  title-field="label"
                                  minlength="1"
                                  input-name="operating_airline"
                                  input-class="form-control form-control-small"
                                  match-class="highlight"
                                  field-required="true"
                                  initial-value="claim.flight_details.flight_code.originalObject">
                                </div>
</code>```

Controller:

```<code> $scope.localSearch = function(str, code_airline) {
  var matches = [];
  code_airline.forEach(function(code) {

      if(str.toString().substring(0, 2).toUpperCase() === code.code_airline){
          console.log("I found him!!");
          matches.push(code);
      }

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

答:
I resolved my issue, in made de first input code to a normal input a use the directive ngChange to detect the chareceters and than create a promise to search for the object and than inserted in the angcomplete input using the initialValue:

controller:

```<code>$scope.automaticFill = function(){
    var str = $scope.claim.flight_details.flight_code;
   if(str.toString().length === 2){
          console.log("Im changed");
       $http.get('data/airlines-companies.json').then(function(response){

        var airlines = response.data;

            airlines.forEach(function(code) {
            if(code.code_airline === str.toString().toUpperCase())
             $scope.test = code;
            });
        });

      }
};
</code>```

Html:

```<code> <input type="text"
                                class="form-control"
                                ng-model="claim.flight_details.flight_code"
                                name="flight_code"
                                id="flight_code"
                                ng-change="automaticFill()">

<div angucomplete-alt
                                   local-search="tap"
                                  id="operating_airline"
                                  placeholder="Search airline"
                                  pause="100"
                                  selected-object="claim.flight_details.operating_airline"
                                  local-data="airlines"
                                  search-fields="label"
                                  title-field="label"
                                  minlength="1"
                                  input-name="operating_airline"
                                  input-class="form-control form-control-small"
                                  match-class="highlight"
                                  field-required="true"
                                  initial-value="test">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have 2 autocomplete select box with a particular feature, basically in the first autocomplate i have a input that accepts a code, and in this code is related with a label. So basically when i select the code of the first input it autofills the second input with the selected object related. But in the second input haves also a autocomplete feature since the code is not a required field.

Bit there is a detail in the first input (code), the code is always 2 charecters, not more or less, but the user can insert more than 2 charecters.
In my code it works fine, but there is a detail, the input 1 (code) it autoselects the object and the first input removes the extra charecters of the user, but i need to have them there. How do i customize it?

Module that im using for autocomplete is this one Angucomplete-Alt

My code is:

<div angucomplete-alt
                                  id="flight_code"

                                  placeholder="flight code"
                                  pause="100"
                                  selected-object="claim.flight_details.flight_code"
                                  local-data="airlines"
                                  local-search="localSearch"
                                  search-fields="code_airline"
                                  title-field="code_airline"
                                  minlength="2"
                                  input-name="operating_airline"
                                  input-class="form-control form-control-small"
                                  match-class="highlight"
                                  field-required="false">

<div angucomplete-alt
                                   local-search="localSearch"
                                  id="operating_airline"
                                  placeholder="Search airline"
                                  pause="100"
                                  selected-object="claim.flight_details.operating_airline"
                                  local-data="airlines"
                                  search-fields="label"
                                  title-field="label"
                                  minlength="1"
                                  input-name="operating_airline"
                                  input-class="form-control form-control-small"
                                  match-class="highlight"
                                  field-required="true"
                                  initial-value="claim.flight_details.flight_code.originalObject">

Controller:

 $scope.localSearch = function(str, code_airline) {
  var matches = [];
  code_airline.forEach(function(code) {

      if(str.toString().substring(0, 2).toUpperCase() === code.code_airline){
          console.log("I found him!!");
          matches.push(code);
      }

  });
  return matches;
};

Body:
I resolved my issue, in made de first input code to a normal input a use the directive ngChange to detect the chareceters and than create a promise to search for the object and than inserted in the angcomplete input using the initialValue:

controller:

$scope.automaticFill = function(){
    var str = $scope.claim.flight_details.flight_code;
   if(str.toString().length === 2){
          console.log("Im changed");
       $http.get('data/airlines-companies.json').then(function(response){

        var airlines = response.data;

            airlines.forEach(function(code) {
            if(code.code_airline === str.toString().toUpperCase())
             $scope.test = code;
            });
        });

      }
};

Html:

 <input type="text"
                                class="form-control"
                                ng-model="claim.flight_details.flight_code"
                                name="flight_code"
                                id="flight_code"
                                ng-change="automaticFill()">

<div angucomplete-alt
                                   local-search="tap"
                                  id="operating_airline"
                                  placeholder="Search airline"
                                  pause="100"
                                  selected-object="claim.flight_details.operating_airline"
                                  local-data="airlines"
                                  search-fields="label"
                                  title-field="label"
                                  minlength="1"
                                  input-name="operating_airline"
                                  input-class="form-control form-control-small"
                                  match-class="highlight"
                                  field-required="true"
                                  initial-value="test">


问:
display image in detail view with one to many reation yii2
I have two tables with one-to-many relation,

This code will display the path not image. how to display image?

答:
The first way is setting the image format of this column:

```<code>    [
             'attribute'=>'photo',
             'format' => 'image',
             'value'=>'path/to/image',
    ],
</code>```

Body:
The first way is setting the image format of this column:

    [
             'attribute'=>'photo',
             'format' => 'image',
             'value'=>'path/to/image',
    ],


问:
is it possible to generate uml or jdl model from existing jhipster project
after generating j hipster project is it possible generate JDL model or uml diagram from the generated code in order to see how the application is build and relations between classes.</p>

答: As you can't import the user entity again it makes no sense to me to have it exported to a jdl file.</p>


问:
Best way to input Products into CRM
I would like to know what the best way to input products into CRM? I don’t much like how it is laid out in CRM now. I would like it to look more like a tree. Such as listed below.

Manufacturer: Akzo

Brand: Sikkens

Primer Brand: U-Tech

Primer Part Numbers: 399199 2K100 Grey

```<code>                             399200 2K Buff
</code>```

Sealer Brand: 398745 ColorBuild Plus

Basecoat Color System: AutoBase Plus

Basecoat Reducer: 394695 Lesonal Reducer

Clearcoat Brand (1): Sikkens

Clearcoat Brand (1) Part Numbers: 381164 Autoclear III

Clearcoat Brand (2): U-Tech

Clearcoat Brand (2) Part Numbers: 399099 4.0 Clear

Please help. I appreciate it very much.

答: CRM has a data import wizard under tools.  You can use that to import data from a csv file.  </p>

ContentLicense: CC BY-SA 2.5

Title: Best way to input Products into CRM

Body:
I would like to know what the best way to input products into CRM? I don’t much like how it is laid out in CRM now. I would like it to look more like a tree. Such as listed below.

Manufacturer: Akzo

Brand: Sikkens

Primer Brand: U-Tech

Primer Part Numbers: 399199 2K100 Grey

                             399200 2K Buff

Sealer Brand: 398745 ColorBuild Plus

Basecoat Color System: AutoBase Plus

Basecoat Reducer: 394695 Lesonal Reducer

Clearcoat Brand (1): Sikkens

Clearcoat Brand (1) Part Numbers: 381164 Autoclear III

Clearcoat Brand (2): U-Tech

Clearcoat Brand (2) Part Numbers: 399099 4.0 Clear

Please help. I appreciate it very much.


问:
how can I increase the int through a method?
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

```<code>int health;
int mana;
</code>```

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

```<code>public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}
</code>```

Please give me some insight!

答:
Try to think Object oriented!

```<code>public class ManaAndHealth {
    int health;
    int mana;
    public int getHealth() {
        return health;
    }

    public void setHealth(int theHealth) {
        health=theHealth;
    }
    public void setMana(int theMana) {
        mana=theMana;
    }
    public int getMana() {
        return mana;
    }
}
</code>```

Then you can use it like this:

```<code>public void upgrade(ManaAndHealth mah){
   mah.setMana(mah.getMana()+10);
   mah.setHealth(mah.getHealth()+10);
}
</code>```

This is just to show the concept, then other things like maxMana and maxHealth could additionally limit the upgrade ...

Body:
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

int health;
int mana;

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}

Please give me some insight!

Body:
Try to think Object oriented!

public class ManaAndHealth {
    int health;
    int mana;
    public int getHealth() {
        return health;
    }

    public void setHealth(int theHealth) {
        health=theHealth;
    }
    public void setMana(int theMana) {
        mana=theMana;
    }
    public int getMana() {
        return mana;
    }
}

Then you can use it like this:

public void upgrade(ManaAndHealth mah){
   mah.setMana(mah.getMana()+10);
   mah.setHealth(mah.getHealth()+10);
}

This is just to show the concept, then other things like maxMana and maxHealth could additionally limit the upgrade ...


问:
My scrip works fine in java class but same script fails when I use testng. It just opens the browser and fails my script
Please Find the below code: I have performed the following steps, but didn't worked.
Please Help:

```<code>public class ForSe_TestCases
public WebDriver driver;

@BeforeTest
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver =new ChromeDriver();
driver.manage().deleteAllCookies();
}

@Test(priority = 0)
public void Validlogin_IO () throws InterruptedException {
driver.navigate().to("http://**URL**");
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345");
driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
System.out.println("Login button pressed");
}
</code>```

What can be the issue with TestNG ?

答:
Sanchit, I think it fails because you are not waiting for the element to appear on the page and the webDriver (which is faster than its shadow!) thinks the first element you are trying to locate isn't there (id='email_address).

Try reading here for implicit or explicit way to wait or use this code of mine below instead (if the element is present then the method returns true):

```<code>public boolean waitForElement(String elementXpath, int timeOut) {

    try{
    WebDriverWait wait = new WebDriverWait(driver, timeOut);
    boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());

    System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
    }
    catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}

    return elementPresent;
 }
</code>```

Update after OP's comments

To see if my method works, try replacing your first find element line:

```<code>driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com"); //this is official email
</code>```

with this code below instead (then your script won't break from then ownwards, if it does use this waiting method again for the 'breaking' element). I think your script is breaking straight away because you locate the element and sendKeys very fast without waiting for it to appear first!

```<code>waitForElement ("//*[@id='email_address']", 10);
if(elementPresent==true){
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
}
else{
System.out.println("FATAL! Couldn't locate email address field!");
}
</code>```

Hope you can crack it this time round!

Body:
Please Find the below code: I have performed the following steps, but didn't worked.
Please Help:

public class ForSe_TestCases
public WebDriver driver;

@BeforeTest
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver =new ChromeDriver();
driver.manage().deleteAllCookies();
}

@Test(priority = 0)
public void Validlogin_IO () throws InterruptedException {
driver.navigate().to("http://**URL**");
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345");
driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
System.out.println("Login button pressed");
}

What can be the issue with TestNG ?

Body:
Sanchit, I think it fails because you are not waiting for the element to appear on the page and the webDriver (which is faster than its shadow!) thinks the first element you are trying to locate isn't there (id='email_address).

Try reading here for implicit or explicit way to wait or use this code of mine below instead (if the element is present then the method returns true):

public boolean waitForElement(String elementXpath, int timeOut) {

    try{
    WebDriverWait wait = new WebDriverWait(driver, timeOut);
    boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());

    System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
    }
    catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}

    return elementPresent;
 }

Update after OP's comments

To see if my method works, try replacing your first find element line:

driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com"); //this is official email

with this code below instead (then your script won't break from then ownwards, if it does use this waiting method again for the 'breaking' element). I think your script is breaking straight away because you locate the element and sendKeys very fast without waiting for it to appear first!

waitForElement ("//*[@id='email_address']", 10);
if(elementPresent==true){
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
}
else{
System.out.println("FATAL! Couldn't locate email address field!");
}

Hope you can crack it this time round!


问:
evancz/url-parser and multiple query parameters
I'm not sure how to get access to multiple query parameters.

There is no example in the source code for that.

I know how to get one query parameter using <?>:

routeParser : Url.Parser (Route -> a) a
routeParser =
    Url.oneOf
        [ Url.map HomeRoute Url.top
        , Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy")
        ]

parseLocation : Location -> Route
parseLocation location =
    location
        |> Url.parsePath routeParser
        |> Maybe.withDefault NotFoundRoute
```

<p>With <code>parsePath</code> I can get <code>Dict</code> with query params, but Is there an elegant way using <code><?></code>?</p>

<p>Edit:</p>

<p>I've used this example in <code>elm-repl</code>:</p>

<pre class="lang-elm prettyprint-override"><code>> parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The 1st argument to function `parsePath` is causing a mismatch.

5|   parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `parsePath` is expecting the 1st argument to be:

    Parser (Maybe String -> Maybe String) (Maybe String)

But it is:

    Parser (Maybe String -> Maybe String -> Maybe String) (Maybe String)

Hint: It looks like a function needs 1 more argument.
</code>```

答:
You can chain <?> together for multiple query parameters. Let's say your SettingsRoute also expected a pageNumber integer argument:

type Route
    = ...
    | SettingsRoute (Maybe String) (Maybe Int)
```

<p>Your parser could then look like this:</p>

<pre class="lang-elm prettyprint-override"><code>Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy" <?> Url.intParam "pageNumber")
</code>```

The query parameters from the incoming URL don't need to be in the same order as your map statement. The following example will give the same results for the above route:

settings?sortBy=name&pageNumber=3
settings?pageNumber=3&sortBy=name
```

<p><strong>Edit</strong></p>

<p>You added an example from the REPL. The problem you are experiencing in the REPL is because you aren't mapping correctly to something that takes two parameters. Consider this example for the REPL:</p>

<pre class="lang-elm prettyprint-override"><code>> type alias SearchParams = { search : Maybe String, sortBy : Maybe String }
> parsePath (map SearchParams (s "blog" <?> stringParam "search" <?> stringParam "sortBy")) (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
Just { search = Just "cats", sortBy = Just "name" }
    : Maybe.Maybe Repl.SearchParams
</code>```

Body:
I'm not sure how to get access to multiple query parameters.

There is no example in the source code for that.

I know how to get one query parameter using <?>:

routeParser : Url.Parser (Route -> a) a
routeParser =
    Url.oneOf
        [ Url.map HomeRoute Url.top
        , Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy")
        ]

parseLocation : Location -> Route
parseLocation location =
    location
        |> Url.parsePath routeParser
        |> Maybe.withDefault NotFoundRoute

With parsePath I can get Dict with query params, but Is there an elegant way using <?>?

Edit:

I've used this example in elm-repl:

> parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The 1st argument to function `parsePath` is causing a mismatch.

5|   parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `parsePath` is expecting the 1st argument to be:

    Parser (Maybe String -> Maybe String) (Maybe String)

But it is:

    Parser (Maybe String -> Maybe String -> Maybe String) (Maybe String)

Hint: It looks like a function needs 1 more argument.

Body:
You can chain <?> together for multiple query parameters. Let's say your SettingsRoute also expected a pageNumber integer argument:

type Route
    = ...
    | SettingsRoute (Maybe String) (Maybe Int)

Your parser could then look like this:

Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy" <?> Url.intParam "pageNumber")

The query parameters from the incoming URL don't need to be in the same order as your map statement. The following example will give the same results for the above route:

settings?sortBy=name&pageNumber=3
settings?pageNumber=3&sortBy=name

Edit

You added an example from the REPL. The problem you are experiencing in the REPL is because you aren't mapping correctly to something that takes two parameters. Consider this example for the REPL:

> type alias SearchParams = { search : Maybe String, sortBy : Maybe String }
> parsePath (map SearchParams (s "blog" <?> stringParam "search" <?> stringParam "sortBy")) (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
Just { search = Just "cats", sortBy = Just "name" }
    : Maybe.Maybe Repl.SearchParams


问:
UE4 Enabling Mouse During Play?
I'm extremely new to UE, and doing a few easy tutorials to get started, so I don't exactly know the correct terminology to use to help me find what I am looking for... Anyway, whenever I hit play and the game starts, my mouse disappears and I am only able to use the input that I set up; so my question is, even though I do not need mouse input for movement, as I am using WASD, how do I keep my mouse unlocked and available to move around without being locked to the camera?</p>

答:
There are 3 blueprint nodes that change the input method:

Set Input Mode Game

Set Input Mode Game and UI

Set Input Mode UI

You want a combination of the second one and a "Show Mouse Cursor" node. However, if you are making an FPS and you use the mouse to look around, you may lose that ability with the second node above. It comes down to what your game is and how you want to use the mouse.

Title: UE4 Enabling Mouse During Play?


问:
How to work using multiple Rnw files?
I have one Rnw file called name "main.Rnw" and it includes this

```<code>\documentclass{article}
\usepackage{float}
\title{Something}
\author{John Smith}
\setkeys{Gin}{width=1.15\textwidth}
\begin{document}
\SweaveOpts{concordance=TRUE}
\thispagestyle{empty}
\maketitle
\newpage
\thispagestyle{empty}
\tableofcontents
\newpage
\SweaveInput{reports/Child.Rnw}
\end{document}
</code>```

In the file "Child.Rnw" I have:

```<code>% !Rnw root = Main.Rnw
 \documentclass{article}
 \usepackage{float}
\begin{document}
\SweaveOpts{concordance=TRUE}
\section{section}
 Something something
\end{document}
</code>```

Now it gives error:

```<code>  Error in SweaveReadFile(c(ifile, file), syntax, encoding = encoding) :
  no Sweave file with name ‘./reports/Child.Rnw’ found
  Calls: <Anonymous> -> SweaveReadFile -> SweaveReadFile
  Execution halted
</code>```

If I change the code and take away reports from command \SweaveInput{reports/Child.Rnw} (so. code is \SweaveInput{Child.Rnw} ) it gives error:

```<code>Writing to file Main.tex
Processing code chunks with options ...
 Error in seq.default(from = which + 1L, length.out = length(linesout) -  :
 'from' must be of length 1
Calls: <Anonymous> -> <Anonymous> -> seq -> seq.default
In addition: Warning messages:
1: In 1L:which : numerical expression has 2 elements: only the first used
2: In seq.default(from = which + 1L, length.out = length(linesout) -  :
first element used of 'length.out' argument
Execution halted
</code>```

What I do wrong?
I use R Studio.

答:
I have no experience with Sweave but the following should will with knitr.

You do not have to specify new document specification for Child.Rnw if they are supposed to be same, as default behaviour is to inherit attributes of the parent.

Sweave to knitr

```<code>#Convert Sweave specific options to knitr compatible version
#this will generate a new file named Parent-knitr.Rnw
library("knitr")
Sweave2knitr("Parent.Rnw")
</code>```

File Paths:

For testing, let us assume following hypothetical directory structure

D:/project/Parent.Rnw

D:/project/reports/Child.Rnw

If Child.Rnw file is present in the same location as Parent.Rnw location
    the following should work

\Sexpr{knit_child('Child.RnW')}

If present at different location you need to specify full path of Child.Rnw and both
    absolute and relative paths should work

absolute path e.g "D:/project/reports/Child.Rnw"

relative path e.g "../reports/Child.Rnw"

. implies current directory and  .. implies moving one level up from working directory and working directory
    is set to directory of Parent.Rnw as default by knitr.
    See ?knit_child for more documentation

Parent.Rnw:

```<code>\documentclass{article}
\usepackage{float}
\title{Testing Parent Child Processing with knitr}
\author{John Smith}
\setkeys{Gin}{width=1.15\textwidth}
\begin{document}

<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
@

\thispagestyle{empty}
\maketitle
%\newpage
\thispagestyle{empty}
%\tableofcontents
%\newpage
%\SweaveInput{reports/Child.Rnw}

\Sexpr{knit_child('./reports/Child.RnW')}
\end{document}
</code>```

Child.Rnw:

```<code>\textbf{Testing Child.Rnw Processing:}

<<testChild>>=

data(mtcars)
plot(hclust(dist(mtcars)))

@
</code>```

PDF Conversion:

```<code>knit2pdf("Parent-knitr.Rnw")
</code>```

Output:

Title: How to work using multiple Rnw files?

Body:
I have one Rnw file called name "main.Rnw" and it includes this

\documentclass{article}
\usepackage{float}
\title{Something}
\author{John Smith}
\setkeys{Gin}{width=1.15\textwidth}
\begin{document}
\SweaveOpts{concordance=TRUE}
\thispagestyle{empty}
\maketitle
\newpage
\thispagestyle{empty}
\tableofcontents
\newpage
\SweaveInput{reports/Child.Rnw}
\end{document}

In the file "Child.Rnw" I have:

% !Rnw root = Main.Rnw
 \documentclass{article}
 \usepackage{float}
\begin{document}
\SweaveOpts{concordance=TRUE}
\section{section}
 Something something
\end{document}

Now it gives error:

  Error in SweaveReadFile(c(ifile, file), syntax, encoding = encoding) :
  no Sweave file with name ‘./reports/Child.Rnw’ found
  Calls: <Anonymous> -> SweaveReadFile -> SweaveReadFile
  Execution halted

If I change the code and take away reports from command \SweaveInput{reports/Child.Rnw} (so. code is \SweaveInput{Child.Rnw} ) it gives error:

Writing to file Main.tex
Processing code chunks with options ...
 Error in seq.default(from = which + 1L, length.out = length(linesout) -  :
 'from' must be of length 1
Calls: <Anonymous> -> <Anonymous> -> seq -> seq.default
In addition: Warning messages:
1: In 1L:which : numerical expression has 2 elements: only the first used
2: In seq.default(from = which + 1L, length.out = length(linesout) -  :
first element used of 'length.out' argument
Execution halted

What I do wrong?
I use R Studio.

Body:
I have no experience with Sweave but the following should will with knitr.

You do not have to specify new document specification for Child.Rnw if they are supposed to be same, as default behaviour is to inherit attributes of the parent.

Sweave to knitr

#Convert Sweave specific options to knitr compatible version
#this will generate a new file named Parent-knitr.Rnw
library("knitr")
Sweave2knitr("Parent.Rnw")

File Paths:

For testing, let us assume following hypothetical directory structure

D:/project/Parent.Rnw

D:/project/reports/Child.Rnw

If Child.Rnw file is present in the same location as Parent.Rnw location
    the following should work

\Sexpr{knit_child('Child.RnW')}

If present at different location you need to specify full path of Child.Rnw and both
    absolute and relative paths should work

absolute path e.g "D:/project/reports/Child.Rnw"

relative path e.g "../reports/Child.Rnw"

. implies current directory and  .. implies moving one level up from working directory and working directory
    is set to directory of Parent.Rnw as default by knitr.
    See ?knit_child for more documentation

Parent.Rnw:

\documentclass{article}
\usepackage{float}
\title{Testing Parent Child Processing with knitr}
\author{John Smith}
\setkeys{Gin}{width=1.15\textwidth}
\begin{document}

<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
@

\thispagestyle{empty}
\maketitle
%\newpage
\thispagestyle{empty}
%\tableofcontents
%\newpage
%\SweaveInput{reports/Child.Rnw}

\Sexpr{knit_child('./reports/Child.RnW')}
\end{document}

Child.Rnw:

\textbf{Testing Child.Rnw Processing:}

<<testChild>>=

data(mtcars)
plot(hclust(dist(mtcars)))

@

PDF Conversion:

knit2pdf("Parent-knitr.Rnw")

Output:


问:
How to avoid charset=utf-8 from Content-Type?
It is a common case to return JSON data in response, aiohttp.web provides a shortcut for returning JSON – aiohttp.web.json_response():

```<code>def handler(request):
    data = {'some': 'data'}
    return web.json_response(data)
</code>```

The shortcut method returns aiohttp.web.Response instance so we can for example set cookies before returning it from handler.

But my curl request returns me Content-Type: application/json; charset=utf-8, but I need just application/json, how to avoid charset=utf-8?

答:
Why do you want to avoid charset=utf-8 in your content type? If you don't specify it, the fallback (default value) will be ISO-8859-1 as of W3C.

And actual answer to your question: current aiohttp version doesn't support changing a charset with json_response shortcut function. Even using aiohttp.web.Response directly without specifying a charset would add charset=utf8 to your response's Content-Type. You can change charset but no omit it (unless text argument of aiohttp.web.Response.__init__ is set None).

To change charset using json_response you can do something like this:

```<code>web.json_response(
    data,
    content_type=None,
    headers={aiohttp.hdrs.CONTENT_TYPE: 'application/json; charset=ISO-8859-1'},
)
</code>```

or use functools.partial to don't repeat this longish function call every time:

```<code>my_json_resp = partial(
    web.json_response,
    content_type=None,
    headers={aiohttp.hdrs.CONTENT_TYPE: 'application/json; charset=ISO-8859-1'},
)

# later in your app
return my_json_resp(data)
</code>```

You can have a look at the sources of json_response here and Response.__init__ here to check it yourself.

Body:
It is a common case to return JSON data in response, aiohttp.web provides a shortcut for returning JSON – aiohttp.web.json_response():

def handler(request):
    data = {'some': 'data'}
    return web.json_response(data)

The shortcut method returns aiohttp.web.Response instance so we can for example set cookies before returning it from handler.

But my curl request returns me Content-Type: application/json; charset=utf-8, but I need just application/json, how to avoid charset=utf-8?

Body:
Why do you want to avoid charset=utf-8 in your content type? If you don't specify it, the fallback (default value) will be ISO-8859-1 as of W3C.

And actual answer to your question: current aiohttp version doesn't support changing a charset with json_response shortcut function. Even using aiohttp.web.Response directly without specifying a charset would add charset=utf8 to your response's Content-Type. You can change charset but no omit it (unless text argument of aiohttp.web.Response.__init__ is set None).

To change charset using json_response you can do something like this:

web.json_response(
    data,
    content_type=None,
    headers={aiohttp.hdrs.CONTENT_TYPE: 'application/json; charset=ISO-8859-1'},
)

or use functools.partial to don't repeat this longish function call every time:

my_json_resp = partial(
    web.json_response,
    content_type=None,
    headers={aiohttp.hdrs.CONTENT_TYPE: 'application/json; charset=ISO-8859-1'},
)

# later in your app
return my_json_resp(data)

You can have a look at the sources of json_response here and Response.__init__ here to check it yourself.


问:
What's the replacement for Xcode's PackageApplication?
With Xcode 8.3 PackageApplication is gone. I did use it to convert an *.app package/directory to a *.ipa file (after re-signing):

```<code>xcrun -sdk iphoneos PackageApplication -v "MyApp.app" -o "MyApp.ipa"
</code>```

Is there any replacement for this, so I can continue to convert .app to .ipa?

答:
Apparently there is no need to use any other tool, and it's also not necessary to change the process that leads to the *.app package (in other words: no need to use xcodebuild -exportArchive).

All we have to do, is to zip that *.app package:

```<code>pushd "/build"
mkdir ./Payload
cp -R "$PATH_TO_SIGNED_APP_PACKAGE.app" ./Payload
zip -qyr MyApp.ipa ./Payload
rm -r ./Payload
popd
</code>```

Note:

Jump into the target directory, here /build. This ensures we don't have the full path in the zip archive later.

Create a folder named Payload (important, this cannot vary)

Copy the *.app bundle to the Payload folder

Zip the folder and instead of *.zip use *.ipa as extension

Jump back to where you came from

Body:
With Xcode 8.3 PackageApplication is gone. I did use it to convert an *.app package/directory to a *.ipa file (after re-signing):

xcrun -sdk iphoneos PackageApplication -v "MyApp.app" -o "MyApp.ipa"

Is there any replacement for this, so I can continue to convert .app to .ipa?

Body:
Apparently there is no need to use any other tool, and it's also not necessary to change the process that leads to the *.app package (in other words: no need to use xcodebuild -exportArchive).

All we have to do, is to zip that *.app package:

pushd "/build"
mkdir ./Payload
cp -R "$PATH_TO_SIGNED_APP_PACKAGE.app" ./Payload
zip -qyr MyApp.ipa ./Payload
rm -r ./Payload
popd

Note:

Jump into the target directory, here /build. This ensures we don't have the full path in the zip archive later.

Create a folder named Payload (important, this cannot vary)

Copy the *.app bundle to the Payload folder

Zip the folder and instead of *.zip use *.ipa as extension

Jump back to where you came from


问:
How put margin between diffrent div on a container?
I have different lines each one contains logo and some text.I want to put each logo in a different line and put a margin-top of 20px between them.

index.html:

```<code><container class="list_project">
      <div class="project">
          <img class ="first_logo" src="./logos/logo.png" value="" />
          <img class ="project_logo" src="./logos/logo.png" value="" />
      </div>
    </container>
</code>```

style.css:

```<code>  .first_logo
  {
   position: absolute;
   top: 150px;
   width: 85px;
   height: 45px;
  }
  .project_logo
  {
    position: absolute;
    margin-bottom: 20px;
    width: 85px;
    height: 45px;

   }
</code>```

But I find that the position of the image is relative to main page not to the container. How can I fix that and I make the position of each image relative to the container?

Logo

答:
Simply make the project div as relative.

```<code>.project{
  position:relative;
}
</code>```

Absolutely positioned div's look for the first relative parent and if none defined, become relative to the body.

Sample Fiddle here : https://jsfiddle.net/dabros/vo1npqdx/

Body:
I have different lines each one contains logo and some text.I want to put each logo in a different line and put a margin-top of 20px between them.

index.html:

<container class="list_project">

    </container>

style.css:

  .first_logo
  {
   position: absolute;
   top: 150px;
   width: 85px;
   height: 45px;
  }
  .project_logo
  {
    position: absolute;
    margin-bottom: 20px;
    width: 85px;
    height: 45px;

   }

But I find that the position of the image is relative to main page not to the container. How can I fix that and I make the position of each image relative to the container?

Logo

Body:
Simply make the project div as relative.

.project{
  position:relative;
}

Absolutely positioned div's look for the first relative parent and if none defined, become relative to the body.

Sample Fiddle here : https://jsfiddle.net/dabros/vo1npqdx/


问:
Distinct is not working?
```<code>  $data = Districts::distinct()->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();
</code>```

I have this query, but problem is that distinct not working. I get for example three records for same thing. Any suggestion?

答:
try to this may i think its could be work with region

```<code>  $data = Districts::select([ DB::raw('DISTINCT(district)'),'region'])->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->get();
</code>```

Title: Distinct is not working?

Body:
  $data = Districts::distinct()->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();

I have this query, but problem is that distinct not working. I get for example three records for same thing. Any suggestion?

Body:
try to this may i think its could be work with region

  $data = Districts::select([ DB::raw('DISTINCT(district)'),'region'])->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->get();


问:
16 millisecond quantization when sending/receivingtcp packets
I have a C++ application running on windows xp 32 system sending and receiving short tcp/ip packets.

Measuring (accurately) the arrival time I see a quantization of the arrival time  to 16 millisecond time units. (Meaning all packets arriving are at (16 )xN milliseconds separated from each other)

To avoid packet aggregation I tried to disable the NAGLE algorithm by setting the IPPROTO_TCP option to TCP_NODELAY in the socket variables but it did not help

I suspect that the problem is related to the windows schedular which also have a 16 millisecond clock..
Any idea of a solution to this problem ?
Thanks

答:
Use a higher resolution timer such as QueryPerformanceTimer() or __rdtsc() being aware of their downfalls.

Similarly note if you are using wait functions you may want to call timeBeginPeriod() for 1ms resolution or even implement a busy-way delay function wrapped around a higher resolution timer.


问:
How to find most recently modified file from all subdirectories in a directory in Python?
I have a directory in which I have many folders, AS WELL as files. I want to write a script that finds the path and name of the most recent file that exists in the directory, either in one of its sub-directories, or in the directory itself. This will be run from VSCode whenever I want to run a program. Earlier I had something like this. It worked ONLY for files in the directory, and not files in sub-directories.

```<code>files = sorted(os.listdir(path), key=os.path.getctime, reverse = True)
for file in files: #Finds most recent file with '.cpp' extension
    if ".cpp" in file:
        last = file
        break
subprocess.call(
    ["g++", "-std=c++14", path + last]
    )
subprocess.call(
    ["open", path + "./a.out"]
)
</code>```

Here's the output of "ls -ltr" in Terminal. The last three lines are for folders.

```<code>-rw-r--r--@  1 tanavya.dimri  staff     2182 Mar 23 16:10 UVa_LEDTest.cpp
-rw-r--r--@  1 tanavya.dimri  staff     4217 Mar 23 16:11 OPC_SiruseriMetro.cpp
-rw-r--r--@  1 tanavya.dimri  staff     2645 Mar 23 16:12 UVa_Password.cpp
-rw-r--r--@  1 tanavya.dimri  staff      940 Mar 23 16:13 UVa_8Queens.cpp
-rw-r--r--@  1 tanavya.dimri  staff     1587 Mar 23 20:57 UVa12405_Scarecrow.cpp
-rw-r--r--@  1 tanavya.dimri  staff     3014 Mar 25 19:58 UVa_Zones.cpp
-rw-r--r--@  1 tanavya.dimri  staff     2733 Mar 25 20:07 YogesMM.cpp
-rw-r--r--@  1 tanavya.dimri  staff     1066 Mar 26 22:33 ChefAndTraingles.cpp
-rw-r--r--@  1 tanavya.dimri  staff      993 Mar 27 07:10 untitled.cpp
-rw-r--r--   1 tanavya.dimri  staff       33 Mar 27 21:42 out.out
-rwxr-xr-x   1 tanavya.dimri  staff    15564 Mar 27 22:54 a.out
drwxr-xr-x   8 tanavya.dimri  staff      272 Mar 27 23:35 SpecificAlgorithms
drwxr-xr-x  25 tanavya.dimri  staff      850 Mar 30 12:49 DynamicProgramming
drwxr-xr-x   5 tanavya.dimri  staff      170 Mar 30 16:27 GraphTheory
</code>```

Maybe in the future, I might have sub-directories INSIDE my sub-directories, so if any suggested script can work in that scenario as well, it would be even more appreciated.

EDIT

I liked both the answers, by Peter and Jean, so thanks!
My file now:

```<code>import os
import subprocess

path = "/Users/tanavya.dimri/Desktop/CompetitiveProgramming/"

most_recent_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")),key=os.path.getctime)
subprocess.call(
                ["g++", "-std=c++14", most_recent_file]
                )
run_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower() == "a.out"),key=os.path.getctime)
subprocess.call(
                ["open", run_file]
                )
</code>```

It's short and simple, though I also liked the readability of Peter's code.

答:
Use os.walk, (ignoring directories), instead of os.listdir in a nested list comprehension fed to sort

```<code>files = sorted([os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")], key=os.path.getctime, reverse = True)
</code>```

As someone noted, if you only need 1 file, you can just apply max with a key (and in that case, switch to generator comprehension, since you don't need the full list to feed to sort and optimize speed):

```<code>most_recent_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")),key=os.path.getctime)
</code>```

note that your expression files = sorted(os.listdir(path), key=os.path.getctime, reverse = True) needs you to change current directory unless path is not the current path, because listdir returns the file names not the file paths (and yes, you also have to filter out directories, which complexifies the expression further. You don't have this problem anymore with the solution above since os.path.join is applied before sorting)

Body:
I have a directory in which I have many folders, AS WELL as files. I want to write a script that finds the path and name of the most recent file that exists in the directory, either in one of its sub-directories, or in the directory itself. This will be run from VSCode whenever I want to run a program. Earlier I had something like this. It worked ONLY for files in the directory, and not files in sub-directories.

files = sorted(os.listdir(path), key=os.path.getctime, reverse = True)
for file in files: #Finds most recent file with '.cpp' extension
    if ".cpp" in file:
        last = file
        break
subprocess.call(
    ["g++", "-std=c++14", path + last]
    )
subprocess.call(
    ["open", path + "./a.out"]
)

Here's the output of "ls -ltr" in Terminal. The last three lines are for folders.

-rw-r--r--@  1 tanavya.dimri  staff     2182 Mar 23 16:10 UVa_LEDTest.cpp
-rw-r--r--@  1 tanavya.dimri  staff     4217 Mar 23 16:11 OPC_SiruseriMetro.cpp
-rw-r--r--@  1 tanavya.dimri  staff     2645 Mar 23 16:12 UVa_Password.cpp
-rw-r--r--@  1 tanavya.dimri  staff      940 Mar 23 16:13 UVa_8Queens.cpp
-rw-r--r--@  1 tanavya.dimri  staff     1587 Mar 23 20:57 UVa12405_Scarecrow.cpp
-rw-r--r--@  1 tanavya.dimri  staff     3014 Mar 25 19:58 UVa_Zones.cpp
-rw-r--r--@  1 tanavya.dimri  staff     2733 Mar 25 20:07 YogesMM.cpp
-rw-r--r--@  1 tanavya.dimri  staff     1066 Mar 26 22:33 ChefAndTraingles.cpp
-rw-r--r--@  1 tanavya.dimri  staff      993 Mar 27 07:10 untitled.cpp
-rw-r--r--   1 tanavya.dimri  staff       33 Mar 27 21:42 out.out
-rwxr-xr-x   1 tanavya.dimri  staff    15564 Mar 27 22:54 a.out
drwxr-xr-x   8 tanavya.dimri  staff      272 Mar 27 23:35 SpecificAlgorithms
drwxr-xr-x  25 tanavya.dimri  staff      850 Mar 30 12:49 DynamicProgramming
drwxr-xr-x   5 tanavya.dimri  staff      170 Mar 30 16:27 GraphTheory

Maybe in the future, I might have sub-directories INSIDE my sub-directories, so if any suggested script can work in that scenario as well, it would be even more appreciated.

EDIT

I liked both the answers, by Peter and Jean, so thanks!
My file now:

import os
import subprocess

path = "/Users/tanavya.dimri/Desktop/CompetitiveProgramming/"

most_recent_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")),key=os.path.getctime)
subprocess.call(
                ["g++", "-std=c++14", most_recent_file]
                )
run_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower() == "a.out"),key=os.path.getctime)
subprocess.call(
                ["open", run_file]
                )

It's short and simple, though I also liked the readability of Peter's code.

Body:
Use os.walk, (ignoring directories), instead of os.listdir in a nested list comprehension fed to sort

files = sorted([os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")], key=os.path.getctime, reverse = True)

As someone noted, if you only need 1 file, you can just apply max with a key (and in that case, switch to generator comprehension, since you don't need the full list to feed to sort and optimize speed):

most_recent_file = max((os.path.join(root,f) for root,_,the_files in os.walk(path) for f in the_files if f.lower().endswith(".cpp")),key=os.path.getctime)

note that your expression files = sorted(os.listdir(path), key=os.path.getctime, reverse = True) needs you to change current directory unless path is not the current path, because listdir returns the file names not the file paths (and yes, you also have to filter out directories, which complexifies the expression further. You don't have this problem anymore with the solution above since os.path.join is applied before sorting)


问:
Multiple-angled css shape, is it possible?
Hi guys consider the picture below

is it possible to create such a shape with css? If so can you give me some clues or an example?

答:
Try this code

.cshape {
  height: 300px;
  width: 250px
  background: #92a8eb;
  background: -moz-linear-gradient(left, #92a8eb 0%, #96c0ea 50%, #9ce4e8 100%);
  background: -webkit-linear-gradient(left, #92a8eb 0%, #96c0ea 50%, #9ce4e8 100%);
  background: linear-gradient(to right, #92a8eb 0%, #96c0ea 50%, #9ce4e8 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92a8eb', endColorstr='#9ce4e8', GradientType=1);
  -webkit-clip-path: polygon(0 0, 100% 0, 37% 28%, 0 25%);
  clip-path: polygon(0 0, 100% 0, 37% 28%, 0 25%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='cshape'>

</div></code>```

Body:
Try this code

.cshape {
  height: 300px;
  width: 250px
  background: #92a8eb;
  background: -moz-linear-gradient(left, #92a8eb 0%, #96c0ea 50%, #9ce4e8 100%);
  background: -webkit-linear-gradient(left, #92a8eb 0%, #96c0ea 50%, #9ce4e8 100%);
  background: linear-gradient(to right, #92a8eb 0%, #96c0ea 50%, #9ce4e8 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92a8eb', endColorstr='#9ce4e8', GradientType=1);
  -webkit-clip-path: polygon(0 0, 100% 0, 37% 28%, 0 25%);
  clip-path: polygon(0 0, 100% 0, 37% 28%, 0 25%);
}

<div class='cshape'>

</div>


问:
Deleting Django Rest Api Database
How do I delete the database I am using in DRF in command line, I want to reset the database to its initial state before I run my first migration. Is there a one line command in the terminal to delete it?</p>

答:
I should have probably phrased my question better. Just putting the answer here in case it is useful to anyone in the future. My database had some migrations that caused conflicts with the previous migrations for which I had to put default values but since the default values were specific to the front end of the user I needed to remove the existing database and start over. I did it by using the following commands in the terminal.

```<code>rm -f tmp.db db.sqlite3
rm -r myapp/migrations
python manage.py makemigrations myapp
python manage.py migrate
</code>```

I would recommend going through the docs here it is pretty clearly outlined.
http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-information-to-our-model

Title: Deleting Django Rest Api Database

Body:
I should have probably phrased my question better. Just putting the answer here in case it is useful to anyone in the future. My database had some migrations that caused conflicts with the previous migrations for which I had to put default values but since the default values were specific to the front end of the user I needed to remove the existing database and start over. I did it by using the following commands in the terminal.

rm -f tmp.db db.sqlite3
rm -r myapp/migrations
python manage.py makemigrations myapp
python manage.py migrate

I would recommend going through the docs here it is pretty clearly outlined.
http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-information-to-our-model


问:
How to convert all files in a specific directory using batch script
I have videos in a folder of .h264 format and i want to convert them to mp4. now by default i can use ffmpeg to do this:
Here is the command:

```<code>ffmpeg -i youtube.flv -c:v libx264 filename.mp4
</code>```

But, new h264 files are being added and I want to keep converting the videos so as to use it for my python script.

I know i can use this to initialize the variable

```<code>SET /A num=1
</code>```

But how do i write a batch script to take all the videos from the directory one by one even though there new videos being added?

I wrote this but this isn't working:

```<code>@echo off
SET /A num=1

for file in E:\Records\1\*.h264
do
    ffmpeg -i "$file" -c:v libx264 E:\Recods\1\converted\%num%.mp4
    move E:\Records\1\"$file" E:\Records\1\done\
    set /A num=%num%+1
done
PAUSE
</code>```

I am making a done folder and moving the videos that have been converted there and in converted folder i am putting converted videos.. Now i just have to run a task scheduler each hour so that if there is a new entry it should convert it and move it to appropriate folder.

答:
You can loop over all files (even with applying a filter) in a folder using the for loop in batch like this:

```<code>@echo off
setlocal EnableDelayedExpansion
set /a vid=0
cd /d "your_Folder\Goes here"
for %%f in (*.h264) do (
  ffmpeg -i "%%~f" -c:v libx264 "!vid!.mp4"
  set /a vid=!vid!+1
)
</code>```

So what happens here?

The first line is used to have the program running in the correct directory.

After that all files ending with .h264 (might be a different ending in your case; just took it from the question) in that directory are processed using your command. For that the filepath is placed in the spot for the input file and the counter together with .mp4 is placed as the outputfile.

The counter is a  bit more tricky because of how sets of parenthesis are evaluated in batch, which is as one whole block. As solution for this there are a lot of questions and answers on SO. Look for "Delayed Expansion batch" and you will find something like this answer.

Placing this as a Task-Scheduler-Task running on a regular basis should keep your folder updated. For actually monitoring the folder I found this impressive code that can be used in combination with the Task-Scheduler to run that on startup. If the monitoring triggers, you can execute the batch-file above and it should be run each time a file is added. You can adjust the powershell-file with file-filters as well to make it fit your needs.

Body:
I have videos in a folder of .h264 format and i want to convert them to mp4. now by default i can use ffmpeg to do this:
Here is the command:

ffmpeg -i youtube.flv -c:v libx264 filename.mp4

But, new h264 files are being added and I want to keep converting the videos so as to use it for my python script.

I know i can use this to initialize the variable

SET /A num=1

But how do i write a batch script to take all the videos from the directory one by one even though there new videos being added?

I wrote this but this isn't working:

@echo off
SET /A num=1

for file in E:\Records\1\*.h264
do
    ffmpeg -i "$file" -c:v libx264 E:\Recods\1\converted\%num%.mp4
    move E:\Records\1\"$file" E:\Records\1\done\
    set /A num=%num%+1
done
PAUSE

I am making a done folder and moving the videos that have been converted there and in converted folder i am putting converted videos.. Now i just have to run a task scheduler each hour so that if there is a new entry it should convert it and move it to appropriate folder.

Body:
You can loop over all files (even with applying a filter) in a folder using the for loop in batch like this:

@echo off
setlocal EnableDelayedExpansion
set /a vid=0
cd /d "your_Folder\Goes here"
for %%f in (*.h264) do (
  ffmpeg -i "%%~f" -c:v libx264 "!vid!.mp4"
  set /a vid=!vid!+1
)

So what happens here?

The first line is used to have the program running in the correct directory.

After that all files ending with .h264 (might be a different ending in your case; just took it from the question) in that directory are processed using your command. For that the filepath is placed in the spot for the input file and the counter together with .mp4 is placed as the outputfile.

The counter is a  bit more tricky because of how sets of parenthesis are evaluated in batch, which is as one whole block. As solution for this there are a lot of questions and answers on SO. Look for "Delayed Expansion batch" and you will find something like this answer.

Placing this as a Task-Scheduler-Task running on a regular basis should keep your folder updated. For actually monitoring the folder I found this impressive code that can be used in combination with the Task-Scheduler to run that on startup. If the monitoring triggers, you can execute the batch-file above and it should be run each time a file is added. You can adjust the powershell-file with file-filters as well to make it fit your needs.


问:
 does not display local images in WordPress header.php and index.php
I am trying to use a simple <img src= tag to link to a favicon.ico in my header.php file and a .png logo in my index.php file in my WordPress theme, but without any luck. I've tested the link by replacing it with a hyperlink to an image hosted online, which works and proves that the <img src= tag isn't broken, but obviously I would prefer to be able to have the images linked within an internal img folder in the theme. The background image I have used in my site (which is linked in the bootstrap.css and is in the same 'img' folder as the two images I am trying to link to) works perfectly. I've tried copying the formatting of that href link but it doesn't seem to work either.

I've tried many variations of 'img/favicon.ico', '/img/favicon.ico', '../img/favicon.ico' but none of them worked to link to the image files in both cases.

Here is my code for the header.php file:

```<code><?php
/**
 * The header for our theme
 *
 * This is the template that displays all of the <head> section and everything up until <div id="content">
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package wpbootstrap-sofa
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="icon" href='../img/favicon.ico'>
<!-- Bootstrap core CSS -->

<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->

<!-- Custom styles for this template -->

<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
    <?php wp_head(); ?>
</head>

<body>

    <div class="background">

        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="index.html">home</a>
                </div>
                <div id="navbar" class="collapse navbar-collapse">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.html">home</a>
                        </li>
                        <li><a href="#about">about</a>
                        </li>
                        <li><a href="#blog">blog posts</a>
                        </li>
                        <li><a href="#submit">submit</a>
                        </li>
                        <li><a href="#events">events</a>
                        </li>
                        <li><a href="#mailing">mailing list</a>
                        </li>
                        <li><a href="#contact">contact</a>
                        </li>
                        <li><a href="http://uqsofa.bigcartel.com/" target="_blank">store</a>
                        </li>
                    </ul>
                </div>
                <!--/.collapse navbar-collapse -->
            </div>
        </nav>

        <div class="container">
</code>```

And here is the code for the index.php file:

```<code><?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package wpbootstrap-sofa
 */

get_header(); ?>

<div class="starter-template">
    <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3">
        <div class="center-block">
            <a href="index.html">
                    <img src='../img/sofa-logo.png' class="img-responsive center-block" alt="UQ SoFA logo">
            </a>
        </div>
        <!-- /.center-block -->
    </div>
    </div>
        <div class="row">
                <div class="col-xs-0 col-sm-0 col-md-4 col-lg-4 col-xl-4">
                        <div class="navbar-collapse collapse sidebar-navbar-collapse">
                                <ul class="nav navbar-nav">
                                    <li class="active"><a href="index.html">home</a>
                                    </li>
                                    <li><a href="#about">about</a>
                                    </li>
                                    <li><a href="#blog">blog posts</a>
                                    </li>
                                    <li><a href="#submit">submit</a>
                                    </li>
                                    <li><a href="#events">events</a>
                                    </li>
                                    <li><a href="#mailing">mailing list</a>
                                    </li>
                                    <li><a href="#contact">contact</a>
                                    </li>
                                    <li><a href="http://uqsofa.bigcartel.com/" target="_blank">store</a>
                                    </li>
                                </ul>
                        </div>
                        <!--/.collapse navbar-collapse -->
                    </div>
                    <!-- /.col-xs-0 col-sm-0 col-md-4 col-lg-4 col-xl-4 -->

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
                        <div class="panel panel-default">
                                <div class="panel-body">SoFA at Market Day</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Cut Thumb ARI</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">GoMA Talks</div>
                        </div>
                        <!-- /.panel panel-default-->
                </div>
                <!-- /.col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4-->

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
                        <div class="panel panel-default">
                                <div class="panel-body">Interview with...</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Lecture by...</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Post #474</div>
                        </div>
                        <!-- /.panel panel-default-->
                </div>
                <!-- /.col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4-->
        </div>
        <!-- /.row-->
</div>
<!-- /.starter-template-->

</div>
<!-- /.container -->

</div>
<!-- /.background -->

<?php
get_footer();?>
</code>```

Linked here is a screenshot of the configuration of my theme's folders, including the 'img' folder where the images are contained.

Any help that could be provided would be much appreciated.

答:
You are better to use automatic path, if your image is in your template directory for example :

```<code><img src="<?php echo get_bloginfo("template_directory"); ?>/img/favicon.ico" />
</code>```

You have to remember that the path is relative to the website address, when using /path/to/file, this will be absolute from the domain, so from the root in the website on server side. When using path/to/file, it will be relative to the web page, not the PHP file. This means if you have http://example.com/category/page, the server will try to find <websiteroot>/category/page/path/to/file.

Title: <img src=...> does not display local images in WordPress header.php and index.php

Body:
I am trying to use a simple <img src= tag to link to a favicon.ico in my header.php file and a .png logo in my index.php file in my WordPress theme, but without any luck. I've tested the link by replacing it with a hyperlink to an image hosted online, which works and proves that the <img src= tag isn't broken, but obviously I would prefer to be able to have the images linked within an internal img folder in the theme. The background image I have used in my site (which is linked in the bootstrap.css and is in the same 'img' folder as the two images I am trying to link to) works perfectly. I've tried copying the formatting of that href link but it doesn't seem to work either.

I've tried many variations of 'img/favicon.ico', '/img/favicon.ico', '../img/favicon.ico' but none of them worked to link to the image files in both cases.

Here is my code for the header.php file:

<?php
/**
 * The header for our theme
 *
 * This is the template that displays all of the  section and everything up until

 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package wpbootstrap-sofa
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="icon" href='../img/favicon.ico'>

    <?php wp_head(); ?>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        Toggle navigation

                    </button>
                    home

home

about

blog posts

submit

events

mailing list

contact

store

And here is the code for the index.php file:

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package wpbootstrap-sofa
 */

get_header(); ?>

home

about

blog posts

submit

events

mailing list

contact

store

SoFA at Market Day

Cut Thumb ARI

GoMA Talks

Interview with...

Lecture by...

Post #474

<?php
get_footer();?>

Linked here is a screenshot of the configuration of my theme's folders, including the 'img' folder where the images are contained.

Any help that could be provided would be much appreciated.

Body:
You are better to use automatic path, if your image is in your template directory for example :

<img src="<?php echo get_bloginfo("template_directory"); ?>/img/favicon.ico" />

You have to remember that the path is relative to the website address, when using /path/to/file, this will be absolute from the domain, so from the root in the website on server side. When using path/to/file, it will be relative to the web page, not the PHP file. This means if you have http://example.com/category/page, the server will try to find <websiteroot>/category/page/path/to/file.


问:
Cannot add SourceSafe Database as Visual Studio 2010 source control
My issue is that I cannot add SourceSafe Database for source control within Visual Studio 2010.

Our team was initially using VSS for source control in Visual Studio 2010.   During an evaluation of TFS, I switched my source control to TFS. It will be a few weeks before a decision is made on TFS, so I needed to switch my source control back to VSS.   However I'm now unable to add a SourceSafe Database in Visual Studio.

Steps to Reproduce in Visual Studio 2010:
1) Access the 'Open SourceSafe Database' form via Tools->Options->Source Control->Plug-in Settings-->Advanced
or via File->Source Control
2) The list of available database is blank so I choose 'Browse'.
3) I browse to the srcsafe.ini file for my VSS database and select it.

4) I'm promted to confirm the Database Name - Click OK.
5) The database does not appear in the 'Open SourceSafe' Database form.  The list of available databases is still blank.

Note that I can add the database fine outside of Visual Studio using VSS directly.   However the databases I add via VSS do not appear in the Visual Studio forms.

I'm suspicious that this is related to "down-grading" from TFS to VSS which may not have been heavily tested at MS.

Any assistance is appreciated.

答:
I installed VS2010, then i install VSS, then i have the same problem, cant connect to my VSS it by default opens (TFS)

the suggestion here, to reinstall, dont sound good, did a bit more searching and found this:-
http://social.msdn.microsoft.com/Forums/en/vssourcecontrol/thread/6c927805-bca6-445b-b406-0a0da8fa21d3

and found the easy solution that 'CletusLoomis' is looking for:

simply:-
hanks for your post.

Could you please try the following steps?

Open VS2010, then choose the menu: Tools->Options, then click "Souce Control"

click drop-down box under text"Current souce control plug-in", use "None", rather than "Microsoft Visual Source Safe"

thats it, problem solved!
:)

hope this helps someone else who found this page via google.


问:
Can I make a CSS grid with dynamic number of rows or columns?
What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let's assume there will always be four cells per row. Can I specify a grid with such a dynamic number of rows?

To make it easier, here's the Flexbox implementation:

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
.container .item {
  flex: 0 0 calc(25% - 1em);
  min-height: 120px;
  margin: 0.25em 0.5em;
}</code>```

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>```

P.S. Apparently, I wasn't clear enough the first time... I want to recreate this effect using the latest CSS Grid Layout.

答:
Something like this?

$(document).ready(function() {
 //Prepare Element selectors
  var cssElem = $("#Dynam"), rowElem = $("#rows"), columnElem = $("#columns"), appElem = $("#app");
  var noItems = $(".item").length,defaultColumns = 4;

  //Init default state
  cssElem.html(".container .item {flex: 0 0 calc(" + (100 / defaultColumns) + "% - 1em);}");
  columnElem.val(defaultColumns);
  rowElem.val(Math.ceil(noItems / columnElem.val()));

  //Add listeners to change
  appElem.on("DOMSubtreeModified", function() {
    noItems = $(".item").length;
    rowElem.val(Math.ceil(noItems / columnElem.val()));
  });
  columnElem.on("change", function() {
    rowElem.val(Math.ceil(noItems / columnElem.val()));
    cssElem.html(".container .item {flex: 0 0 calc(" + (100 / columnElem.val()) + "% - 1em);}");
  });
  rowElem.on("change", function() {
    columnElem.val(Math.ceil(noItems / rowElem.val()));
    cssElem.html(".container .item {flex: 0 0 calc(" + (100 / columnElem.val()) + "% - 1em);}");
  });
});

const COLORS = ['#FE9', '#9AF', '#F9A', "#AFA", "#FA7"];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, {
    color,
    num
  }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for (let i = 0; i < 5; i++) {
    addItem(container, tmpl);
  }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}

.container .item {
  min-height: 120px;
  margin: 0.25em 0.5em;
  overflow: hidden;
}</code>```

<button id="add_el">Add element</button> rows:
<input id="rows" /> columns:<input id="columns" />

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>```

ContentLicense: CC BY-SA 4.0

Body:
What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let's assume there will always be four cells per row. Can I specify a grid with such a dynamic number of rows?

To make it easier, here's the Flexbox implementation:

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});

.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
.container .item {
  flex: 0 0 calc(25% - 1em);
  min-height: 120px;
  margin: 0.25em 0.5em;
}

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>

P.S. Apparently, I wasn't clear enough the first time... I want to recreate this effect using the latest CSS Grid Layout.

Body:
Something like this?

$(document).ready(function() {
 //Prepare Element selectors
  var cssElem = $("#Dynam"), rowElem = $("#rows"), columnElem = $("#columns"), appElem = $("#app");
  var noItems = $(".item").length,defaultColumns = 4;

  //Init default state
  cssElem.html(".container .item {flex: 0 0 calc(" + (100 / defaultColumns) + "% - 1em);}");
  columnElem.val(defaultColumns);
  rowElem.val(Math.ceil(noItems / columnElem.val()));

  //Add listeners to change
  appElem.on("DOMSubtreeModified", function() {
    noItems = $(".item").length;
    rowElem.val(Math.ceil(noItems / columnElem.val()));
  });
  columnElem.on("change", function() {
    rowElem.val(Math.ceil(noItems / columnElem.val()));
    cssElem.html(".container .item {flex: 0 0 calc(" + (100 / columnElem.val()) + "% - 1em);}");
  });
  rowElem.on("change", function() {
    columnElem.val(Math.ceil(noItems / rowElem.val()));
    cssElem.html(".container .item {flex: 0 0 calc(" + (100 / columnElem.val()) + "% - 1em);}");
  });
});

const COLORS = ['#FE9', '#9AF', '#F9A', "#AFA", "#FA7"];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, {
    color,
    num
  }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for (let i = 0; i < 5; i++) {
    addItem(container, tmpl);
  }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});

.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}

.container .item {
  min-height: 120px;
  margin: 0.25em 0.5em;
  overflow: hidden;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style id="Dynam"></style>
<button id="add_el">Add element</button> rows:
<input id="rows" /> columns:<input id="columns" />

<div id="app" class="container">
</div>

<template id="item_template">
  <div class="item" style="background: {{color}}">
    <p>{{ num }}</p>
    <p>
      <button class="del_el">Delete</button>
    </p>
  </div>
</template>