问:
I got Initialization error in Cucumber with maven and selenium
Test Runner

import org.junit.runner.RunWith;

```<code>import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {

}
</code>```

MyApplication.feature

```<code>Feature: Test test smoke scenario

  Scenario Outline: Test  login with valid credentials
    Given open fireFox and start application
    When I enter valid "username" and valid "password"
    Then User should be able to login successfully

Examples:
      | username   | password          |
      | 9739817000 | mnbvcxz  |
      | 9739817001 | mnbvcxz1  |
      | 9739817002 | mnbvcxz2  |
</code>```

Maven POM

```<code><groupId>demo</groupId>
  <artifactId>prac</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>prac</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
</dependency>
</dependencies>
</project>
</code>```

Smoke.java

```<code>public class Smoke {
    WebDriver driver;
    @Given("^open fireFox and start application$")
    public void open_fireFox_and_start_application() throws Throwable {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://testweb.com");

    }

    @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();

    }

    @When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
    public void enter_valid_and_valid(String un, String pwd) throws Throwable {
        driver.findElement(By.id("Username")).sendKeys(un);
        driver.findElement(By.id("Password")).sendKeys(pwd);

    }

    @Then("^Click on Login$")
    public void Click_on_Login() throws Throwable {
        driver.findElement(By.id("loginUser")).click();

    }
    @Then("^User should be able to login successfully$")
    public void User_should_be_able_to_login_successfully() throws Throwable {

    }
</code>```

These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error

enter image description here

答:
Your pom file is absolutely fine.

Here you are using Scenario Outline if you are using Scenario outline there should be Examples annotation in the feature file. Anyways your test scenario can be achieved without using scenario outline

Update feature file and java file with below code:

Myapplication.feature:
Feature: Test test smoke scenario

```<code>  Scenario: Test  login with valid credentials
     Given open fireFox and start application
     When I click on Login
     When I enter valid "username" and valid "password"
     Then I click on Loginbutton
     Then User should be able to login successfully
</code>```

Smoke.java:

```<code>import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class Smoke {
   WebDriver driver;
@Given("^open fireFox and start application$")
public void open_fireFox_and_start_application() throws Throwable {
    driver=new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://testweb.com");

}

 @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
    }

@When("^I enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void i_enter_valid_and_valid(String arg1, String arg2) throws   Throwable {
    driver.findElement(By.id("Username")).sendKeys(arg1);
    driver.findElement(By.id("Password")).sendKeys(arg2);
}

@Then("^I click on Loginbutton$")
public void Click_on_Login() throws Throwable {
    driver.findElement(By.id("loginUser")).click();

}
@Then("^User should be able to login successfully$")
public void User_should_be_able_to_login_successfully() throws Throwable {

}
}
</code>```

Maintain Folder structure as mentioned in the attached image

If you want to use scenario outline update feature file like below
Same smoke.java file will works in this case.

```<code>Feature: Test test smoke scenario

 Scenario Outline: Test  login with valid credentials
  Given open fireFox and start application
  When I click on Login
  When I enter valid "<username>" and valid "<password>"
  Then I click on Loginbutton
  Then User should be able to login successfully

Examples:
  |username|password|
  |test|test|
</code>```

Let me know if it works for you

ContentLicense: CC BY-SA 4.0

Body:
Test Runner

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {

}

MyApplication.feature

Feature: Test test smoke scenario

  Scenario Outline: Test  login with valid credentials
    Given open fireFox and start application
    When I enter valid "username" and valid "password"
    Then User should be able to login successfully

Examples:
      | username   | password          |
      | 9739817000 | mnbvcxz  |
      | 9739817001 | mnbvcxz1  |
      | 9739817002 | mnbvcxz2  |

Maven POM

<groupId>demo</groupId>
  <artifactId>prac</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>prac</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
</dependency>
</dependencies>
</project>

Smoke.java

public class Smoke {
    WebDriver driver;
    @Given("^open fireFox and start application$")
    public void open_fireFox_and_start_application() throws Throwable {
        driver=new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://testweb.com");

    }

    @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();

    }

    @When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
    public void enter_valid_and_valid(String un, String pwd) throws Throwable {
        driver.findElement(By.id("Username")).sendKeys(un);
        driver.findElement(By.id("Password")).sendKeys(pwd);

    }

    @Then("^Click on Login$")
    public void Click_on_Login() throws Throwable {
        driver.findElement(By.id("loginUser")).click();

    }
    @Then("^User should be able to login successfully$")
    public void User_should_be_able_to_login_successfully() throws Throwable {

    }

These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error

enter image description here

Body:
Your pom file is absolutely fine.

Here you are using Scenario Outline if you are using Scenario outline there should be Examples annotation in the feature file. Anyways your test scenario can be achieved without using scenario outline

Update feature file and java file with below code:

Myapplication.feature:
Feature: Test test smoke scenario

  Scenario: Test  login with valid credentials
     Given open fireFox and start application
     When I click on Login
     When I enter valid "username" and valid "password"
     Then I click on Loginbutton
     Then User should be able to login successfully

Smoke.java:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class Smoke {
   WebDriver driver;
@Given("^open fireFox and start application$")
public void open_fireFox_and_start_application() throws Throwable {
    driver=new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://testweb.com");

}

 @When("^I click on Login$")
    public void I_click_on_Login() throws Throwable {
        driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
    }

@When("^I enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void i_enter_valid_and_valid(String arg1, String arg2) throws   Throwable {
    driver.findElement(By.id("Username")).sendKeys(arg1);
    driver.findElement(By.id("Password")).sendKeys(arg2);
}

@Then("^I click on Loginbutton$")
public void Click_on_Login() throws Throwable {
    driver.findElement(By.id("loginUser")).click();

}
@Then("^User should be able to login successfully$")
public void User_should_be_able_to_login_successfully() throws Throwable {

}
}

Maintain Folder structure as mentioned in the attached image

If you want to use scenario outline update feature file like below
Same smoke.java file will works in this case.

Feature: Test test smoke scenario

 Scenario Outline: Test  login with valid credentials
  Given open fireFox and start application
  When I click on Login
  When I enter valid "<username>" and valid "<password>"
  Then I click on Loginbutton
  Then User should be able to login successfully

Examples:
  |username|password|
  |test|test|

Let me know if it works for you


来源: stackexchange

问:
Example for RTNPARM keyword and use case
After reading the IBM documentation about RTNPARM keyword, it's still not clear, to me, how I have to handle it.

Could someone give me a small procedure example?

If it is much faster, why IBM didn't make it implicit?

答: If you compare subprocedures with Microsofts VB/VBA, a subprocedure with rtnparm is a function and a subprocedure without rtnparm is a sub.</p>

ContentLicense: CC BY-SA 3.0


问:
wait for a promise inside a directive before rendering
I have a directive like this:

```<code>'use strict';

angular.module('rowe.desktop').directive('bottomBar', function ($translate, sessionService) {
  return {
    templateUrl: 'modules/desktop/shared/directives/views/_bottomBar.html',
    restrict: 'E',
    replace: true,
    scope: {},
    link: function (scope) {
      var nowDate = new Date();
     $translate('COPYRIGHT').then((translation)=>{
       scope.copyright = translation;
     })
    }
  };
})
</code>```

the translation service acutally returns a promise and I need to wait for that promise to get resolved before the rendering is performed. Any suggestions?

答:
I'd use ngIf on the root element of the template to make prevent the root element from rendering unless the ngIf condition is true.

If your template looks as follows:

```<code><div>This is the template of the directive</div>
</code>```

you can add an ngIf that is false initially, therefore not rendering the div.

```<code><div ng-if="allowRendering">This is the template of the directive</div>
</code>```

in your directive you set allowRendering to true whenever you feel like the template should be rendered.

I have created an example in JSFiddle: JSFiddle example

Body:
I have a directive like this:

'use strict';

angular.module('rowe.desktop').directive('bottomBar', function ($translate, sessionService) {
  return {
    templateUrl: 'modules/desktop/shared/directives/views/_bottomBar.html',
    restrict: 'E',
    replace: true,
    scope: {},
    link: function (scope) {
      var nowDate = new Date();
     $translate('COPYRIGHT').then((translation)=>{
       scope.copyright = translation;
     })
    }
  };
})

the translation service acutally returns a promise and I need to wait for that promise to get resolved before the rendering is performed. Any suggestions?

Body:
I'd use ngIf on the root element of the template to make prevent the root element from rendering unless the ngIf condition is true.

If your template looks as follows:

<div>This is the template of the directive</div>

you can add an ngIf that is false initially, therefore not rendering the div.

<div ng-if="allowRendering">This is the template of the directive</div>

in your directive you set allowRendering to true whenever you feel like the template should be rendered.

I have created an example in JSFiddle: JSFiddle example


问:
Log of remote history
I have been asked to make a log of all the pushes made to a remote repository during a working day to display along side our build information. I am having trouble getting the necessary information for the remote repository.

I can get the info in relation to my local version of the repository with "$git log", and I have come close with the command "$git reflog show origin/master" on the remote but the main problem here is that it shows no details.

My remote repository is hosted on BitBucket. I am trying to get the list of files that have been pushed and the commit message associated with that push, across the whole day. Is this possible?

答:
You have first to fetch the remote branch into your local remotes/origin. Then you can log this. For instance, if you are working on branch master:

```<code>git fetch
git log FETCH_HEAD
</code>```

This will now show you the log from remotes/origin/master on your local machine.

Title: Log of remote history

Body:
You have first to fetch the remote branch into your local remotes/origin. Then you can log this. For instance, if you are working on branch master:

git fetch
git log FETCH_HEAD

This will now show you the log from remotes/origin/master on your local machine.


问:
PHP: display all students marks with subject column
I have 3 tables student_register, subject, marks have to display all students marks with subject column
marks table with student_register_id, subject_id
I want to show output in table format tell me mysql query.

Studentid  StudentName Sub1  Sub2  Sub3 Sub4  Sub5  Sub6  Outof

```<code>1        Akash       75    80   82   86    70    71    100

2        Amit        92     87  89   93    65     82   100
</code>```

My query is

```<code>SELECT DISTINCT student_register.student_register_id,student_register.student_first_name, student_register.stud_l_name, subject.subject_name, subject.subject_id, marks.marks_obtain,marks.outof, marks.status
FROM student_register
INNER JOIN marks ON  marks.student_register_id=student_register.student_register_id

INNER JOIN subject ON marks.subject_id=subject.subject_id
INNER JOIN class_teacher ON class_teacher.division_id = student_register.division_id AND class_teacher.class_teacher_id = '".$_SESSION['class_teacher_id']."'";
</code>```

it gives me output

Studentid  StudentName Sub1  Sub2  Sub3 Sub4  Sub5  Sub6  Outof

```<code>1        Akash           71                            100

2        Akash      92                                 100

3        Akash                       93                100

4        Amit                    98                    100

5        Amit       89                                 100
</code>```

答:
```<code>"SELECT s.student_register_id,
       s.student_first_name,
       a.mark Sub1,
       b.mark Sub2,
       c.mark Sub3,
       d.mark Sub4,
       e.mark Sub5,
       f.mark Sub6,
       100 Outof
FROM student_register s, marks a, marks b, marks c, marks d, marks e, marks f
INNER JOIN class_teacher k ON k.division_id=s.division_id
WHERE (s.student_register_id = a.student_register_id AND a.Subjectid = 100)
AND   (s.student_register_id = b.student_register_id AND b.Subjectid = 102)
AND   (s.student_register_id = c.student_register_id AND c.Subjectid = 103)
AND   (s.student_register_id = d.student_register_id AND d.Subjectid = 104)
AND   (s.student_register_id = e.student_register_id AND e.Subjectid = 105)
AND   (s.student_register_id = f.student_register_id AND f.Subjectid = 106)
AND   k.class_teacher_id='".$_SESSION['class_teacher_id']."'";
</code>```

You can try this

Body:
I have 3 tables student_register, subject, marks have to display all students marks with subject column
marks table with student_register_id, subject_id
I want to show output in table format tell me mysql query.

Studentid  StudentName Sub1  Sub2  Sub3 Sub4  Sub5  Sub6  Outof

1        Akash       75    80   82   86    70    71    100

2        Amit        92     87  89   93    65     82   100

My query is

SELECT DISTINCT student_register.student_register_id,student_register.student_first_name, student_register.stud_l_name, subject.subject_name, subject.subject_id, marks.marks_obtain,marks.outof, marks.status
FROM student_register
INNER JOIN marks ON  marks.student_register_id=student_register.student_register_id

INNER JOIN subject ON marks.subject_id=subject.subject_id
INNER JOIN class_teacher ON class_teacher.division_id = student_register.division_id AND class_teacher.class_teacher_id = '".$_SESSION['class_teacher_id']."'";

it gives me output

Studentid  StudentName Sub1  Sub2  Sub3 Sub4  Sub5  Sub6  Outof

1        Akash           71                            100

2        Akash      92                                 100

3        Akash                       93                100

4        Amit                    98                    100

5        Amit       89                                 100

Body:
"SELECT s.student_register_id,
       s.student_first_name,
       a.mark Sub1,
       b.mark Sub2,
       c.mark Sub3,
       d.mark Sub4,
       e.mark Sub5,
       f.mark Sub6,
       100 Outof
FROM student_register s, marks a, marks b, marks c, marks d, marks e, marks f
INNER JOIN class_teacher k ON k.division_id=s.division_id
WHERE (s.student_register_id = a.student_register_id AND a.Subjectid = 100)
AND   (s.student_register_id = b.student_register_id AND b.Subjectid = 102)
AND   (s.student_register_id = c.student_register_id AND c.Subjectid = 103)
AND   (s.student_register_id = d.student_register_id AND d.Subjectid = 104)
AND   (s.student_register_id = e.student_register_id AND e.Subjectid = 105)
AND   (s.student_register_id = f.student_register_id AND f.Subjectid = 106)
AND   k.class_teacher_id='".$_SESSION['class_teacher_id']."'";

You can try this


问:
Comparing floating-point numbers (floats or doubles) for min/max
How to compare two different floats, to a certain degree of accuracy. I know that there are very slight imprecisions while using floats or doubles in any programming language, but which may however, be enough to cause this comparison of floats a < b to return a different value than it actually should.

I was solving a problem from the UVa Online Judge which gave me a Wrong Answer many times. It took few float values as input, albeit, to 2 decimal places. I figured out the makeshift solution, which was by splitting the input and converting it to ints, but I wouldn't prefer to use that always.

So my question is, what's the best way to compare whether a float a is lesser (or greater) than a float b, provided that the inputs of a and b are given correct to n decimal places, in this case, 2?

The language I prefer is C++.

答:
Comparing floats is alway a tricky Here is a more complicated example, showing why you should use std::numeric_limits<T>::epsilon().

The first line returns true, but the second returns false (on my machine).

```<code>float64_t CalculateEpsilon ()
{
    float64_t l_AllowedInaccuray = 1; // 1.1, 0.9
    int32_t significantDecimalPlaces = 2;

    return ( l_AllowedInaccuray * pow ( 0.1, significantDecimalPlaces ) );
}

bool IsEqual ( float64_t lhs, float64_t rhs )
{
    float64_t l_Epsilon = CalculateEpsilon ();

    float64_t l_Delta = std::abs ( lhs - rhs );
    return l_Delta <= l_Epsilon;
}

int32_t main ()
{
    std::cout << IsEqual ( 107.35999999999999, 107.350 );  //returns true
    std::cout << IsEqual ( 107.359999999999999, 107.350 ); //returns false

    return 0;
}
</code>```

Body:
Comparing floats is alway a tricky Here is a more complicated example, showing why you should use std::numeric_limits<T>::epsilon().

The first line returns true, but the second returns false (on my machine).

float64_t CalculateEpsilon ()
{
    float64_t l_AllowedInaccuray = 1; // 1.1, 0.9
    int32_t significantDecimalPlaces = 2;

    return ( l_AllowedInaccuray * pow ( 0.1, significantDecimalPlaces ) );
}

bool IsEqual ( float64_t lhs, float64_t rhs )
{
    float64_t l_Epsilon = CalculateEpsilon ();

    float64_t l_Delta = std::abs ( lhs - rhs );
    return l_Delta <= l_Epsilon;
}

int32_t main ()
{
    std::cout << IsEqual ( 107.35999999999999, 107.350 );  //returns true
    std::cout << IsEqual ( 107.359999999999999, 107.350 ); //returns false

    return 0;
}


问:
How to tackle this session problem in ASP.NET,VB.NET?
How to tackle this session problem in ASP.NET,VB.NET?

The following requirement are there:

When the authorized user logs into the system that user is not allowed to login from another computer or in different browser other than that user is using right at this time.

The remedy we applied was: We have kept "Is_Loggedin" as a column with data type "bit" in a mst_vendor as a table name. When a user logs in we set the flag, Is_Loggedin, to "1" and each time when someone tries to log in using this account, the system is showing the error "The user is already logged in.".

When the user logs out it turns to "0" as the logout procedure calls as soon as the user clicks the log out button.

Problem scenario:

When the user closes the browser the flag remains the same, that is, "1".

When power gets off, it remains the same as "1".

If the session timeouts after a predefined value it remains the same.

There may be different scenarios other than this.

Is there any way so that we can store this internal flagging for the user's login status using the application object?

It may improve efficiency of the system and also eliminates the above problematic scenarios.

答:
You should use the Global.asax file and use the Session_End function.

Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

ContentLicense: CC BY-SA 2.5


问:
how to put pictures in a row bootstrap
I'm trying to get these 3 pictures in a row with no or little spaces in between, but this code is causing them to stack on top of each other.  I also want them to be aligned to the center of the page.</p>

```<code><div class="container">
  <div class="row col-xs-2">
  <img style= "width: 25%; height: 25%" src="https://image.ibb.co/ckA7ka/mr_marbles.png" alt="Mister Marbles head tilt">
</div>
<div class="row col-xs-2">
  <img style= "width: 25%; height: 25%"  src="https://image.ibb.co/bTMKyv/kermit.png" alt="Kermit the Dog">
</div>
<div class="row col-xs-2">
  <img style= "width: 25%; height: 25%" src="https://image.ibb.co/ki8tQa/peach.png" alt="Peach posing magestically">
</div>
</div>
</code>```

答:
```<code>    **YOu need to put everthing in row then add one div with a class .center make the div center finally offset the the first column**
    ==============================================================

<style>
    /*CENTER COLUMN */
    .align-center {
        text-align: center;
    }
    /*CENTER DIV*/
    .center {
        margin: 0 auto;
        width: 80%;
    }
</style>
<div class="container">
    <div class="row">
        <div class="center">
            <div class="col-xs-2 align-center col-xs-offset-3"> <img style="width: 25%; height: 25%" src="https://image.ibb.co/ckA7ka/mr_marbles.png" alt="Mister Marbles head tilt"> </div>
            <div class="col-xs-2 align-center"> <img style="width: 25%; height: 25%" src="https://image.ibb.co/bTMKyv/kermit.png" alt="Kermit the Dog"> </div>
            <div class="col-xs-2 align-center"> <img style="width: 25%; height: 25%" src="https://image.ibb.co/ki8tQa/peach.png" alt="Peach posing magestically"> </div>
        </div>
    </div>
</div>
</code>```

Title: how to put pictures in a row bootstrap


问:
CastError mongoose
I am using mongodb in an express/nodejs project. I have a nested schema such that Themes have categories

Given this schema:

```<code>var ControlCategorySchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the category name'
    }
});
ControlCategorySchema.plugin(autoIncrement.plugin, 'ControlCategorySchemaCounter');

var ThemeSchema = new Schema({
    name : String,
    category : {type: Schema.Types.ObjectId, ref: 'ControlCategorySchema'}
});
ThemeSchema.plugin(autoIncrement.plugin, 'ThemeCounter');
</code>```

And the following controller code:

```<code>exports.create_a_theme = function(req, res) {
    console.log(req.body.category);
    if (req.body.category != undefined) {
        addTheme(req,res,req.body.category);
    }

};

function addTheme(req,res,category_id) {
    console.log("category id " + category_id);
    ControlCategory.findById(category_id, function (err, category_found) {
        if (err)
            res.send(err)

        req.body.category = category_found;
        console.log("body is " + req.body.category);
        var new_theme = new Theme();
        new_theme.name = req.body.name;
        new_theme.category = req.body.category;
        new_theme.save(function (err, theme) {
            if (err)
                res.send(err);
            console.log(theme);
            res.json(theme);
        });
    });
}
</code>```

Can anyone help solve why posting this json

```<code>{
    "name": "Application Security",
    "category": 0
}
</code>```

Results in the error below:

```<code>{
  "errors": {
    "category": {
      "message": "Cast to ObjectID failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
      "name": "CastError",
      "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
      "kind": "ObjectID",
      "value": {
        "_id": 0,
        "name": "Application Security",
        "__v": 0
      },
      "path": "category",
      "reason": {
        "message": "Cast to ObjectId failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
        "name": "CastError",
        "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
        "kind": "ObjectId",
        "value": {
          "_id": 0,
          "name": "Application Security",
          "__v": 0
        },
        "path": "category"
      }
    }
  },
  "message": "Theme validation failed",
  "name": "ValidationError"
}
</code>```

One thing that is very strange is that I do virtually the same thing on another schema and controller code and it works!

```<code>var AssessmentSchema = new Schema({
    name: {
        type: String,
        Required: 'Kindly enter the name of the assessment'
    },
    Created_date: {
        type: Date,
        default: Date.now
    },
    status: { type: Schema.ObjectId, ref: 'AssessmentStatus' },
});

var AssessmentStatusSchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the name of the assessment status'
    }

});

exports.create_an_assessment = function(req, res) {
    console.log(req.body.status);
    if (req.body.status == undefined) {
        AssessmentStatus.findOne({"name": "Due For Assessment"}, function (err, assessment_status) {
            if (err)
                res.send(err)
            addAssessment(req,res,assessment_status._id);
        });
    }
    else {

        addAssessment(req,res,req.body.status);
    }

};

function addAssessment(req,res,status_id) {
    console.log("status id " + status_id);
    AssessmentStatus.findById(status_id, function (err, assessment_status) {
        if (err)
            res.send(err)
        req.body.status = assessment_status;
        console.log("body is " + req.body.status);
        var new_assessment = new Assessment();
        new_assessment.name = req.body.name;
        new_assessment.status = assessment_status;
        new_assessment.save(function (err, assessment) {
            if (err)
                res.send(err);
            console.log(assessment);
            res.json(assessment);
        });
    });
}
</code>```

And there I post same kind of data

```<code>{
    "name": "Assessment 10",
    "status": 6
}
</code>```

and get the desired result

```<code>{
  "__v": 0,
  "_id": 28,
  "status": {
    "_id": 6,
    "name": "Due For Assessment",
    "__v": 0
  },
  "name": "Assessment 10",
  "Created_date": "2017-03-31T06:48:21.999Z"
}
</code>```

I cant tell what is different?

答:
ThemeSchema.category is of type Schema.Types.ObjectId and '0' is not a valid mongo id. A valid mongo id would be 12-byte hexadecimal, for example 507f1f77bcf86cd799439011.

You have two options here, either define ThemeSchema.category as a number or assign valid mongo id. Since you are referring ControlCategorySchema in ThemeSchema, I guess later is the only option here.

Title: CastError mongoose

Body:
I am using mongodb in an express/nodejs project. I have a nested schema such that Themes have categories

Given this schema:

var ControlCategorySchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the category name'
    }
});
ControlCategorySchema.plugin(autoIncrement.plugin, 'ControlCategorySchemaCounter');

var ThemeSchema = new Schema({
    name : String,
    category : {type: Schema.Types.ObjectId, ref: 'ControlCategorySchema'}
});
ThemeSchema.plugin(autoIncrement.plugin, 'ThemeCounter');

And the following controller code:

exports.create_a_theme = function(req, res) {
    console.log(req.body.category);
    if (req.body.category != undefined) {
        addTheme(req,res,req.body.category);
    }

};

function addTheme(req,res,category_id) {
    console.log("category id " + category_id);
    ControlCategory.findById(category_id, function (err, category_found) {
        if (err)
            res.send(err)

        req.body.category = category_found;
        console.log("body is " + req.body.category);
        var new_theme = new Theme();
        new_theme.name = req.body.name;
        new_theme.category = req.body.category;
        new_theme.save(function (err, theme) {
            if (err)
                res.send(err);
            console.log(theme);
            res.json(theme);
        });
    });
}

Can anyone help solve why posting this json

{
    "name": "Application Security",
    "category": 0
}

Results in the error below:

{
  "errors": {
    "category": {
      "message": "Cast to ObjectID failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
      "name": "CastError",
      "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
      "kind": "ObjectID",
      "value": {
        "_id": 0,
        "name": "Application Security",
        "__v": 0
      },
      "path": "category",
      "reason": {
        "message": "Cast to ObjectId failed for value \"{ _id: 0, name: 'Application Security', __v: 0 }\" at path \"category\"",
        "name": "CastError",
        "stringValue": "\"{ _id: 0, name: 'Application Security', __v: 0 }\"",
        "kind": "ObjectId",
        "value": {
          "_id": 0,
          "name": "Application Security",
          "__v": 0
        },
        "path": "category"
      }
    }
  },
  "message": "Theme validation failed",
  "name": "ValidationError"
}

One thing that is very strange is that I do virtually the same thing on another schema and controller code and it works!

var AssessmentSchema = new Schema({
    name: {
        type: String,
        Required: 'Kindly enter the name of the assessment'
    },
    Created_date: {
        type: Date,
        default: Date.now
    },
    status: { type: Schema.ObjectId, ref: 'AssessmentStatus' },
});

var AssessmentStatusSchema = new Schema({
    name: {
        type: String,
        Required: 'Please enter the name of the assessment status'
    }

});

exports.create_an_assessment = function(req, res) {
    console.log(req.body.status);
    if (req.body.status == undefined) {
        AssessmentStatus.findOne({"name": "Due For Assessment"}, function (err, assessment_status) {
            if (err)
                res.send(err)
            addAssessment(req,res,assessment_status._id);
        });
    }
    else {

        addAssessment(req,res,req.body.status);
    }

};

function addAssessment(req,res,status_id) {
    console.log("status id " + status_id);
    AssessmentStatus.findById(status_id, function (err, assessment_status) {
        if (err)
            res.send(err)
        req.body.status = assessment_status;
        console.log("body is " + req.body.status);
        var new_assessment = new Assessment();
        new_assessment.name = req.body.name;
        new_assessment.status = assessment_status;
        new_assessment.save(function (err, assessment) {
            if (err)
                res.send(err);
            console.log(assessment);
            res.json(assessment);
        });
    });
}

And there I post same kind of data

{
    "name": "Assessment 10",
    "status": 6
}

and get the desired result

{
  "__v": 0,
  "_id": 28,
  "status": {
    "_id": 6,
    "name": "Due For Assessment",
    "__v": 0
  },
  "name": "Assessment 10",
  "Created_date": "2017-03-31T06:48:21.999Z"
}

I cant tell what is different?


问:
How to use reflection inside a static method
Ive got a logging method:

```<code>    public static void WriteSimpleDebugTrace(string logFilePathArg, string messageArg)
    {

        StreamWriter writer;

        //Environment.ExpandEnvironmentVariables("%SystemDrive%") [will get to the c drive]
        if (EnumsAndConstants.EnableApplicationLogging)
        {
            writer = new StreamWriter(logFilePathArg, true);
            writer.Write("Time: " + DateTime.Now.ToString() + " Message: " + messageArg);
            writer.Write(Environment.NewLine);
            writer.Flush();
            writer.Close();
        }

    }
</code>```

And I am trying to access this.GetType().Name inside it but im not allowed to. Is there anyway around this? I want to easily get the calling class name when this method is called without having to rewrite all calls to this method...

答: You can use stackTrace.GetFrame(1).GetMethod() to retrieve the calling method and from there the associated class name

Body:
Ive got a logging method:

    public static void WriteSimpleDebugTrace(string logFilePathArg, string messageArg)
    {

        StreamWriter writer;

        //Environment.ExpandEnvironmentVariables("%SystemDrive%") [will get to the c drive]
        if (EnumsAndConstants.EnableApplicationLogging)
        {
            writer = new StreamWriter(logFilePathArg, true);
            writer.Write("Time: " + DateTime.Now.ToString() + " Message: " + messageArg);
            writer.Write(Environment.NewLine);
            writer.Flush();
            writer.Close();
        }

    }

And I am trying to access this.GetType().Name inside it but im not allowed to. Is there anyway around this? I want to easily get the calling class name when this method is called without having to rewrite all calls to this method...


问:
WPF: Creating the same grid for every object
I have a grid of one player that looks like this: image
and here is the code:

```<code><Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5" Background="AliceBlue">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Label Grid.Column="4" Grid.Row="0" FontWeight="Bold">Pool</Label>
        <Label Grid.Column="5" Grid.Row="0" FontWeight="Bold">Edge</Label>
        <Label Grid.ColumnSpan="2" Grid.Row="0" HorizontalAlignment="Center" FontWeight="Bold">Felix</Label>
        <Label Grid.Column="0" Grid.Row="1">Might</Label>
        <Button x:Name="btMightP1" Margin="3" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3, 0, 3, 0" Click="btMightP1_Click">+</Button>
        <TextBox  x:Name="tbMight1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" Grid.Column="2" Grid.Row="1" MinWidth="40">10</TextBox>
        <Button x:Name="btMightM1" Margin="3" Grid.Column="3" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="4, 0, 4, 0" Click="btMightM1_Click">-</Button>
        <TextBox Name="lbMightPool1" Grid.Row="1" Grid.Column="4" HorizontalAlignment="Center">0</TextBox>
        <TextBox Name="lbMightEdge1" Grid.Row="1" Grid.Column="5" HorizontalAlignment="Center">0</TextBox>
        <Label Grid.Column="0" Grid.Row="2">Speed</Label>
        <Button x:Name="btSpeedP1" Margin="3" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3, 0, 3, 0" Click="btSpeedP1_Click">+</Button>
        <TextBox x:Name="tbSpeed1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" Grid.Column="2" Grid.Row="2" MinWidth="40">10</TextBox>
        <Button x:Name="btSpeedM1" Margin="3" Grid.Column="3" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="4, 0, 4, 0" Click="btSpeedM1_Click">-</Button>
        <TextBox Name="lbSpeedPool1" Grid.Row="2" Grid.Column="4" HorizontalAlignment="Center">0</TextBox>
        <TextBox Name="lbSpeedEdge1" Grid.Row="2" Grid.Column="5" HorizontalAlignment="Center">0</TextBox>
        <Label Grid.Column="0" Grid.Row="3">Intellect</Label>
        <Button x:Name="btIntellectP1" Margin="3" Grid.Column="1" Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3, 0, 3, 0" Click="btIntellectP1_Click">+</Button>
        <TextBox x:Name="tbIntellect1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" Grid.Column="2" Grid.Row="3" MinWidth="40">10</TextBox>
        <Button x:Name="btIntellectM1" Margin="3" Grid.Column="3" Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="4, 0, 4, 0" Click="btIntellectM1_Click">-</Button>
        <TextBox Name="lbIntellectPool1" Grid.Row="3" Grid.Column="4" HorizontalAlignment="Center">0</TextBox>
        <TextBox Name="lbIntellectEdge1" Grid.Row="3" Grid.Column="5" HorizontalAlignment="Center">0</TextBox>
    </Grid>
</code>```

code for Player class:

```<code>public class Player
{
    public DataClass Might { get; set; }
    public DataClass Speed { get; set; }
    public DataClass Intellect { get; set; }
    public string Name { get; set; }
    public Player()
    {
        Might = new DataClass();
        Speed = new DataClass();
        Intellect = new DataClass();
    }
</code>```

and DataClass:

```<code>public class DataClass
{
    public string Current { get; set; }
    public string Pool { get; set; }
    public string Edge { get; set; }
    public DataClass()
    {
        Current = "0";
        Pool = "0";
        Edge = "0";
    }
}
</code>```

My question is how can I create identical grid every time I create an object of Player and tie the TextBoxes with newly created object's properties? Is this achievable only using data binding? I've tried to use it but I don't quite understand how the binding works.

答:
Use listbox or ItemsControl.</p>

```<code><Listbox ItemSource="{Binding YourListOfPlayers}">
    <Listbox.ItemTemplate>
        <DataTemplate>
            <Put your common grid here/>
        </DataTemplate>
    </Listbox.ItemTemplate>
</Listbox>
</code>```

Body:
I have a grid of one player that looks like this: image
and here is the code:

<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5" Background="AliceBlue">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        Pool
        Edge
        Felix
        Might
        <Button x:Name="btMightP1" Margin="3" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3, 0, 3, 0" Click="btMightP1_Click">+</Button>
        <TextBox  x:Name="tbMight1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" Grid.Column="2" Grid.Row="1" MinWidth="40">10</TextBox>
        <Button x:Name="btMightM1" Margin="3" Grid.Column="3" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="4, 0, 4, 0" Click="btMightM1_Click">-</Button>
        <TextBox Name="lbMightPool1" Grid.Row="1" Grid.Column="4" HorizontalAlignment="Center">0</TextBox>
        <TextBox Name="lbMightEdge1" Grid.Row="1" Grid.Column="5" HorizontalAlignment="Center">0</TextBox>
        Speed
        <Button x:Name="btSpeedP1" Margin="3" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3, 0, 3, 0" Click="btSpeedP1_Click">+</Button>
        <TextBox x:Name="tbSpeed1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" Grid.Column="2" Grid.Row="2" MinWidth="40">10</TextBox>
        <Button x:Name="btSpeedM1" Margin="3" Grid.Column="3" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="4, 0, 4, 0" Click="btSpeedM1_Click">-</Button>
        <TextBox Name="lbSpeedPool1" Grid.Row="2" Grid.Column="4" HorizontalAlignment="Center">0</TextBox>
        <TextBox Name="lbSpeedEdge1" Grid.Row="2" Grid.Column="5" HorizontalAlignment="Center">0</TextBox>
        Intellect
        <Button x:Name="btIntellectP1" Margin="3" Grid.Column="1" Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="3, 0, 3, 0" Click="btIntellectP1_Click">+</Button>
        <TextBox x:Name="tbIntellect1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="2" Grid.Column="2" Grid.Row="3" MinWidth="40">10</TextBox>
        <Button x:Name="btIntellectM1" Margin="3" Grid.Column="3" Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="4, 0, 4, 0" Click="btIntellectM1_Click">-</Button>
        <TextBox Name="lbIntellectPool1" Grid.Row="3" Grid.Column="4" HorizontalAlignment="Center">0</TextBox>
        <TextBox Name="lbIntellectEdge1" Grid.Row="3" Grid.Column="5" HorizontalAlignment="Center">0</TextBox>
    </Grid>

code for Player class:

public class Player
{
    public DataClass Might { get; set; }
    public DataClass Speed { get; set; }
    public DataClass Intellect { get; set; }
    public string Name { get; set; }
    public Player()
    {
        Might = new DataClass();
        Speed = new DataClass();
        Intellect = new DataClass();
    }

and DataClass:

public class DataClass
{
    public string Current { get; set; }
    public string Pool { get; set; }
    public string Edge { get; set; }
    public DataClass()
    {
        Current = "0";
        Pool = "0";
        Edge = "0";
    }
}

My question is how can I create identical grid every time I create an object of Player and tie the TextBoxes with newly created object's properties? Is this achievable only using data binding? I've tried to use it but I don't quite understand how the binding works.

Body:
Use listbox or ItemsControl.

<Listbox ItemSource="{Binding YourListOfPlayers}">
    <Listbox.ItemTemplate>
        <DataTemplate>
            <Put your common grid here/>
        </DataTemplate>
    </Listbox.ItemTemplate>
</Listbox>


问:
Delete rows when specific condition found
I am trying to delete rows which matches below condition.

I have excel workbook in that a sheet named "Calls closed"
in column "I" drop down list there are  many conditions in that I want delete all row which matches below condition.

"Closed by bank", "With Requestor For Closure" ,"Abandoned by Requestor"

I tried below code its not working for me

```<code> Sub Callsclosed_DeleteRow()

 "Closed by bank", "With Requestor For Closure" ,"Abandoned by Requestor"

Dim LR As Long, i As Long
Dim wrksht As Excel.Worksheet

Set wrksht = Application.Worksheets("Calls closed")

LR = Range("A" & Rows.Count).End(xlUp).Row
For i = LR To 20000 Step -1
    If IsError(Application.Match(Range("L" & i).Value, Array("Closed By Bank", "With Requestor For Closure", "Abandoned by Requestor"), 0)) Then
 Rows(i).Delete
    Next i
    End Sub
</code>```

答:
In order to delete all matches to the array, you need to look for If Not IsError(Application.Match... , that means that the current's cell value is found within the array.

Code

```<code>Option Explicit

Sub Callsclosed_DeleteRow()
' "Closed by bank", "With Requestor For Closure" ,"Abandoned by Requestor"

Dim LR As Long, i As Long
Dim WrkSht As Excel.Worksheet

Application.ScreenUpdating = False

Set WrkSht = Application.Worksheets("Calls closed")
With WrkSht
    LR = .Range("L" & .Rows.Count).End(xlUp).Row
    For i = LR To 1 Step -1
        If Not IsError(Application.Match(.Range("L" & i).Value, Array("Closed By Bank", "With Requestor For Closure", "Abandoned by Requestor"), 0)) Then
            .Rows(i).Delete
        End If
    Next i
End With
Application.ScreenUpdating = True

End Sub
</code>```

Body:
I am trying to delete rows which matches below condition.

I have excel workbook in that a sheet named "Calls closed"
in column "I" drop down list there are  many conditions in that I want delete all row which matches below condition.

"Closed by bank", "With Requestor For Closure" ,"Abandoned by Requestor"

I tried below code its not working for me

 Sub Callsclosed_DeleteRow()

 "Closed by bank", "With Requestor For Closure" ,"Abandoned by Requestor"

Dim LR As Long, i As Long
Dim wrksht As Excel.Worksheet

Set wrksht = Application.Worksheets("Calls closed")

LR = Range("A" & Rows.Count).End(xlUp).Row
For i = LR To 20000 Step -1
    If IsError(Application.Match(Range("L" & i).Value, Array("Closed By Bank", "With Requestor For Closure", "Abandoned by Requestor"), 0)) Then
 Rows(i).Delete
    Next i
    End Sub

Body:
In order to delete all matches to the array, you need to look for If Not IsError(Application.Match... , that means that the current's cell value is found within the array.

Code

Option Explicit

Sub Callsclosed_DeleteRow()
' "Closed by bank", "With Requestor For Closure" ,"Abandoned by Requestor"

Dim LR As Long, i As Long
Dim WrkSht As Excel.Worksheet

Application.ScreenUpdating = False

Set WrkSht = Application.Worksheets("Calls closed")
With WrkSht
    LR = .Range("L" & .Rows.Count).End(xlUp).Row
    For i = LR To 1 Step -1
        If Not IsError(Application.Match(.Range("L" & i).Value, Array("Closed By Bank", "With Requestor For Closure", "Abandoned by Requestor"), 0)) Then
            .Rows(i).Delete
        End If
    Next i
End With
Application.ScreenUpdating = True

End Sub


问:
androidstudio external libraries error
I include some dependencies (v23.2.0), but in my project, more external libraries that I didn`t include were there(v24.2.1), so Could you help me to figure out where I made the mistakes?
Here is my pic and code .

app.gradle:

```<code>dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':common')
    apt 'com.zhy:mpermission-compiler:1.0.0'
    compile project(':umeng')
}
</code>```

common.gradle:

```<code>dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.zhy:okhttputils:2.6.2'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup:otto:1.3.7'
    compile 'com.zhy:autolayout:1.4.5'
    compile 'com.yanzhenjie:permission:1.0.5'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    compile 'io.reactivex:rxjava:1.0.13'
    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'com.zhy:mpermission-api:1.0.0'
    compile 'com.github.satyan:sugar:1.5'
}
</code>```

umeng.gradle:

```<code>dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.0'
}
</code>```

答: These Libraries are added with the compile 'com.android.support:design:23.2.0' library</p>

Title: androidstudio external libraries error

Body:
I include some dependencies (v23.2.0), but in my project, more external libraries that I didn`t include were there(v24.2.1), so Could you help me to figure out where I made the mistakes?
Here is my pic and code .

app.gradle:

dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':common')
    apt 'com.zhy:mpermission-compiler:1.0.0'
    compile project(':umeng')
}

common.gradle:

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.zhy:okhttputils:2.6.2'
    compile 'com.oguzdev:CircularFloatingActionMenu:1.0.2'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup:otto:1.3.7'
    compile 'com.zhy:autolayout:1.4.5'
    compile 'com.yanzhenjie:permission:1.0.5'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    compile 'io.reactivex:rxjava:1.0.13'
    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'com.zhy:mpermission-api:1.0.0'
    compile 'com.github.satyan:sugar:1.5'
}

umeng.gradle:

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.0'
}


问:
Binary Search in C - wrong exit code when integer not in the array
This C Binary search function is finding what it's supposed to but I'm getting the error: "\ expected an exit code of 1, not 0 " if the integer it's looking for is not in the array.  I have tried removing false at the end or removing the else statement but this doesn't work. Can anyone see why?

```<code>bool search(int value, int values[], int n)
{
    int min = 0;
    int max = n-1;
    int mid = (max + min) / 2;

    if(n <= 0)
        {
            return false;
        }

    while (values[max] >= values[min])
        {
            if (values[mid] == value)
                {
                    return true;
                }

            else if (values[mid] > value) //value's on the left of mid
                {
                    min = 0;
                    max = mid - 1;
                    return true;
                }

            else if (values[mid] < value) //value's on the right of mid
                {
                    max = n-1;
                    min = mid + 1;
                    return true;
                }

            else
                {
                    return false;
                }

        }
    return false;
}
</code>```

I just modified the code to the following and got exactly the same result. Thought this might narrow down the problem.

```<code>bool search(int value, int values[], int n)
{
int min = 0;
int max = n-1;
int mid = (max + min) / 2;

if(n <= 0)
{
    return false;
}

if (values[max] >= values[min])
{
    if (values[mid] == value)
    {
        return true;
    }

    else if (values[mid] > value) //value's on the left of mid
    {
        min = 0;
        max = mid - 1;
        return true;
    }

    else if (values[mid] < value) //value's on the right of mid
    {
        max = n-1;
        min = mid + 1;
        return true;
    }

    else
    {
        return false;
    }

}
else
{
    return 1;
}
}
</code>```

答:
With your help I've finally got a winner. It seems I needed to remove the array name from the 'while' statement (values[]); and I also had to reference "int mid = (min + max)/2" inside each 'if/if else' statement.  Thanks everyone. Phew!</p>

```<code>bool search(int value, int values[], int n) //values = the array
{
    int min = 0;
    int max = n - 1;

    while (min <= max)
    {
        int mid = (min + max) / 2;

        if (values[mid] == value)
        {
            return true;
        }

        else if (value < values[mid]) //value's on the left of mid
        {
            max = mid - 1;
        }

        else if (value > values[mid]) //value's on the right of mid
        {
           min = mid + 1;
        }
    }
    return false;
}
</code>```

Body:
This C Binary search function is finding what it's supposed to but I'm getting the error: "\ expected an exit code of 1, not 0 " if the integer it's looking for is not in the array.  I have tried removing false at the end or removing the else statement but this doesn't work. Can anyone see why?

bool search(int value, int values[], int n)
{
    int min = 0;
    int max = n-1;
    int mid = (max + min) / 2;

    if(n <= 0)
        {
            return false;
        }

    while (values[max] >= values[min])
        {
            if (values[mid] == value)
                {
                    return true;
                }

            else if (values[mid] > value) //value's on the left of mid
                {
                    min = 0;
                    max = mid - 1;
                    return true;
                }

            else if (values[mid] < value) //value's on the right of mid
                {
                    max = n-1;
                    min = mid + 1;
                    return true;
                }

            else
                {
                    return false;
                }

        }
    return false;
}

I just modified the code to the following and got exactly the same result. Thought this might narrow down the problem.

bool search(int value, int values[], int n)
{
int min = 0;
int max = n-1;
int mid = (max + min) / 2;

if(n <= 0)
{
    return false;
}

if (values[max] >= values[min])
{
    if (values[mid] == value)
    {
        return true;
    }

    else if (values[mid] > value) //value's on the left of mid
    {
        min = 0;
        max = mid - 1;
        return true;
    }

    else if (values[mid] < value) //value's on the right of mid
    {
        max = n-1;
        min = mid + 1;
        return true;
    }

    else
    {
        return false;
    }

}
else
{
    return 1;
}
}

Body:
With your help I've finally got a winner. It seems I needed to remove the array name from the 'while' statement (values[]); and I also had to reference "int mid = (min + max)/2" inside each 'if/if else' statement.  Thanks everyone. Phew!

bool search(int value, int values[], int n) //values = the array
{
    int min = 0;
    int max = n - 1;

    while (min <= max)
    {
        int mid = (min + max) / 2;

        if (values[mid] == value)
        {
            return true;
        }

        else if (value < values[mid]) //value's on the left of mid
        {
            max = mid - 1;
        }

        else if (value > values[mid]) //value's on the right of mid
        {
           min = mid + 1;
        }
    }
    return false;
}


问:
get youtube video id from video list
i m about to make youtube video downloader app but don't get to integrate youtube video list so below is testing code to get started with

```<code> webView = (WebView) findViewById(R.id.webview);
    webView.setWebViewClient(new WebViewClient());
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.loadUrl("http://www.youtube.com");
</code>```

above code simply load youtube site to a webview .. now i want to get id or link  of clicked video

or

is there any other way to do so?

答:
Read link from webview loading and parse the link </p>

```<code>webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                //Parse Link
            }

            @Override
            public void onPageFinished(WebView view, String url) {
               //Parse Link
                super.onPageFinished(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onLoadResource(view, url);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //Parse Link

                return super.shouldOverrideUrlLoading(view, url);
            }
        });
</code>```

Title: get youtube video id from video list

Body:
i m about to make youtube video downloader app but don't get to integrate youtube video list so below is testing code to get started with

 webView = (WebView) findViewById(R.id.webview);
    webView.setWebViewClient(new WebViewClient());
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.loadUrl("http://www.youtube.com");

above code simply load youtube site to a webview .. now i want to get id or link  of clicked video

or

is there any other way to do so?

Body:
Read link from webview loading and parse the link

webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                //Parse Link
            }

            @Override
            public void onPageFinished(WebView view, String url) {
               //Parse Link
                super.onPageFinished(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onLoadResource(view, url);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //Parse Link

                return super.shouldOverrideUrlLoading(view, url);
            }
        });


问:
How to place pseudo-elements behind the parent node?
http://codepen.io/pen/YZdpgb

The pseudo-element after is on front of the div .rotate.
It seems that the z-index: -1 is not working

HTML

```<code><div class="box--container">
  <div class="box--rotate">
    <div class="box">
      <p>my background should be the light grey :(</p>
    </div>
  </div>
</div>
</code>```

CSS

```<code>body {
  height: 80vh;
  margin: 10vh 10vw;
}
.box--container {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  text-align: center;
}

.box--rotate {
  position: relative;
  width: 250px;
  height: 250px;
  transform: rotate(45deg);
  transform-origin: 100% 150%;
  background: #ccc;
  z-index: 1;
  &::after {
    position: absolute;
    content: '';
    width: 100%;
    height: 100%;
    background: #F2C398;
    top: 15px;
    left: 15px;
    z-index: -1;
  }
}

.box {
  position: relative;
  top: 50%;
  transform: rotate(-45deg) translateY(-50%);
  z-index: 10;
}
</code>```

答: try this one it's helpful https://jsfiddle.net/x061nock/ <code>::after</code> use default color  </p>

Body:
http://codepen.io/pen/YZdpgb

The pseudo-element after is on front of the div .rotate.
It seems that the z-index: -1 is not working

HTML

my background should be the light grey :(

CSS

body {
  height: 80vh;
  margin: 10vh 10vw;
}
.box--container {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  text-align: center;
}

.box--rotate {
  position: relative;
  width: 250px;
  height: 250px;
  transform: rotate(45deg);
  transform-origin: 100% 150%;
  background: #ccc;
  z-index: 1;
  &::after {
    position: absolute;
    content: '';
    width: 100%;
    height: 100%;
    background: #F2C398;
    top: 15px;
    left: 15px;
    z-index: -1;
  }
}

.box {
  position: relative;
  top: 50%;
  transform: rotate(-45deg) translateY(-50%);
  z-index: 10;
}

Body: try this one it's helpful https://jsfiddle.net/x061nock/ ::after use default color


问:
Define Model Parameter as Variable
I am attempting to define the parameter of a model (block) as a variable. For example:

```<code>Real WallThickness = 0.5;
Real WallConductance = 10*WallThickness;
Modelica.Thermal.HeatTransfer.Components.ThermalConductor TopPanelConductor(G=WallConductance);
</code>```

I would like to define "G" so that it remains constant throughout the simulation but the coefficient is updated prior to the simulation based on the other variable "WallThickness". When defining the ThermalConductor parameter "G" as a variable in the model, which is being calculated elsewhere, I get the error message:

```<code>The variability of the definition equation:
TopPanelConductor.G = WallConductance;
is higher than the declared variability of the variables.
</code>```

I would like to define the parameters of a model as a variable. This allows me to create parametric definitions as the geometry of the all changes. Is there a way I can make this definition work?

答:
You mean the geometry changes during simulation? If so, you'll have to rewrite the ThermalConductor model to work with a variable G, because a variable  cannot be assigned to a parameter. A variable may vary during the course of simulation. A parameter is fixed at the start of simulation, but can be changed from run to run without recompiling the model, which allows for quicker iteration/design work.

Note that you can also calculate a parameter from other parameters that you define, e.g. to calculate a heat transfer coefficient from a given wall thickness (which you vary from simulation run to simulation run).

Title: Define Model Parameter as Variable

Body:
I am attempting to define the parameter of a model (block) as a variable. For example:

Real WallThickness = 0.5;
Real WallConductance = 10*WallThickness;
Modelica.Thermal.HeatTransfer.Components.ThermalConductor TopPanelConductor(G=WallConductance);

I would like to define "G" so that it remains constant throughout the simulation but the coefficient is updated prior to the simulation based on the other variable "WallThickness". When defining the ThermalConductor parameter "G" as a variable in the model, which is being calculated elsewhere, I get the error message:

The variability of the definition equation:
TopPanelConductor.G = WallConductance;
is higher than the declared variability of the variables.

I would like to define the parameters of a model as a variable. This allows me to create parametric definitions as the geometry of the all changes. Is there a way I can make this definition work?


问:
How do I access textField Value, which is created dynamically in Objective C using for loop?
I have created 4 UITextField using for loop in Objective C. Now I want to validate those text. whether those text field is empty or not.

```<code> for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}
</code>```

答:
If you want to check if your UITextField is empty, define a macro for trimming the whitespaces.

```<code>#define TRIM(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
</code>```

In your button action method.

```<code>UITextField *textField1 = [self.view viewWithTag:0];
UITextField *textField2 = [self.view viewWithTag:1];
UITextField *textField3 = [self.view viewWithTag:2];
UITextField *textField4 = [self.view viewWithTag:3];

if(![TRIM(textField1.text) length])
{
   // Your textfield is empty
}
//Similarly check for other textfields
</code>```

Body:
I have created 4 UITextField using for loop in Objective C. Now I want to validate those text. whether those text field is empty or not.

 for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}

Body:
If you want to check if your UITextField is empty, define a macro for trimming the whitespaces.

#define TRIM(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

In your button action method.

UITextField *textField1 = [self.view viewWithTag:0];
UITextField *textField2 = [self.view viewWithTag:1];
UITextField *textField3 = [self.view viewWithTag:2];
UITextField *textField4 = [self.view viewWithTag:3];

if(![TRIM(textField1.text) length])
{
   // Your textfield is empty
}
//Similarly check for other textfields


问:
Cordova - Android SDK not found
I saw a lot of thread in here related to this, but any of them helped me.

With Cordova 6.5.0 installed and Android Studio also installed with Android 6.0 (API 23) and Android 4.4 (API 19), I'm trying to run:

```<code>cordova requirements
</code>```

I got the following error:

```<code>Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
</code>```

Ok. I set up the ANDROID_HOME and the PATH:

```<code>export ANDROID_HOME=/Users/USER/Library/Android/sdk
export PATH=${PATH}:/Users/USER/Library/Android/sdk/platform-tools:/Users/italoborges/Library/Android/sdk/tools
</code>```

I also changed inside platforms/project.properties the line:

```<code>target=android-23
</code>```

And inside platforms/android/AndroidManifest.xml the line:

```<code><uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
</code>```

And inside platforms/android/CordovaLib/AndroidManifest.xml the same line above.

Right now I'm stuck because I have tried all the possibilities that I found.

Thanks.

答:
Cause the cordova updated, you may skip this answer and see others.

The reason is not only The recent Android SDK tools removed the android command, but also the file structure of the SDK ,installed by android studio ,has been changed.
You can wait for the fix, or do a temporary fix by you self.

1,Delete all contents of ~/Library/Android/sdk

2,Download https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip ,and unzip it to ~/Library/Android/sdk/tools

3,Open sdk manager in command line (~/Library/Android/sdk/tools/android sdk),and install the SDKs.You may need to install 5.5.1(API22) and 6.0(API23)

That's all.

Title: Cordova - Android SDK not found

Body:
I saw a lot of thread in here related to this, but any of them helped me.

With Cordova 6.5.0 installed and Android Studio also installed with Android 6.0 (API 23) and Android 4.4 (API 19), I'm trying to run:

cordova requirements

I got the following error:

Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.

Ok. I set up the ANDROID_HOME and the PATH:

export ANDROID_HOME=/Users/USER/Library/Android/sdk
export PATH=${PATH}:/Users/USER/Library/Android/sdk/platform-tools:/Users/italoborges/Library/Android/sdk/tools

I also changed inside platforms/project.properties the line:

target=android-23

And inside platforms/android/AndroidManifest.xml the line:

<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />

And inside platforms/android/CordovaLib/AndroidManifest.xml the same line above.

Right now I'm stuck because I have tried all the possibilities that I found.

Thanks.


问:
Convert string to int[,]
I have weird requirement in matrix clustering.

My inputs are like

```<code>string param = "1100,1110,0110,0001";
</code>```

and what I want is

```<code> var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };
</code>```

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

```<code>string[] resultantArray = param.Split(',').ToArray();
</code>```

And then I tried to convert my string[] to int[], using below code.

```<code>var intArray = resultantArray .Select(int.Parse).ToArray();
</code>```

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

答:
Can you try this.</p>

```<code>        string param = "1100,10110,0110,0001";   //"1100,1110,0110,0001";

        string[] allStrings = param.Split(',');
        var m = allStrings.Count();

        System.Collections.Generic.List<char[]> listOfCharArr = new System.Collections.Generic.List<char[]>();
        System.Collections.Generic.List<int> lengthList = new System.Collections.Generic.List<int>();
        for(int i = 0; i<m ; i++)
        {
            string str = allStrings[i];
            char[] allChars = str.ToCharArray();
            listOfCharArr.Add(allChars);
            lengthList.Add(allChars.Count());
        }
        int maxLength = lengthList.Max();

        int[,] matrix = new int[m, maxLength] ;

        for(int i = 0; i<m ; i++)
        {
            for (int j = 0; j < maxLength; j++)
            {
                char[] temp = listOfCharArr[i];
                if (j < listOfCharArr[i].Count())
                    matrix[i, j] = Convert.ToInt32(listOfCharArr[i][j].ToString()); // you can use int.tryparse if not sure that input will always be integer
                else
                    matrix[i, j] = -1; // I have used -1 as no value, you can use whatever you require
            }
        }
</code>```

Title: Convert string to int[,]

Body:
I have weird requirement in matrix clustering.

My inputs are like

string param = "1100,1110,0110,0001";

and what I want is

 var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

string[] resultantArray = param.Split(',').ToArray();

And then I tried to convert my string[] to int[], using below code.

var intArray = resultantArray .Select(int.Parse).ToArray();

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

Body:
Can you try this.

        string param = "1100,10110,0110,0001";   //"1100,1110,0110,0001";

        string[] allStrings = param.Split(',');
        var m = allStrings.Count();

        System.Collections.Generic.List<char[]> listOfCharArr = new System.Collections.Generic.List<char[]>();
        System.Collections.Generic.List<int> lengthList = new System.Collections.Generic.List<int>();
        for(int i = 0; i<m ; i++)
        {
            string str = allStrings[i];
            char[] allChars = str.ToCharArray();
            listOfCharArr.Add(allChars);
            lengthList.Add(allChars.Count());
        }
        int maxLength = lengthList.Max();

        int[,] matrix = new int[m, maxLength] ;

        for(int i = 0; i<m ; i++)
        {
            for (int j = 0; j < maxLength; j++)
            {
                char[] temp = listOfCharArr[i];
                if (j < listOfCharArr[i].Count())
                    matrix[i, j] = Convert.ToInt32(listOfCharArr[i][j].ToString()); // you can use int.tryparse if not sure that input will always be integer
                else
                    matrix[i, j] = -1; // I have used -1 as no value, you can use whatever you require
            }
        }


问:
Extract specific text out of bash variable containing TSV string
I have the following TSV and newlines string assigned to a variable in bash:

```<code>TAGS    Product3    qwerty  text    Desc3
TAGS    Product1    qwerty  text    Desc1
TAGS    Product2    qwerty  text    Desc2
</code>```

I would like to extract the last column to a new string, and it has to be product ordered by my product input, for example:

Product1,Product2,Product3 will have to output: Desc1,Desc2,Desc3

What would be the best approach to accomplish this?

答:
```<code>echo "$var" | sort -k2 tags | cut -f5 | paste -sd,
</code>```

Body:
I have the following TSV and newlines string assigned to a variable in bash:

TAGS    Product3    qwerty  text    Desc3
TAGS    Product1    qwerty  text    Desc1
TAGS    Product2    qwerty  text    Desc2

I would like to extract the last column to a new string, and it has to be product ordered by my product input, for example:

Product1,Product2,Product3 will have to output: Desc1,Desc2,Desc3

What would be the best approach to accomplish this?


问:
Code Golf: Gray Code

The Challenge

The shortest program by character count that outputs the n-bit Gray Code. n will be an arbitrary number smaller than <s>1000</s>100000 (due to user suggestions) that is taken from standard input. The gray code will be printed in standard output, like in the example.

Note: I don't expect the program to print the gray code in a reasonable time (n=100000 is overkill); I do expect it to start printing though.

Example

Input:

```<code>4
</code>```

Expected Output:

```<code>0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
</code>```

答:
In cut-free Prolog (138 bytes if you remove the space after '<<'; submission editor truncates the last line without it):</p>

```<code>b(N,D):-D=0->nl;Q is D-1,H is N>>Q/\1,write(H),b(N,Q).

c(N,D):-N=0;P is N xor(N//2),b(P,D),M is N-1,c(M,D).

:-read(N),X is 1<< N-1,c(X,N).
</code>```

Title: Code Golf: Gray Code

Body:
The Challenge

The shortest program by character count that outputs the n-bit Gray Code. n will be an arbitrary number smaller than <s>1000</s>100000 (due to user suggestions) that is taken from standard input. The gray code will be printed in standard output, like in the example.

Note: I don't expect the program to print the gray code in a reasonable time (n=100000 is overkill); I do expect it to start printing though.

Example

Input:

4

Expected Output:

0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000

LastEditorDisplayName: Roger Pate

Body:
In cut-free Prolog (138 bytes if you remove the space after '<<'; submission editor truncates the last line without it):

b(N,D):-D=0->nl;Q is D-1,H is N>>Q/\1,write(H),b(N,Q).

c(N,D):-N=0;P is N xor(N//2),b(P,D),M is N-1,c(M,D).

:-read(N),X is 1<< N-1,c(X,N).


问:
How to Change Oracle Encoding to AL32UTF8 in SQLPlus in Windows
Iused the following command to test my Oracle current encoding

```<code>select userenv('language') from dual;
select * from v$nls_parameters where parameter='NLS_CHARACTERSET';
select * from nls_database_parameters
select * from nls_instance_parameters
select * from nls_session_parameters
</code>```

But what I want is AL32UTF8. How to change the encoding to AL32UTF8. Thanks~

答:
There are two ways to set it.

As Environment Variable NLS_LANG. Either temporarily with

SET NLS_LANG=AMERICAN_AMERICA.AL32UTF8 or in your Computer Property settings.

In your Registry at HKLM\SOFTWARE\ORACLE\KEY_%ORACLE_HOME_NAME%\NLS_LANG, resp. HKLM\SOFTWARE\Wow6432Node\ORACLE\KEY_%ORACLE_HOME_NAME%\NLS_LANG for an 32-bit Oracle Client on Windows 64-bit.

In case you set both the Environment variable takes precedence.

Please note, when you set NLS_LANG value then you just tell the Oracle database "my client uses character set AL32UTF8" - it does not necessarily mean that your client is really using AL32UTF8!

In case of SQL*Plus it inherits the character set from cmd.exe codepage. You can interrogate and change it with command chcp, e.g.

```<code>C:\>chcp
Active code page: 850

C:\>chcp 65001
Active code page: 65001

C:\>sqlplus ...
</code>```

See Code Page Identifiers to get a list of code pages.

However, according to your screenshot you use Java based SQL Developer. SQL Developer does not depend on NLS_LANG setting. Check value in Tools -> Preferences -> Environment -> Encoding.

Body:
Iused the following command to test my Oracle current encoding

select userenv('language') from dual;
select * from v$nls_parameters where parameter='NLS_CHARACTERSET';
select * from nls_database_parameters
select * from nls_instance_parameters
select * from nls_session_parameters

But what I want is AL32UTF8. How to change the encoding to AL32UTF8. Thanks~

Body:
There are two ways to set it.

As Environment Variable NLS_LANG. Either temporarily with

SET NLS_LANG=AMERICAN_AMERICA.AL32UTF8 or in your Computer Property settings.

In your Registry at HKLM\SOFTWARE\ORACLE\KEY_%ORACLE_HOME_NAME%\NLS_LANG, resp. HKLM\SOFTWARE\Wow6432Node\ORACLE\KEY_%ORACLE_HOME_NAME%\NLS_LANG for an 32-bit Oracle Client on Windows 64-bit.

In case you set both the Environment variable takes precedence.

Please note, when you set NLS_LANG value then you just tell the Oracle database "my client uses character set AL32UTF8" - it does not necessarily mean that your client is really using AL32UTF8!

In case of SQL*Plus it inherits the character set from cmd.exe codepage. You can interrogate and change it with command chcp, e.g.

C:\>chcp
Active code page: 850

C:\>chcp 65001
Active code page: 65001

C:\>sqlplus ...

See Code Page Identifiers to get a list of code pages.

However, according to your screenshot you use Java based SQL Developer. SQL Developer does not depend on NLS_LANG setting. Check value in Tools -> Preferences -> Environment -> Encoding.


问:
How can i use a thousand separator in SQL Server?
```<code> SELECT count(id) FROM table a
</code>```

it gives me a number lets say 36136, how can i make thousand separator on top?

答:
Use TOP statement in SQL server :</p>

```<code>SELECT TOP 1000 * FROM table a
</code>```

Body:
 SELECT count(id) FROM table a

it gives me a number lets say 36136, how can i make thousand separator on top?

Body:
Use TOP statement in SQL server :

SELECT TOP 1000 * FROM table a


问:
Yii2 orderBy specific values
Here's my controller

```<code>public function actionIndex()
{
    $query = users::find();
    $count = count($users);
    $pagination = new Pagination(['totalCount' => $count, 'pageSize'=>20]);
    $models = $query->offset($pagination->offset)
    ->limit($pagination->limit)
    ->orderBy([new \yii\db\Expression('FIELD (mission, Leader, Right Hand, QA, Member)')])
    ->all();
    return $this->render('index', [
        'models' => $models,
        'pagination' => $pagination,
    ]);
 }
</code>```

But it not working. I keep getting this error

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Hand, QA, Member) LIMIT 16 OFFSET 16' at line 1
  The SQL being executed was: SELECT * FROM users ORDER BY FIELD (mission, Leader, Right Hand, QA, Member) LIMIT 16 OFFSET 16

Please help me with this. Thank you.

答:
if you need  order by FIELD(column, string....) you should use  quote around values </p>

```<code>->orderBy([new \yii\db\Expression("FIELD (mission, 'Leader', 'Right Hand', 'QA', 'Member')")])
</code>```

Title: Yii2 orderBy specific values

Body:
Here's my controller

public function actionIndex()
{
    $query = users::find();
    $count = count($users);
    $pagination = new Pagination(['totalCount' => $count, 'pageSize'=>20]);
    $models = $query->offset($pagination->offset)
    ->limit($pagination->limit)
    ->orderBy([new \yii\db\Expression('FIELD (mission, Leader, Right Hand, QA, Member)')])
    ->all();
    return $this->render('index', [
        'models' => $models,
        'pagination' => $pagination,
    ]);
 }

But it not working. I keep getting this error

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Hand, QA, Member) LIMIT 16 OFFSET 16' at line 1
  The SQL being executed was: SELECT * FROM users ORDER BY FIELD (mission, Leader, Right Hand, QA, Member) LIMIT 16 OFFSET 16

Please help me with this. Thank you.

Body:
if you need  order by FIELD(column, string....) you should use  quote around values

->orderBy([new \yii\db\Expression("FIELD (mission, 'Leader', 'Right Hand', 'QA', 'Member')")])


问:
C - fseek() affecting the contents(structure) of a file when trying to update the records
Not sure what is wrong the fseek() in this function as I am lead to believe that it is the cause for the problems with the incorrect output for my program.

```<code>   index = 0;
    present = 0;
    while(fread(&beverage, sizeof(struct beverages), 1, filepointer))
    {
        if(newFile == 0)
            break;

        printf("%s\n\n", beverage.bcode);
        getch();

        if(strcmp(_bev_name, beverage.bname) == 0)
        {
            printf("Inside if statement\n\n");
            getch();

            beverage.quantity = beverage.quantity + qty;
            beverage.qty_last_purchase = qty;

            priceOne = spent/qty;//Used to calculate the cost price for one beverage
            beverage.price = priceOne + (priceOne*0.10);//Calculation of sale price for beverage

            printf("%d\n\n", index);
            getch();

            fseek(filepointer,index*sizeof(struct beverages),SEEK_SET);
            fwrite(&beverage,sizeof(struct beverages),1,filepointer);

            present = 1;
            break;
        }
        else
        {
            present = 0;
            index = index + 1;
        }

    }

    if(present == 0)
    {
        //Stores new beverage name
        strcpy(beverage.bname, _bev_name);

        //Creation of beverage code using the first two letters of beverage name and random 3 digit number
        srand(time(NULL));
        int ran_num = rand()%(999 + 1 - 100) + 100;
        char str[3];

        itoa(ran_num, str,10);

        beverage.bcode[0] = beverage.bname[0];
        beverage.bcode[1] = beverage.bname[1];
        beverage.bcode[2] = str[0];
        beverage.bcode[3] = str[1];
        beverage.bcode[4] = str[2];
        beverage.bcode[5] = '\0';

        beverage.qty_last_purchase = qty;
        beverage.quantity = qty;
        priceOne = spent/qty;//Used to calculate the cost price for one beverage
        beverage.price = priceOne + (priceOne*0.10);//Calculation of sale price for beverage

        fwrite(&beverage, sizeof(struct beverages), 1, filepointer);

    }
</code>```

The first part of the code loops through an existing file to find the matching beverage code and then to update the quantity and price of the beverage but what has been happening is that it is affecting the other structures in the file.

Shows how beverages are displayed when they are first added to file

Shows how the list of beverages are affected after the records are updated

To be noted I chose to update the first beverage in the first picture but as you can see it affects the second beverage record.

EDIT : The definition of the struct beverages

```<code>struct beverages
{
    char bname[NAME_LIMIT];
    char bcode[MAX_SIZE];
    int quantity;
    int qty_last_purchase;
    float price;
} beverage;
</code>```

答:
Although you don't show the most important part of your code: the definition of struct beverages, I strongly believe you are barking up the wrong tree and your problems have nothing to do at all with fseek().

It appears struct beverages doesn't store the beverage's name literal characters in beverage.bname, but a pointer to them instead.

Thus, you most likely save and retrieve pointers instead of values. These pointers point to meaningless data once restored. Either store all of your data inside of your data records or make yourself familiar with the concepts of serialization and deserialization.

Body:
Not sure what is wrong the fseek() in this function as I am lead to believe that it is the cause for the problems with the incorrect output for my program.

   index = 0;
    present = 0;
    while(fread(&beverage, sizeof(struct beverages), 1, filepointer))
    {
        if(newFile == 0)
            break;

        printf("%s\n\n", beverage.bcode);
        getch();

        if(strcmp(_bev_name, beverage.bname) == 0)
        {
            printf("Inside if statement\n\n");
            getch();

            beverage.quantity = beverage.quantity + qty;
            beverage.qty_last_purchase = qty;

            priceOne = spent/qty;//Used to calculate the cost price for one beverage
            beverage.price = priceOne + (priceOne*0.10);//Calculation of sale price for beverage

            printf("%d\n\n", index);
            getch();

            fseek(filepointer,index*sizeof(struct beverages),SEEK_SET);
            fwrite(&beverage,sizeof(struct beverages),1,filepointer);

            present = 1;
            break;
        }
        else
        {
            present = 0;
            index = index + 1;
        }

    }

    if(present == 0)
    {
        //Stores new beverage name
        strcpy(beverage.bname, _bev_name);

        //Creation of beverage code using the first two letters of beverage name and random 3 digit number
        srand(time(NULL));
        int ran_num = rand()%(999 + 1 - 100) + 100;
        char str[3];

        itoa(ran_num, str,10);

        beverage.bcode[0] = beverage.bname[0];
        beverage.bcode[1] = beverage.bname[1];
        beverage.bcode[2] = str[0];
        beverage.bcode[3] = str[1];
        beverage.bcode[4] = str[2];
        beverage.bcode[5] = '\0';

        beverage.qty_last_purchase = qty;
        beverage.quantity = qty;
        priceOne = spent/qty;//Used to calculate the cost price for one beverage
        beverage.price = priceOne + (priceOne*0.10);//Calculation of sale price for beverage

        fwrite(&beverage, sizeof(struct beverages), 1, filepointer);

    }

The first part of the code loops through an existing file to find the matching beverage code and then to update the quantity and price of the beverage but what has been happening is that it is affecting the other structures in the file.

Shows how beverages are displayed when they are first added to file

Shows how the list of beverages are affected after the records are updated

To be noted I chose to update the first beverage in the first picture but as you can see it affects the second beverage record.

EDIT : The definition of the struct beverages

struct beverages
{
    char bname[NAME_LIMIT];
    char bcode[MAX_SIZE];
    int quantity;
    int qty_last_purchase;
    float price;
} beverage;


问:
Is there any benefit to using getters/setters inside a class for its own fields?
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

答:
Some people think that they should always encapsulate all fields by using setters/getters.
Others think that this practice should not be used at all.

If your class does not have any logic for the fields and just is used as a holder, you can skip using methods and just declare your fields as public. This concept is also called a Data Transfer Object (or Messenger.) But as a rule you should use final attribute for such fields to make your class immutable:

```<code>public class TwoTuple<A,B> {
  public final A first;
  public final B second;
  public TwoTuple(A a, B b) { first = a; second = b; }
}
</code>```

However you must/or it's strongly recommended to use setters/getters:

in web applications sometimes there are requirements to use setters/getters. See POJO/JavaBean objects.

if your class is going to be used in concurrent environment. See Java Concurrency in Practice, Section 3.2:
"Whether another thread actually does something with a published reference doesn't really matter, because the risk of misuse is still present.[7] Once an object escapes, you have to assume that another class or thread may, maliciously or carelessly, misuse it. This is a compelling reason to use encapsulation: it makes it practical to analyze programs for correctness and harder to violate design constraints accidentally"

if you want to add some extra logic when you set/get values you must use setters/getters. Just read about encapsulation and its advantages.

My own opinion always declare fields as "private final" and only then, if needed change these properties.

Body:
Some people think that they should always encapsulate all fields by using setters/getters.
Others think that this practice should not be used at all.

If your class does not have any logic for the fields and just is used as a holder, you can skip using methods and just declare your fields as public. This concept is also called a Data Transfer Object (or Messenger.) But as a rule you should use final attribute for such fields to make your class immutable:

public class TwoTuple<A,B> {
  public final A first;
  public final B second;
  public TwoTuple(A a, B b) { first = a; second = b; }
}

However you must/or it's strongly recommended to use setters/getters:

in web applications sometimes there are requirements to use setters/getters. See POJO/JavaBean objects.

if your class is going to be used in concurrent environment. See Java Concurrency in Practice, Section 3.2:
"Whether another thread actually does something with a published reference doesn't really matter, because the risk of misuse is still present.[7] Once an object escapes, you have to assume that another class or thread may, maliciously or carelessly, misuse it. This is a compelling reason to use encapsulation: it makes it practical to analyze programs for correctness and harder to violate design constraints accidentally"

if you want to add some extra logic when you set/get values you must use setters/getters. Just read about encapsulation and its advantages.

My own opinion always declare fields as "private final" and only then, if needed change these properties.