答:
```<code> SELECT *
 FROM Trips
 INNER JOIN Users ON [Trips].Id = [Users].User_Id AND [Users].Role = 'client' AND [Users].Banned = 'No'
</code>```

Body:
table (Trips)

| Id | Client_Id | Driver_Id | City_Id |     Status      |Request_at|

| 1  |     1     |    10     |    1    |     completed      |2013-10-01|

| 2  |     2     |    10     |    1    |     completed      |2013-10-02|

| 3  |     3     |    11     |    6    |     completed      |2013-10-03|

table ( users)

Users_Id    | Banned |  Role  |

|    1     |   No   | client |

|    2     |   Yes  | client |

|    3     |   No   | client |

|    4     |   No      | driver|

How can I join these 2 tables (trips, users) on the condition that the user role needs to be client and these clients should be unbanned.
I am trying to use a subquery but I got "single-row subquery returns more than one row"error and not sure what went wrong.

SELECT * FROM Trips
INNER JOIN users
ON client_id = (SELECT users_id from users
                  where
                  role = 'Client' and  banned = 'No');


来源: stackexchange

问:
What is the path to the JRE file?
I am looking for the path the the JRE file on Mac OS X 10.6.8.
Or is there no such file?
Is JRE just slang for an idea or concept?
Java Runtime Environment is a real thing.

Does it have a file?
I am installing something that asks for the path to the JRE file
http://www.boonex.com/trac/dolphin/wiki/RayMediaServerInstallation

答:
After installing the latest JRE8 (as of today update 131), do the following :

In your .bash_profile add the following

```<code>export JAVA_HOME='/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home'
</code>```

Then add that to your path export PATH=$PATH:$JAVA_HOME. Save and open a new terminal. Type java -version. You should see output like this:

```<code>->java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
</code>```

ContentLicense: CC BY-SA 3.0

Title: What is the path to the JRE file?

Body:
After installing the latest JRE8 (as of today update 131), do the following :

In your .bash_profile add the following

export JAVA_HOME='/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home'

Then add that to your path export PATH=$PATH:$JAVA_HOME. Save and open a new terminal. Type java -version. You should see output like this:

->java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)


问:
How to create mongoDB user using Powershell?
I am trying to write a script that creates a user in the admin database of a mongoDB 3.0 replica set.

After much reading and many tries using different versions of the c-sharp MongoDB drivers, I was finally able to put together the following code, which is able to log successfully into the replica set, access the admin database, writing out the full name of the system collection:

```<code>try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.Core.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Bson.dll'

    $connectionString = "mongodb://username:password@primary:27017,secondary:27017,arbiter:27017/admin?replicaSet=name&authSource=admin"
    $dbName =  "admin"
    $collectionName =  "System"

    function Get-MongoDBDatabase ($connectionString, $db) {
        $mongoClient = New-Object MongoDB.Driver.MongoClient($connectionString)
        $mongoServer = $mongoClient.GetServer()
        $mongoServer.GetDatabase($db)
    }

    [MongoDB.Driver.MongoDatabase] $mongoDatabase = Get-MongoDBDatabase $connectionString $dbName
    [MongoDB.Driver.MongoCollection] $mongoCollection = $mongoDatabase.GetCollection($collectionName)

    Write-Output "Test accessing collection: $($mongoCollection.FullName)"
}
catch {
    Write-Output "Error: $($_.Exception.Message)"
}
</code>```

At this point I have no clue in which direction to move to create a new user in the admin database and assign this user some roles.

```<code>db.createUser(
   {
     user: "testUser",
     pwd: "abc123",
     roles: [
        {role:"read", db:"admin"},
        {role:"readWrite", db:"databaseOne"},
        {role:"readWrite", db:"databaseTwo"},
        {role:"readWrite", db:"databaseThree"},
        {role:"readWrite", db:"databaseFour"},
        {role:"read", db:"config"}]
   }
)
</code>```

Above is the command/query that I would like to be able to execute on the admin database, but I need your help to understand how to translate this into Powershell using the MongoDB C-Sharp Driver v.2.0.2

答:
Ok, I found a way to make this work, alas not entirely in Powershell.

Following @PeteGarafano suggestion I decided to use the latest and greatest driver (version 2.4.3.23, downloaded via NuGet) in a simple Visual Studio class library.

Since this is just a test at the moment the code is very crude and full of hard-coded things (for example the roles to be assigned to the user)

Here is the code of the class library:

```<code>using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBUtilities
{
    public class Connectivity
    {
        public bool DoesUserExist(string connectionString, string databaseName, string username)
        {
            try
            {
                var command = @" { usersInfo: { user: '" + username + @"', db: 'admin' } } ";

                var result = runCommand(connectionString, databaseName, command);
                var users = result["users"];
                if(users != null)
                {
                    var usersArray = users.AsBsonArray;
                    if(usersArray.Count > 0) {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public string CreateUser(string connectionString, string databaseName, string username, string password)
        {
            try
            {
                var command = @"{
                      createUser: '" + username + @"',
                      pwd: '" + password + @"',
                      roles: [
                          { role: 'read', db: 'admin'},
                          { role: 'read', db: 'someDB'},
                          { role: 'read', db: 'someOtherDB'}]
                    }";

                var result = runCommand(connectionString, databaseName, command);
                return result.ToJson().ToString();
            }
            catch (Exception ex) {
                return unfoldException(ex);
            }
        }

        private BsonDocument runCommand(string connectionString, string databaseName, string command)
        {
            var database = getDatabase(connectionString, databaseName);
            var task = database.RunCommandAsync<BsonDocument>(command);
            var result = task.Result;
            return result;
        }

        private IMongoDatabase getDatabase(string connectionString, string databaseName) {
            IMongoClient client;
            client = new MongoClient(connectionString);
            return client.GetDatabase(databaseName);
        }

        private string unfoldException(Exception ex) {
            string message = ex.Message + Environment.NewLine;
            Exception currentException = ex;
            while (currentException.InnerException != null)
            {
                currentException = currentException.InnerException;
                message += currentException.Message + Environment.NewLine;
            }
            return message;
        }
    }
}
</code>```

Nothing fancy, really, but the main point is how you can use the JSON form of any command as described in the MongoDB official reference documentation (for example: https://docs.mongodb.com/manual/reference/command/usersInfo/).

NOTE: There is another way to do this, building BsonDocument objects, but I found it less intuitive since the reference uses all JSON syntax.

Next, I used this library in my PS script. Here is an example:

```<code>try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB\MongoDBUtilities.dll'

    $connectionString = "mongodb://username:password@primaryServerName:27017,secondaryServerName:27017,arbiterServerName:27017/admin?replicaSet=replicaSetName&authSource=admin"
    $conn = New-Object -TypeName MongoDBUtilities.Connectivity
    if($conn.DoesUserExist($connectionString, "admin", "testUser")) {
        Write-Output "User already exists, no need to create again"
    }
    else {
        Write-Output "Creating user...";
        $result = $conn.CreateUser($connectionString, "admin", "testUser", "test")
        Write-Output $result;
    }
}
catch {
    Write-Output "Error: $($_.Exception.Message)"
}
</code>```

This example first checks if a user is already in the admin database and, if it is not already there, it creates it.

I hope this can be useful for anyone trying to do anything similar, either in C# or in Powershell.

Body:
I am trying to write a script that creates a user in the admin database of a mongoDB 3.0 replica set.

After much reading and many tries using different versions of the c-sharp MongoDB drivers, I was finally able to put together the following code, which is able to log successfully into the replica set, access the admin database, writing out the full name of the system collection:

try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.Core.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Bson.dll'

    $connectionString = "mongodb://username:password@primary:27017,secondary:27017,arbiter:27017/admin?replicaSet=name&authSource=admin"
    $dbName =  "admin"
    $collectionName =  "System"

    function Get-MongoDBDatabase ($connectionString, $db) {
        $mongoClient = New-Object MongoDB.Driver.MongoClient($connectionString)
        $mongoServer = $mongoClient.GetServer()
        $mongoServer.GetDatabase($db)
    }

    [MongoDB.Driver.MongoDatabase] $mongoDatabase = Get-MongoDBDatabase $connectionString $dbName
    [MongoDB.Driver.MongoCollection] $mongoCollection = $mongoDatabase.GetCollection($collectionName)

    Write-Output "Test accessing collection: $($mongoCollection.FullName)"
}
catch {
    Write-Output "Error: $($_.Exception.Message)"
}

At this point I have no clue in which direction to move to create a new user in the admin database and assign this user some roles.

db.createUser(
   {
     user: "testUser",
     pwd: "abc123",
     roles: [
        {role:"read", db:"admin"},
        {role:"readWrite", db:"databaseOne"},
        {role:"readWrite", db:"databaseTwo"},
        {role:"readWrite", db:"databaseThree"},
        {role:"readWrite", db:"databaseFour"},
        {role:"read", db:"config"}]
   }
)

Above is the command/query that I would like to be able to execute on the admin database, but I need your help to understand how to translate this into Powershell using the MongoDB C-Sharp Driver v.2.0.2

Body:
Ok, I found a way to make this work, alas not entirely in Powershell.

Following @PeteGarafano suggestion I decided to use the latest and greatest driver (version 2.4.3.23, downloaded via NuGet) in a simple Visual Studio class library.

Since this is just a test at the moment the code is very crude and full of hard-coded things (for example the roles to be assigned to the user)

Here is the code of the class library:

using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBUtilities
{
    public class Connectivity
    {
        public bool DoesUserExist(string connectionString, string databaseName, string username)
        {
            try
            {
                var command = @" { usersInfo: { user: '" + username + @"', db: 'admin' } } ";

                var result = runCommand(connectionString, databaseName, command);
                var users = result["users"];
                if(users != null)
                {
                    var usersArray = users.AsBsonArray;
                    if(usersArray.Count > 0) {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public string CreateUser(string connectionString, string databaseName, string username, string password)
        {
            try
            {
                var command = @"{
                      createUser: '" + username + @"',
                      pwd: '" + password + @"',
                      roles: [
                          { role: 'read', db: 'admin'},
                          { role: 'read', db: 'someDB'},
                          { role: 'read', db: 'someOtherDB'}]
                    }";

                var result = runCommand(connectionString, databaseName, command);
                return result.ToJson().ToString();
            }
            catch (Exception ex) {
                return unfoldException(ex);
            }
        }

        private BsonDocument runCommand(string connectionString, string databaseName, string command)
        {
            var database = getDatabase(connectionString, databaseName);
            var task = database.RunCommandAsync<BsonDocument>(command);
            var result = task.Result;
            return result;
        }

        private IMongoDatabase getDatabase(string connectionString, string databaseName) {
            IMongoClient client;
            client = new MongoClient(connectionString);
            return client.GetDatabase(databaseName);
        }

        private string unfoldException(Exception ex) {
            string message = ex.Message + Environment.NewLine;
            Exception currentException = ex;
            while (currentException.InnerException != null)
            {
                currentException = currentException.InnerException;
                message += currentException.Message + Environment.NewLine;
            }
            return message;
        }
    }
}

Nothing fancy, really, but the main point is how you can use the JSON form of any command as described in the MongoDB official reference documentation (for example: https://docs.mongodb.com/manual/reference/command/usersInfo/).

NOTE: There is another way to do this, building BsonDocument objects, but I found it less intuitive since the reference uses all JSON syntax.

Next, I used this library in my PS script. Here is an example:

try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB\MongoDBUtilities.dll'

    $connectionString = "mongodb://username:password@primaryServerName:27017,secondaryServerName:27017,arbiterServerName:27017/admin?replicaSet=replicaSetName&authSource=admin"
    $conn = New-Object -TypeName MongoDBUtilities.Connectivity
    if($conn.DoesUserExist($connectionString, "admin", "testUser")) {
        Write-Output "User already exists, no need to create again"
    }
    else {
        Write-Output "Creating user...";
        $result = $conn.CreateUser($connectionString, "admin", "testUser", "test")
        Write-Output $result;
    }
}
catch {
    Write-Output "Error: $($_.Exception.Message)"
}

This example first checks if a user is already in the admin database and, if it is not already there, it creates it.

I hope this can be useful for anyone trying to do anything similar, either in C# or in Powershell.


问:
When does Chrome autofill in a web page render?
I have a customer who wanted their UI to display field names in a form (username field says "username", password field says "password", etc.). Since the form uses a password type <input> (which normally displays dots), I had to mock filling data into the fields by overlaying them with divs that contained the verbiage.

To recognize autofill, I wrote some Javascript that checks to see if the field is filled and acts accordingly (either hiding or showing the verbiage).

As far as I can tell, Chrome is the only browser that goes wonky. It doesn't seem to care if there's autofill data or not, and the verbiage always overlays the autofill data (ostensibly because the hide functionality isn't being triggered).

My long-winded question is When does Chrome autofill data in the rendering process? Does it wait until Javascript has finished as well? Is there any way for me to check if autofill data is occupying a field in Chrome?

答: I decided to attach a listener to an event that activated the modal that contained the forms. Needless to say, this is a solution that would only work in my particular circumstances. I don't consider this an answer, but I'm posting it here to possibly give others looking for a solution a workaround.</p>

ContentLicense: CC BY-SA 2.5


问:
How to format cp command or ditto in terminal MAC OS X to copy source to multiple destinations
How to format cp command or ditto in terminal to copy source to multiple destinations? I am completely unexperienced in using terminal but have heard that is copies faster and I have large batched to send to multiple USB flash drives all titled NO NAME, NO NAME 1, NO NAME 2, etc etc</p>

答:
Did you try?</p>

```<code>cp -r source target1 target2 targetN
</code>```

Body:
Did you try?

cp -r source target1 target2 targetN


问:
How to run node.js ES6 file on mac
Can someone help me run a node.js file that has ES6 features? This is my current workflow:

Save change in file

npm run build --- builds file to my src/dist folder

cd into my dist directory

node

var file = require('./index.js')

file.someMethod()

Then when I make a change to my method, I need to repeat all the steps above again.

Does anyone know of a more efficient way to do this?

Thanks in advance!

答:
You dont need anything if you are not using import/export. Just Install node 8.x and then run node my_file.js. Nodejs supports most of the es6 features out of the box.

If you want to use import/export then I would recommend to use typescript: https://www.typescriptlang.org/. It has compiler TS (statically typed ES6) to ES5.

Oh, and of course both babel and typescript have watcher modules (auto recompiling on file change).

Title: How to run node.js ES6 file on mac


问:
Execute LLVM IR code generated from Python code
Does anyone know if I can execute LLVM IR which is generated from Python code?

Using numba, llvm-lite we can have LLVM IR, but I am not sure if it is executable using clang or not?

答:
You can compile it with clang, just make sure your IR have .bc or .ll extensions.

But the proper way is to use llc or LLVM API to compile down to native code, and then link it using system linker or LLD.

On linking stage you'd probably need to link some "runtime" libraries, numba ones in this case.


问:
Spring Boot: Inject Bean into HttpServlet
I've got a Spring Boot where I've autoconfigured a Router bean.
This all works perfect but it becomes a problem when I want to inject that bean into a custom servlet:

```<code>public class MembraneServlet extends HttpServlet {
    @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}
</code>```

This should be the way to go, but

```<code>SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
</code>```

won't autowire the Router because the WebapplicationContext is always null. The application is running in an MVC environment.

答:
Assuming you Spring Application Context is wired to the Servlet Context, you might want to pass ServletContext to SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext</p>

```<code>public class MembraneServlet extends HttpServlet {

  @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this, getServletContext());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}
</code>```

Body:
I've got a Spring Boot where I've autoconfigured a Router bean.
This all works perfect but it becomes a problem when I want to inject that bean into a custom servlet:

public class MembraneServlet extends HttpServlet {
    @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}

This should be the way to go, but

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

won't autowire the Router because the WebapplicationContext is always null. The application is running in an MVC environment.

Body:
Assuming you Spring Application Context is wired to the Servlet Context, you might want to pass ServletContext to SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext

public class MembraneServlet extends HttpServlet {

  @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this, getServletContext());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}


问:
Find lost rows after a pyspark DataFrame join
Given 2 spark DataFrames, csv_df and other_df, I need to join them and then figure out which rows from csv_df were lost in the join.

Here's what I've tried:

```<code>    csv_df = self.sqlContext.read.load('csv_table.parquet')
    csv_df = csv_df.withColumn(
        "mid", monotonically_increasing_id()
    )
    other_df = self.sqlContext.read.load('other_table.parquet')
    joined = csv_df.join(other_df, ['col1', 'col2'])
    found_rows = joined.select('mid').distinct()
    not_found_ids = csv_df.where(~csv_df.mid.isin(found_rows))
</code>```

This gives me the following error:

```<code>AttributeError: 'DataFrame' object has no attribute '_get_object_id'
</code>```

What am I doing wrong? How can I fix my code to get the non-joined rows?

答:
Although I would still like to know why my above-posted code doesn't work, I've realized that I can just do another join to answer my question:</p>

```<code>csv_df = self.sqlContext.read.load('csv_table.parquet')
csv_df = csv_df.withColumn(
    "mid", monotonically_increasing_id()
)
other_df = self.sqlContext.read.load('other_table.parquet')
joined = csv_df.join(other_df, ['col1', 'col2'])
found_rows = joined.select('mid').distinct()
not_found_rows = csv_df.selectExpr('mid').subtract(found_rows)
not_found_ids = csv_df.join(not_found_rows, 'mid')
</code>```

Body:
Given 2 spark DataFrames, csv_df and other_df, I need to join them and then figure out which rows from csv_df were lost in the join.

Here's what I've tried:

    csv_df = self.sqlContext.read.load('csv_table.parquet')
    csv_df = csv_df.withColumn(
        "mid", monotonically_increasing_id()
    )
    other_df = self.sqlContext.read.load('other_table.parquet')
    joined = csv_df.join(other_df, ['col1', 'col2'])
    found_rows = joined.select('mid').distinct()
    not_found_ids = csv_df.where(~csv_df.mid.isin(found_rows))

This gives me the following error:

AttributeError: 'DataFrame' object has no attribute '_get_object_id'

What am I doing wrong? How can I fix my code to get the non-joined rows?

Body:
Although I would still like to know why my above-posted code doesn't work, I've realized that I can just do another join to answer my question:

csv_df = self.sqlContext.read.load('csv_table.parquet')
csv_df = csv_df.withColumn(
    "mid", monotonically_increasing_id()
)
other_df = self.sqlContext.read.load('other_table.parquet')
joined = csv_df.join(other_df, ['col1', 'col2'])
found_rows = joined.select('mid').distinct()
not_found_rows = csv_df.selectExpr('mid').subtract(found_rows)
not_found_ids = csv_df.join(not_found_rows, 'mid')


问:
serenity configuration via pom.xml
I have a java project contains some serenity tests. When I execute mvn test verify -Dwebdriver.chrome.driver=c:\dev\applications\chrome\chromedriver-2.29.exe -Dwebdriver.driver=chrome then my build works fine.

I would like to add the two -D properties to maven pom.xml as a profile as it is written in the serenity documentation but the following code snippet does not work:

```<code><profiles>
    <profile>
        <id>firefox</id>
        <properties>
            <webdriver.driver>firefox</webdriver.driver>
        </properties>
    </profile>
    <profile>
        <id>chrome</id>
        <properties>
            <webdriver.driver>chrome</webdriver.driver>
            <webdriver.chrome.driver>c:\\dev\\applications\\chrome\\chromedriver-2.29.exe</webdriver.chrome.driver>
        </properties>
    </profile>
</profiles>
</code>```

Maven command what I used: mvn clean test verify -Pchrome

I also tried to add the variables to my pom.xml as system variables but it did not work:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <systemPropertyVariables>
            <webdriver.driver>chrome</webdriver.driver>
            <webdriver.chrome.driver>c:/dev/applications/chrome/chromedriver-2.29.exe</webdriver.chrome.driver>
        </systemPropertyVariables>
    </configuration>
</plugin>
</code>```

What is wrong with my pom file?

答: I created a simple "hello-world" application to demonstrate how Serenity and JBehave work together. Link to the java project.</p>

Title: serenity configuration via pom.xml

Body:
I have a java project contains some serenity tests. When I execute mvn test verify -Dwebdriver.chrome.driver=c:\dev\applications\chrome\chromedriver-2.29.exe -Dwebdriver.driver=chrome then my build works fine.

I would like to add the two -D properties to maven pom.xml as a profile as it is written in the serenity documentation but the following code snippet does not work:

<profiles>
    <profile>
        <id>firefox</id>
        <properties>
            <webdriver.driver>firefox</webdriver.driver>
        </properties>
    </profile>
    <profile>
        <id>chrome</id>
        <properties>
            <webdriver.driver>chrome</webdriver.driver>
            <webdriver.chrome.driver>c:\\dev\\applications\\chrome\\chromedriver-2.29.exe</webdriver.chrome.driver>
        </properties>
    </profile>
</profiles>

Maven command what I used: mvn clean test verify -Pchrome

I also tried to add the variables to my pom.xml as system variables but it did not work:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <systemPropertyVariables>
            <webdriver.driver>chrome</webdriver.driver>
            <webdriver.chrome.driver>c:/dev/applications/chrome/chromedriver-2.29.exe</webdriver.chrome.driver>
        </systemPropertyVariables>
    </configuration>
</plugin>

What is wrong with my pom file?


问:
Center three div containers next to each other
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="selectionElementContainer">
      <div id="selectionElementLeft">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLink">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
      <div id="selectionElementCenter">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLink">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
      <div id="selectionElementRight">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLinkContainer">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
    </div></code>```

答:
Check flexbox in this case the parent container is flexed and the children as well with a direction of column for your specific case. You can target nested elements with the pseudo element nth-child(n) for instance .flex-child:nth-child(2) h2 {color: green;} will make the second
 green Fiddle

#flex-parent{
  display:flex;
  width: 100%;
  justify-content: space-around;
  flex-wrap: wrap;
}

.flex-child{
  display:flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}
.flex-child img{
  border-radius: 50%;
}

.flex-child a{
  margin-bottom: 20px; /*So you can have space when the screen resize*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="flex-parent">
  <div class="flex-child">
    <img src="https://placehold.it/100x100">
    <h2>Title</h2>
    <p>Text</p>
    Link
  </div>
  <div class="flex-child">
    <img src="https://placehold.it/100x100">
    <h2>Title</h2>
    <p>Text</p>
    Link
  </div>
  <div class="flex-child">
    <img src="https://placehold.it/100x100">
    <h2>Title</h2>
    <p>Text</p>
    Link
  </div>
</div></code>```

Body:
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

Body:
Check flexbox in this case the parent container is flexed and the children as well with a direction of column for your specific case. You can target nested elements with the pseudo element nth-child(n) for instance .flex-child:nth-child(2) h2 {color: green;} will make the second <h2> green Fiddle

#flex-parent{
  display:flex;
  width: 100%;
  justify-content: space-around;
  flex-wrap: wrap;
}

.flex-child{
  display:flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}
.flex-child img{
  border-radius: 50%;
}

.flex-child a{
  margin-bottom: 20px; /*So you can have space when the screen resize*/
}

<div id="flex-parent">
  <div class="flex-child">
    <img src="https://placehold.it/100x100">
    <h2>Title</h2>
    <p>Text</p>
    <a href="#">Link</a>
  </div>
  <div class="flex-child">
    <img src="https://placehold.it/100x100">
    <h2>Title</h2>
    <p>Text</p>
    <a href="#">Link</a>
  </div>
  <div class="flex-child">
    <img src="https://placehold.it/100x100">
    <h2>Title</h2>
    <p>Text</p>
    <a href="#">Link</a>
  </div>
</div>


问:
Flex SKD's main project and external SWC's
Can I have an application that is based on flex4 SDK and a library (swc file) inside this project which is based on another version of flex (3.2)?

how will flex deal with this situation?

答:
In theory, a Flex 3 SWC should work fine for all Flex 3 point releases.  A Flex 4 SWC should work fine with all Flex 4 point releases.  I wouldn't expect a Flex 3 SWC to work against Flex 4, but it depends what is in the SWC and what classes are used.

In practice, odd errors sometimes do crop up.  I strongly recommend compiling all your SWCs against the same SDK you use with your main project.  A lot of odd runtime and compiler errors can be solved by making sure your versions match.

This is the type of question that makes me wonder "wouldn't it have been quicker to try it than to ask the question." Are you having a specific problem?


问:
python __init__ assignment with operator 'or'
```<code>import operator

class ClassTupleMeta(type):
    def __init__(cls, *args, **kwargs):
        super(ClassTupleMeta, cls).__init__(*args, **kwargs)
        for n, name in enumerate(cls._fields):
            setattr(cls, name, property(operator.itemgetter(n)))

class ClassTuple(tuple):
    _fields = []
    __metaclass__ = ClassTupleMeta
    def __new__(cls, *args):
        if (len(args) != len(cls._fields)):
            raise ValueError('{} arguments required',format(len(cls._fields)))
        return super(ClassTuple, cls).__new__(cls, args)

class CommonConstExam(ClassTuple):
    _fields = ['long_run_50', 'long_run_800', 'long_run_1000']

    def __init__(self, *arg):
        super(CommonConstExam, self).__init__()
        #setattr(self, 'long_run', self.long_run_50 or self.long_run_800 or self.long_run_1000)
</code>```

See code above, for the last line, there's always one of long_run_50, self.long_run_800, self.long_run_1000 that has an non-None value, and I try to assign the non-None value to long_run, but it is always assigned the value of long_run_50, whether it is None or not. And also, if I rewrite it as if-else clauses, it is assigned the value in first if clause. Does anybody know how to tackle this problem? I really want to use only one variable(long_run), which can extremely simplify the following code.

答:
You say your problem is this line:

```<code>setattr(self, 'long_run', self.long_run_50 or self.long_run_800 or self.long_run_1000)
</code>```

The trouble with or-expressions like this is that they sometimes do things you didn't mean: 0 and "", both of which might be legal and interesting values, both count as False. The converse is also true. Suppose, for example, that long_run_50 has the string value "None". That might be very hard to see. Especially as it is probably the result of a bug elsewhere, and so unexpected.

Try using an inline if-expression that specifies exactly what you mean, for example

```<code>setattr(self, 'long_run',
        self.long_run_50 if self.long_run_50 is not None
        else
        self.long_run_800 if self.long_run_800 is not None
        else
        self.long_run_1000 if self.long_run_1000 is not None
        else "Nyah-nyah-nyah")
</code>```

I do wonder why you are using setattr() when it could, as far as I can see, just as well be

```<code>self.long_run = (  ...etc... )
</code>```

There are at least three good reasons why you might be doing that, but I do have to ask.

Body:
import operator

class ClassTupleMeta(type):
    def __init__(cls, *args, **kwargs):
        super(ClassTupleMeta, cls).__init__(*args, **kwargs)
        for n, name in enumerate(cls._fields):
            setattr(cls, name, property(operator.itemgetter(n)))

class ClassTuple(tuple):
    _fields = []
    __metaclass__ = ClassTupleMeta
    def __new__(cls, *args):
        if (len(args) != len(cls._fields)):
            raise ValueError('{} arguments required',format(len(cls._fields)))
        return super(ClassTuple, cls).__new__(cls, args)

class CommonConstExam(ClassTuple):
    _fields = ['long_run_50', 'long_run_800', 'long_run_1000']

    def __init__(self, *arg):
        super(CommonConstExam, self).__init__()
        #setattr(self, 'long_run', self.long_run_50 or self.long_run_800 or self.long_run_1000)

See code above, for the last line, there's always one of long_run_50, self.long_run_800, self.long_run_1000 that has an non-None value, and I try to assign the non-None value to long_run, but it is always assigned the value of long_run_50, whether it is None or not. And also, if I rewrite it as if-else clauses, it is assigned the value in first if clause. Does anybody know how to tackle this problem? I really want to use only one variable(long_run), which can extremely simplify the following code.

Body:
You say your problem is this line:

setattr(self, 'long_run', self.long_run_50 or self.long_run_800 or self.long_run_1000)

The trouble with or-expressions like this is that they sometimes do things you didn't mean: 0 and "", both of which might be legal and interesting values, both count as False. The converse is also true. Suppose, for example, that long_run_50 has the string value "None". That might be very hard to see. Especially as it is probably the result of a bug elsewhere, and so unexpected.

Try using an inline if-expression that specifies exactly what you mean, for example

setattr(self, 'long_run',
        self.long_run_50 if self.long_run_50 is not None
        else
        self.long_run_800 if self.long_run_800 is not None
        else
        self.long_run_1000 if self.long_run_1000 is not None
        else "Nyah-nyah-nyah")

I do wonder why you are using setattr() when it could, as far as I can see, just as well be

self.long_run = (  ...etc... )

There are at least three good reasons why you might be doing that, but I do have to ask.


问:
Delphi DataSnap Rest
I'm running some Datasnap tests with REST and json.

There in Unit ServerMethods, which Delphi itself creates, has the "ReverseString" function, but well, how do I know who sent it?

I would like to keep a log of information from the clients who called this method.

I know it could be passed as a parameter, but it would be the responsibility of the client to pass this information to me, which I do not want, let's say the method would be public and several clients would be triggering this information. I can easily lose this control, if I do not get the information directly by the control of the server.

I found on the web, that in the ServerConteiner unit, has a "DSServer" object, this object has an event called "OnConnect", so it can get the following sa data:

```<code>Procedure TServerContainer1.DSServer1Connect (
  DSConnectEventObject: TDSConnectEventObject);
Begin
  DSConnectEventObject.ChannelInfo.ClientInfo.IpAddress;
  DSConnectEventObject.ChannelInfo.ClientInfo.ClientPort;
  DSConnectEventObject.ChannelInfo.ClientInfo.Protocol;
  DSConnectEventObject.ChannelInfo.ClientInfo.AppName;
End;
</code>```

But I am not able to find how there in ServerMethods.ReverseString I can get this data ...

I believe that the processing is in thread on the server, so I can not pass this value as global, because it can pick up information from other simultaneous connections.

In the method, ReverseString, I tried as follows:

```<code>Var
    ADSServerClass: TDSServerClass;
Begin
  ADSServerClass: = TDSServerClass (GetOwner);
  TDSServer (ADSServerClass.Server). ???
  // I got to the server, but I can not find it, and I do not know if it is this way to find the data of who is requesting me to execute the ReverseString
End;
</code>```

答:
Server side session management is a solution: an advanced feature of DataSnap. When a client connects to a DataSnap server, a session is created. This session is represented with a TDSSession instance.

In a session object you put for example ip-address. In server method you can read information from session object for specific client connection.

http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Server_Side_Session_Management

Title: Delphi DataSnap Rest

Body:
I'm running some Datasnap tests with REST and json.

There in Unit ServerMethods, which Delphi itself creates, has the "ReverseString" function, but well, how do I know who sent it?

I would like to keep a log of information from the clients who called this method.

I know it could be passed as a parameter, but it would be the responsibility of the client to pass this information to me, which I do not want, let's say the method would be public and several clients would be triggering this information. I can easily lose this control, if I do not get the information directly by the control of the server.

I found on the web, that in the ServerConteiner unit, has a "DSServer" object, this object has an event called "OnConnect", so it can get the following sa data:

Procedure TServerContainer1.DSServer1Connect (
  DSConnectEventObject: TDSConnectEventObject);
Begin
  DSConnectEventObject.ChannelInfo.ClientInfo.IpAddress;
  DSConnectEventObject.ChannelInfo.ClientInfo.ClientPort;
  DSConnectEventObject.ChannelInfo.ClientInfo.Protocol;
  DSConnectEventObject.ChannelInfo.ClientInfo.AppName;
End;

But I am not able to find how there in ServerMethods.ReverseString I can get this data ...

I believe that the processing is in thread on the server, so I can not pass this value as global, because it can pick up information from other simultaneous connections.

In the method, ReverseString, I tried as follows:

Var
    ADSServerClass: TDSServerClass;
Begin
  ADSServerClass: = TDSServerClass (GetOwner);
  TDSServer (ADSServerClass.Server). ???
  // I got to the server, but I can not find it, and I do not know if it is this way to find the data of who is requesting me to execute the ReverseString
End;


问:
Test for array of string type in TypeScript
How can I test if a variable is an array of string in TypeScript?  Something like this:

```<code>function f(): string {
    var a: string[] = ["A", "B", "C"];

    if (typeof a === "string[]")    {
        return "Yes"
    }
    else {
        // returns no as it's 'object'
        return "No"
    }
};
</code>```

TypeScript.io here: http://typescript.io/k0ZiJzso0Qg/2

Edit: I've updated the text to ask for a test for string[]. This was only in the code example previously.

答:
I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

If you have a type like: Object[] | string[] and what to do something conditionally based on what type it is - you can use this type guarding:

function isStringArray(value: any): value is string[] {
  if (value instanceof Array) {
    for (const item of value) {
      if (typeof item !== 'string') {
        return false
      }
    }
    return true
  }
  return false
}

function join<T>(value: string[] | T[]) {
  if (isStringArray(value)) {
    return value.join(',') // value is string[] here
  } else {
    return value.map((x) => x.toString()).join(',') // value is T[] here
  }
}
```

There is an issue with an empty array being typed as string[], but that might be okay

Body:
How can I test if a variable is an array of string in TypeScript?  Something like this:

function f(): string {
    var a: string[] = ["A", "B", "C"];

    if (typeof a === "string[]")    {
        return "Yes"
    }
    else {
        // returns no as it's 'object'
        return "No"
    }
};

TypeScript.io here: http://typescript.io/k0ZiJzso0Qg/2

Edit: I've updated the text to ask for a test for string[]. This was only in the code example previously.

Body:
I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

If you have a type like: Object[] | string[] and what to do something conditionally based on what type it is - you can use this type guarding:

function isStringArray(value: any): value is string[] {
  if (value instanceof Array) {
    for (const item of value) {
      if (typeof item !== 'string') {
        return false
      }
    }
    return true
  }
  return false
}

function join<T>(value: string[] | T[]) {
  if (isStringArray(value)) {
    return value.join(',') // value is string[] here
  } else {
    return value.map((x) => x.toString()).join(',') // value is T[] here
  }
}

There is an issue with an empty array being typed as string[], but that might be okay

ContentLicense: CC BY-SA 4.0


问:
Python: Close a loop on keypress
I am building an motion detection security camera with a raspberry pi https://www.raspberrypi.org/learning/parent-detector/worksheet/.

The code works fine, but I want the device to run my python code at startup and I want it to close the program when I hit a certain key. As of now, the program runs but wont get out of the loop so I can't get to the raspberry pi desktop (my workaround to this is turning the device off, manually removing the camera, turn the device back on, to get an error because camera is not detected which exits the code to the desktop....very inefficient I know!)

Essentially, this code was written to run the program from a pi that is connected to a monitor, keyboard, etc. I want to just plug it in somewhere and have it arm the camera. Then after I return to the house (work, vacation, etc), I want to plug in a keyboard, hit a key to exit the program, shutdown safly and be able to view any security incidents when I connect it to a monitor.

script code:

```<code>from gpiozero import MotionSensor
from picamera import PiCamera
from datetime import datetime

camera = PiCamera()
pir = MotionSensor(4)
while True:
    pir.wait_for_motion()
    filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
    camera.start_recording(filename)
    pir.wait_for_no_motion()
    camera.stop_recording()
</code>```

答:
You can stop program execution with Ctrl + C in the command line window that the script is running in.

If you'd like to still do some processing, then wrap your while loop in an try block as such:

```<code>try:
    while True:
        pir.wait_for_motion()
        filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
        camera.start_recording(filename)
        pir.wait_for_no_motion()
        camera.stop_recording()
except KeyboardInterrupt:
    pass

# Continue your code here
</code>```

If you'd like to pick the key that stops the program (other than Ctrl + C) and/or have it stop when you press your key from anywhere in the OS, then I'd recommend using the Keyboard library.

Title: Python: Close a loop on keypress

Body:
I am building an motion detection security camera with a raspberry pi https://www.raspberrypi.org/learning/parent-detector/worksheet/.

The code works fine, but I want the device to run my python code at startup and I want it to close the program when I hit a certain key. As of now, the program runs but wont get out of the loop so I can't get to the raspberry pi desktop (my workaround to this is turning the device off, manually removing the camera, turn the device back on, to get an error because camera is not detected which exits the code to the desktop....very inefficient I know!)

Essentially, this code was written to run the program from a pi that is connected to a monitor, keyboard, etc. I want to just plug it in somewhere and have it arm the camera. Then after I return to the house (work, vacation, etc), I want to plug in a keyboard, hit a key to exit the program, shutdown safly and be able to view any security incidents when I connect it to a monitor.

script code:

from gpiozero import MotionSensor
from picamera import PiCamera
from datetime import datetime

camera = PiCamera()
pir = MotionSensor(4)
while True:
    pir.wait_for_motion()
    filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
    camera.start_recording(filename)
    pir.wait_for_no_motion()
    camera.stop_recording()

Body:
You can stop program execution with Ctrl + C in the command line window that the script is running in.

If you'd like to still do some processing, then wrap your while loop in an try block as such:

try:
    while True:
        pir.wait_for_motion()
        filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
        camera.start_recording(filename)
        pir.wait_for_no_motion()
        camera.stop_recording()
except KeyboardInterrupt:
    pass

# Continue your code here

If you'd like to pick the key that stops the program (other than Ctrl + C) and/or have it stop when you press your key from anywhere in the OS, then I'd recommend using the Keyboard library.


问:
How to create a Mininet VLAN
I am using Mininet to simulate a network I am trying to create. Is there a way to setup switches to use VLANs? I can't find any documentation on it.</p>

答:
From GitHub:

vlanhost.py:
  An example of how to subclass Host to use a VLAN on its primary interface.

Mininet Examples

Mininet Python API Reference Manua

Title: How to create a Mininet VLAN


问:
How to edit file in resources of Spring MVC?
I have a project on Spring MVC, The resources folder added to buildpath of Spring.

Project Structure

On some UI action i want to edit the file resources/thirdparty/thirdparty.er from the controller.

So here are the code is tried

```<code>File inputFile = new File("/home/local/<User>/Desktop/workspace/<ProjectName>/WebContent/resources/thirdparty/thirdparty.er");
</code>```

result - it worked fine

Instead of absolute path i wanted a relative path so i tried

```<code>File inputFile = new File("../../<something>/WebContent/resources/thirdparty/thirdparty.er");
</code>```

result - it worked fine, but the path was relative to eclipse(base path), as i was executing code in eclipse

To remove eclipse path dependency, i tried

```<code>File inputFile = new File("/resources/thirdparty/thirdparty.er");
</code>```

result - it didnot worked

Later on searching web, i found

```<code>Resource resource = new ClassPathResource("/thirdparty/thirdparty.ER");
File inputFile = resource.getFile();
</code>```

result - it is returning

/home/local//Desktop/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps//WEB-INF/classes/thirdparty/thirdparty.er

which actually isn't the file i want to edit.
Please let me know how this can be done. I donot want any path dependencies on eclipse, server or the system, it sould be completely based on project.

答:
Maybe all you need is

```<code>Resource resource = resourceLoader.getResource("classpath:/thirdparty/thirdparty.ER");
</code>```

and just autowire the resource loader like that:

```<code>@Autowired
private ResourceLoader resourceLoader;
</code>```

Body:
I have a project on Spring MVC, The resources folder added to buildpath of Spring.

Project Structure

On some UI action i want to edit the file resources/thirdparty/thirdparty.er from the controller.

So here are the code is tried

File inputFile = new File("/home/local/<User>/Desktop/workspace/<ProjectName>/WebContent/resources/thirdparty/thirdparty.er");

result - it worked fine

Instead of absolute path i wanted a relative path so i tried

File inputFile = new File("../../<something>/WebContent/resources/thirdparty/thirdparty.er");

result - it worked fine, but the path was relative to eclipse(base path), as i was executing code in eclipse

To remove eclipse path dependency, i tried

File inputFile = new File("/resources/thirdparty/thirdparty.er");

result - it didnot worked

Later on searching web, i found

Resource resource = new ClassPathResource("/thirdparty/thirdparty.ER");
File inputFile = resource.getFile();

result - it is returning

/home/local//Desktop/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps//WEB-INF/classes/thirdparty/thirdparty.er

which actually isn't the file i want to edit.
Please let me know how this can be done. I donot want any path dependencies on eclipse, server or the system, it sould be completely based on project.

Body:
Maybe all you need is

Resource resource = resourceLoader.getResource("classpath:/thirdparty/thirdparty.ER");

and just autowire the resource loader like that:

@Autowired
private ResourceLoader resourceLoader;


问:
Localization and drawables
I want to localize an image by adding the folder res/drawable-hdpi-no, but I get an error stating "invalid resource directory name".  What's up with this?</p>

答:
As far as I remember, only certain res folders will work.
You need to call it drawable-[language code]-r[capitalised localisation code] if I remember rightly. Pretty sure it's one of the Android Tutorials.

Yeah here it is
http://developer.android.com/resources/tutorials/localization/index.html

Title: Localization and drawables


问:
Automatically subset data frame by factor
Looking for help writing a function to automatically subset data frames based on the value of a column? For example,

df$x contains values a, b, c, d

I want to make separate data frames named a, b, c, d that contain all values x == 'a', or x == 'b', etc. I know several methods to do this manually but am hoping for guidance on how to automate this? Thank you!

答:
The split function returns a list of subsetted data frames:

```<code>split(df, df$x)
</code>```

EDIT:

If you want a new object for each subsetted data frame:

```<code>for (i in levels(df$x)) {
    command <- paste0(i, "<-subset(df, x=='", i, "')")
    eval(parse(text=command))
}
</code>```

EDIT 2:

To split by two or more variables, a more automated solution would be to create a function that takes as input a data frame and column names with which to subset the dataframe:

```<code>create_new_df <- function (dataframe, vars) {
    # Creates a new data frame in the global environment based on names of variables in 'vars'
    split(dataframe, as.list(dataframe[, vars]), drop = TRUE) %>%
        lapply(function (subset_dataframe) {
            new_object_name <- paste(as.character(subset_dataframe[1, vars])
            # The double arrowed '<<-' creates a new object in the global environment
            command <- paste0(new_object_name, collapse="_"), "<<-subset_dataframe")
            eval(parse(text=command))
        }) %>%
        invisible()
}
</code>```

This function can then be used to create new objects with any combination of variables:

```<code>variables <- c("x", "y", "z")
create_new_df(df, variables)
</code>```

Body:
The split function returns a list of subsetted data frames:

split(df, df$x)

EDIT:

If you want a new object for each subsetted data frame:

for (i in levels(df$x)) {
    command <- paste0(i, "<-subset(df, x=='", i, "')")
    eval(parse(text=command))
}

EDIT 2:

To split by two or more variables, a more automated solution would be to create a function that takes as input a data frame and column names with which to subset the dataframe:

create_new_df <- function (dataframe, vars) {
    # Creates a new data frame in the global environment based on names of variables in 'vars'
    split(dataframe, as.list(dataframe[, vars]), drop = TRUE) %>%
        lapply(function (subset_dataframe) {
            new_object_name <- paste(as.character(subset_dataframe[1, vars])
            # The double arrowed '<<-' creates a new object in the global environment
            command <- paste0(new_object_name, collapse="_"), "<<-subset_dataframe")
            eval(parse(text=command))
        }) %>%
        invisible()
}

This function can then be used to create new objects with any combination of variables:

variables <- c("x", "y", "z")
create_new_df(df, variables)


问:
How to detect if browser window is scrolled to bottom?
I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them to the new bottom. If they are not at the bottom, they are reading previous content higher on the page, so I don't want to auto-scroll them since they want to stay where they are.

How can I detect if a user is scrolled to the bottom of the page or if they have scrolled higher on the page?

答:
```<code>window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};
</code>```

This Answer will fix edge cases, this is because pageYOffset is double while innerHeight and  offsetHeight are long, so when the browser gives you the info, you may be a pixel short.
For example: on bottom of the page we have

true window.innerHeight = 10.2

true window.pageYOffset = 5.4

true document.body.offsetHeight = 15.6

Our calculation then becomes:
10 + 5.4 >= 16 which is false

To fix this we can do Math.ceil on the pageYOffset value.

Hope that helps.

Body:
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

This Answer will fix edge cases, this is because pageYOffset is double while innerHeight and  offsetHeight are long, so when the browser gives you the info, you may be a pixel short.
For example: on bottom of the page we have

true window.innerHeight = 10.2

true window.pageYOffset = 5.4

true document.body.offsetHeight = 15.6

Our calculation then becomes:
10 + 5.4 >= 16 which is false

To fix this we can do Math.ceil on the pageYOffset value.

Hope that helps.


问:
How to Override Client Side Soap Logging - Spring Boot
I'm consuming a soap webservice inside a spring boot application. The response/request logging is too big, because of one attribute which is too large. So I want to intercept that logging and remove the offending attribute.

I've been messing about with SoapEnvelopeLoggingInterceptor, but i think that is just for Server side logging. It will not get picked up.

I have configured my soap logging inside yml as follows:

```<code>logging:
  pattern:
    ...
  level:
    ...
    org.springframework.ws.client.MessageTracing.sent: TRACE
    org.springframework.ws.client.MessageTracing.received: TRACE
    org.springframework.ws.server.MessageTracing: DEBUG
</code>```

That works fine for logging both request and response, but I need to remove a very large problematic attribute from the envelope. Any ideas?

答:
There is no simple way of doing that. You ether implement your own Logger by extending sl4j API or wrap log calls and do the transformations there.

The first way will require some efforts because you'll need to implement batch of classes and make sure that the other parts of log system are not broken.

But second part is pretty strait forward.
You have ti create a logger wrapper which implements Logger interface, could be something like this:

```<code>public class LoggerWrapper extends MarkerIgnoringBase {
    private final Logger logger;

    public LoggerWrapper(Logger logger) {
        this.logger = logger;
    }

    private String transformMessage(String input) {
        // do all needed regexp transformations here
    }

    @Override
    public void debug(String msg) {
        String transformedMessage = transformMessage(msg);
        // delegate log call to inner logger
        logger.debug(transformedMessage);
    }

    // implement the rest of the methods here
}
</code>```

And in the code you might use it like this:

```<code>private static final Logger log = new LoggerWrapper(
        LoggerFactory.getLogger(SomeClass.class)
);
</code>```

You can also wrap the logger without implementing Logger interface (in my case it is MarkerIgnoringBase class). In that case you'll not need to implement number of methods from the interface, however you'll louse interchangeability.

The drawback of this solution is that you have to log the messages in advance on your side (not via MessageTracing) but if it is possible I would go this way. On the other hand the first solution does it out of the box.

Body:
I'm consuming a soap webservice inside a spring boot application. The response/request logging is too big, because of one attribute which is too large. So I want to intercept that logging and remove the offending attribute.

I've been messing about with SoapEnvelopeLoggingInterceptor, but i think that is just for Server side logging. It will not get picked up.

I have configured my soap logging inside yml as follows:

logging:
  pattern:
    ...
  level:
    ...
    org.springframework.ws.client.MessageTracing.sent: TRACE
    org.springframework.ws.client.MessageTracing.received: TRACE
    org.springframework.ws.server.MessageTracing: DEBUG

That works fine for logging both request and response, but I need to remove a very large problematic attribute from the envelope. Any ideas?

Body:
There is no simple way of doing that. You ether implement your own Logger by extending sl4j API or wrap log calls and do the transformations there.

The first way will require some efforts because you'll need to implement batch of classes and make sure that the other parts of log system are not broken.

But second part is pretty strait forward.
You have ti create a logger wrapper which implements Logger interface, could be something like this:

public class LoggerWrapper extends MarkerIgnoringBase {
    private final Logger logger;

    public LoggerWrapper(Logger logger) {
        this.logger = logger;
    }

    private String transformMessage(String input) {
        // do all needed regexp transformations here
    }

    @Override
    public void debug(String msg) {
        String transformedMessage = transformMessage(msg);
        // delegate log call to inner logger
        logger.debug(transformedMessage);
    }

    // implement the rest of the methods here
}

And in the code you might use it like this:

private static final Logger log = new LoggerWrapper(
        LoggerFactory.getLogger(SomeClass.class)
);

You can also wrap the logger without implementing Logger interface (in my case it is MarkerIgnoringBase class). In that case you'll not need to implement number of methods from the interface, however you'll louse interchangeability.

The drawback of this solution is that you have to log the messages in advance on your side (not via MessageTracing) but if it is possible I would go this way. On the other hand the first solution does it out of the box.


问:
rewrite url from subdirectory to subdomain
How to redirect the url using .htaccess?

Actual url is www.mywebsite.com/index.php/user/john

is need to convert as john.mywebsite.com/

答:
Try this code in .htaccess:

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteEngine On
RewriteRule ^index.php/(.*)/(.*) $2.mywebsite.com/
</code>```

Body:
Try this code in .htaccess:

Options +FollowSymLinks
RewriteEngine on
RewriteEngine On
RewriteRule ^index.php/(.*)/(.*) $2.mywebsite.com/


问:
How to set the value of the Access-Control-Allow-Origin header based on a list of allowed origins?
I have read quite a lot of posts but none of them worked though.

I have ec2 setup in aws installed with ubuntu 16.04 and nginx. went into the site-available /  site-enabled to 'Access-Control-Allow-Origin' allowing one domain access, but how can I add more than one domain access?

I would get multiple values error if I add more than one accress.
Lots posts are about php such as

NGINX 'Access-Control-Allow-Origin' header contains multiple values

even though I am not using php but I have tried using the code above but does not work though.

is anyone able to give me a hand or direct me how this can be done on server?

Thanks in advance.

答:
You can conditionally cause the Access-Control-Allow-Origin response header to be sent, with the right value, by adding something like the following to your nginx config.

```<code>location / {
  set $is_allowed_origin "";
  if ($http_origin = "https://some.allowed.origin") {
    set $is_allowed_origin "true";
  }
  if ($http_origin = "https://another.allowed.origin") {
    set $is_allowed_origin "true";
  }
  if ($is_allowed_origin = "true") {
    add_header "Access-Control-Allow-Origin" "$http_origin";
  }
}
</code>```

That’ll cause Access-Control-Allow-Origin: https://some.allowed.origin to be sent if the value of the Origin request header in the request is https://some.allowed.origin, and will cause Access-Control-Allow-Origin: https://another.allowed.origin to be sent if the Origin is https://another.allowed.origin, etc.

And if the value of the Origin request header is neither https://some.allowed.origin or https://another.allowed.origin, then no Access-Control-Allow-Origin would be sent.

Body:
You can conditionally cause the Access-Control-Allow-Origin response header to be sent, with the right value, by adding something like the following to your nginx config.

location / {
  set $is_allowed_origin "";
  if ($http_origin = "https://some.allowed.origin") {
    set $is_allowed_origin "true";
  }
  if ($http_origin = "https://another.allowed.origin") {
    set $is_allowed_origin "true";
  }
  if ($is_allowed_origin = "true") {
    add_header "Access-Control-Allow-Origin" "$http_origin";
  }
}

That’ll cause Access-Control-Allow-Origin: https://some.allowed.origin to be sent if the value of the Origin request header in the request is https://some.allowed.origin, and will cause Access-Control-Allow-Origin: https://another.allowed.origin to be sent if the Origin is https://another.allowed.origin, etc.

And if the value of the Origin request header is neither https://some.allowed.origin or https://another.allowed.origin, then no Access-Control-Allow-Origin would be sent.


问:
Customizing ASP.NET Identity
I'm using Identity Server 4 and I've customised my ASP.NET Identity user as follows:

```<code>public class ApplicationUser : IdentityUser
{
    [MaxLength(100)]
    public virtual string FirstName { get; set; }

    [MaxLength(100)]
    public virtual string LastName { get; set; }
}
</code>```

I can't see where I would configure Identity Server 4 to include these 2 properties in the claims collection.  I've had a look through some of the Identity Server 4 samples but can't see any examples.

I'd ideally like to map these 2 user properties to the given_name and family_name claims.

I'm currently hooking up to the notifications and querying the userinfo endpoint (hybrid flow?).  So I'm not sure if this is configuration of Identity Server or customization of the userinfo endpoint?

答:
In order to include your custom claims, you need to implement your own GetProfileDataAsync() method using the IProfileService. This method is being called everytime a user claim is requested.

Here is my implementation of IProfileService.

```<code>public class CustomProfileService : IProfileService
{
    private readonly UserManager<User> _userManager;

    public CustomProfileService(UserManager<User> userManager)
    {
        _userManager = userManager;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var subjectId = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(subjectId);

        if (user == null) return;

        var claims = new List<Claim>
        {
            new Claim("username", user.UserName),
            new Claim("email", user.Email),
            new Claim("firstname", user.FirstName),
            new Claim("lastname", user.LastName)
        };

        var roles = await _userManager.GetRolesAsync(user);
        foreach (var role in roles)
        {
            claims.Add(new Claim("role", role));
        }

        var userClaims = await _userManager.GetClaimsAsync(user);
        foreach (var userClaim in userClaims)
        {
            claims.Add(new Claim(userClaim.Type, userClaim.Value));
        }

        context.IssuedClaims = claims;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        var user = await _userManager.FindByIdAsync(context.Subject.GetSubjectId());
        context.IsActive = user.IsActive;
    }
}
</code>```

Then you will have to add this following line to Startup.ConfigureServices()

services.AddScoped<IProfileService, CustomProfileService>();

Title: Customizing ASP.NET Identity

Body:
I'm using Identity Server 4 and I've customised my ASP.NET Identity user as follows:

public class ApplicationUser : IdentityUser
{
    [MaxLength(100)]
    public virtual string FirstName { get; set; }

    [MaxLength(100)]
    public virtual string LastName { get; set; }
}

I can't see where I would configure Identity Server 4 to include these 2 properties in the claims collection.  I've had a look through some of the Identity Server 4 samples but can't see any examples.

I'd ideally like to map these 2 user properties to the given_name and family_name claims.

I'm currently hooking up to the notifications and querying the userinfo endpoint (hybrid flow?).  So I'm not sure if this is configuration of Identity Server or customization of the userinfo endpoint?

Body:
In order to include your custom claims, you need to implement your own GetProfileDataAsync() method using the IProfileService. This method is being called everytime a user claim is requested.

Here is my implementation of IProfileService.

public class CustomProfileService : IProfileService
{
    private readonly UserManager<User> _userManager;

    public CustomProfileService(UserManager<User> userManager)
    {
        _userManager = userManager;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var subjectId = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(subjectId);

        if (user == null) return;

        var claims = new List<Claim>
        {
            new Claim("username", user.UserName),
            new Claim("email", user.Email),
            new Claim("firstname", user.FirstName),
            new Claim("lastname", user.LastName)
        };

        var roles = await _userManager.GetRolesAsync(user);
        foreach (var role in roles)
        {
            claims.Add(new Claim("role", role));
        }

        var userClaims = await _userManager.GetClaimsAsync(user);
        foreach (var userClaim in userClaims)
        {
            claims.Add(new Claim(userClaim.Type, userClaim.Value));
        }

        context.IssuedClaims = claims;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        var user = await _userManager.FindByIdAsync(context.Subject.GetSubjectId());
        context.IsActive = user.IsActive;
    }
}

Then you will have to add this following line to Startup.ConfigureServices()

services.AddScoped<IProfileService, CustomProfileService>();


问:
Javascript bitwise operators - explanation required
I'm using some code in JS and I bumped into these (unrelated) expressions:

```<code>1) var r = (d + Math.random() * 16) % 16 | 0;

2) return c === 'x' ? r : (r & 0x3 | 0x8);
</code>```

I read some about bitwise operators but it does not help in this context.
Can somebody explain (preferably step-by-step) how do they work ? How this two expressions are logically evaluated and run ?

Thanks in advance.

答:
First statement has almost nothing to do with bitwise operators.
It simply means:

assign random number between 0 and 15 to r, but if variable d is undefined, give me 0. It uses math fact that modulo 16 of any number gives you a result in [0..15] range and bitwise OR with 0 is an identity operation with one exception. JavaScript logic of handling undefined dictates that without | 0 when d is undefined you will get NaN as a result in r.

Second statement does use bitwise operators.

x & 0x03 is the same as x BITWISE_AND 0011 and it returns lowest 2 bits of x. x | 0x8 always sets 4th bit. So, c will be a 10.. where dots are the lowest 2 bits of r. Of course, it will happen only if c is a string and equals x.

I strongly suggest you read https://www.w3schools.com/js/js_bitwise.asp and do some experimentation.

Body:
I'm using some code in JS and I bumped into these (unrelated) expressions:

1) var r = (d + Math.random() * 16) % 16 | 0;

2) return c === 'x' ? r : (r & 0x3 | 0x8);

I read some about bitwise operators but it does not help in this context.
Can somebody explain (preferably step-by-step) how do they work ? How this two expressions are logically evaluated and run ?

Thanks in advance.


问:
How to animate the height changing
I have a simple card in my app and when the user click on it, I'm changing the height. This change of height I'd like to be animated, a smooth change of height.

```<code>@OnClick({R.id.emptyDescription})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.emptyDescription:
            if(isCardCollapsed){

                emptyDescription.setMinimumHeight(400);

                cancelSaveLinear.setVisibility(View.VISIBLE);
                editDescription.setVisibility(View.GONE);

                isCardCollapsed = false;
            } else {
                emptyDescription.setMinimumHeight(100);

                cancelSaveLinear.setVisibility(View.GONE);
                editDescription.setVisibility(View.VISIBLE);

                isCardCollapsed = true;
            }

            break;
        case R.id.card_view:
            break;
    }
}
</code>```

How could I do it?

答:
you need to set layout transition when applying the new size check out this developer.android.com/training/animation/layout.html

```<code>TransitionManager.beginDelayedTransition(transitionsContainer, new TransitionSet()
    .addTransition(new ChangeBounds())
    .addTransition(new ChangeImageTransform()));

ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.height = expanded ? ViewGroup.LayoutParams.MATCH_PARENT :
    ViewGroup.LayoutParams.WRAP_CONTENT;
imageView.setLayoutParams(params);

imageView.setScaleType(expanded ? ImageView.ScaleType.CENTER_CROP :
    ImageView.ScaleType.FIT_CENTER);
</code>```

Source of Sample Code
https://medium.com/@andkulikov/animate-all-the-things-transitions-in-android-914af5477d50

Title: How to animate the height changing

Body:
I have a simple card in my app and when the user click on it, I'm changing the height. This change of height I'd like to be animated, a smooth change of height.

@OnClick({R.id.emptyDescription})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.emptyDescription:
            if(isCardCollapsed){

                emptyDescription.setMinimumHeight(400);

                cancelSaveLinear.setVisibility(View.VISIBLE);
                editDescription.setVisibility(View.GONE);

                isCardCollapsed = false;
            } else {
                emptyDescription.setMinimumHeight(100);

                cancelSaveLinear.setVisibility(View.GONE);
                editDescription.setVisibility(View.VISIBLE);

                isCardCollapsed = true;
            }

            break;
        case R.id.card_view:
            break;
    }
}

How could I do it?

Body:
you need to set layout transition when applying the new size check out this developer.android.com/training/animation/layout.html

TransitionManager.beginDelayedTransition(transitionsContainer, new TransitionSet()
    .addTransition(new ChangeBounds())
    .addTransition(new ChangeImageTransform()));

ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.height = expanded ? ViewGroup.LayoutParams.MATCH_PARENT :
    ViewGroup.LayoutParams.WRAP_CONTENT;
imageView.setLayoutParams(params);

imageView.setScaleType(expanded ? ImageView.ScaleType.CENTER_CROP :
    ImageView.ScaleType.FIT_CENTER);

Source of Sample Code
https://medium.com/@andkulikov/animate-all-the-things-transitions-in-android-914af5477d50


问:
NSUserDefaults: How to get value
I am new in iOS, Object-C and I am trying to do a simple login/registerLogin using NSUserDefaults.

My problem is: How could I access/get the value saved in NSUserDefaults to verify if an user already exist?

This is the code for registering a new user:

```<code>-(void)registerNewUser {

// Getting username and the password
NSString *newUsername = self.usernameRegisterTextField.text;
NSString *newPassword = self.passwordRegisterTextField.text;

// Using NSUserDefaults to storage username and password
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

[newUser setObject:newUsername forKey:@"username"];
[newUser setObject:newPassword forKey:@"password"];
[newUser setBool:YES forKey:@"registered"];

[newUser synchronize];

[self performSegueWithIdentifier:@"registerSucessSegue" sender:nil];
</code>```

}

And I am trying to get the value saved in NSUserDefaults to verify if an user already exist instead of calling the login screen again:

```<code>- (IBAction)productTableButton:(id)sender {
// Verification if an user exist
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

BOOL newUserExist = [newUser valueForKey:@"registered"];

if (newUserExist == YES) {
    [self performSegueWithIdentifier:@"productSegue" sender:nil];
} else {
    [self performSegueWithIdentifier:@"loginSegue" sender:nil];
}
</code>```

}

Is there something that I am doing wrong when I am trying to access the value of an user saved in NSUserDefaults?

答:
You can always check objectForKey, which is safe to use for any type that could be associated with your key.

If the key has been previously set, it will return an id; otherwise, it will return nil. If it is a boolean, you will get an NSNumber which can easily be converted.

```<code>id someKey = [[NSUserDefaults standardUserDefaults] objectForKey:@"Key"];
if(someKey)
{
    //User exists
}
else
{
    //User doesn't exist
}
</code>```

Title: NSUserDefaults: How to get value

Body:
I am new in iOS, Object-C and I am trying to do a simple login/registerLogin using NSUserDefaults.

My problem is: How could I access/get the value saved in NSUserDefaults to verify if an user already exist?

This is the code for registering a new user:

-(void)registerNewUser {

// Getting username and the password
NSString *newUsername = self.usernameRegisterTextField.text;
NSString *newPassword = self.passwordRegisterTextField.text;

// Using NSUserDefaults to storage username and password
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

[newUser setObject:newUsername forKey:@"username"];
[newUser setObject:newPassword forKey:@"password"];
[newUser setBool:YES forKey:@"registered"];

[newUser synchronize];

[self performSegueWithIdentifier:@"registerSucessSegue" sender:nil];

}

And I am trying to get the value saved in NSUserDefaults to verify if an user already exist instead of calling the login screen again:

- (IBAction)productTableButton:(id)sender {
// Verification if an user exist
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

BOOL newUserExist = [newUser valueForKey:@"registered"];

if (newUserExist == YES) {
    [self performSegueWithIdentifier:@"productSegue" sender:nil];
} else {
    [self performSegueWithIdentifier:@"loginSegue" sender:nil];
}

}

Is there something that I am doing wrong when I am trying to access the value of an user saved in NSUserDefaults?

Body:
You can always check objectForKey, which is safe to use for any type that could be associated with your key.

If the key has been previously set, it will return an id; otherwise, it will return nil. If it is a boolean, you will get an NSNumber which can easily be converted.

id someKey = [[NSUserDefaults standardUserDefaults] objectForKey:@"Key"];
if(someKey)
{
    //User exists
}
else
{
    //User doesn't exist
}


问:
Angular2 App: Fetch as Google doesn't load page content
I am working on Angular2 based web app. I used Angular CLI to generate app and then to build it for prod. I have hosted website on AWS S3 & Cloudfront. When I use 'Fetch as Google' tool from the webmaster, it shows only Loading....

Isn't Googlebot able to crawl my website?

答:
had a similar issue. I believe Google-Bot do not support modern JS. I simply activated all shims recommended by angular.io see https://angular.io/docs/ts/latest/guide/browser-support.html and added in the script header:

```

If you really need all of them I'm not sure, but I need support for older IE  anyway.

If this works for all Searchbots is very unclear, if you have to support them you can try https://prerender.io/. However they are also just able to render it with the shims

Hope this helps.

Body:
had a similar issue. I believe Google-Bot do not support modern JS. I simply activated all shims recommended by angular.io see https://angular.io/docs/ts/latest/guide/browser-support.html and added in the script header:

<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/shim.min.js">
</script>

If you really need all of them I'm not sure, but I need support for older IE  anyway.

If this works for all Searchbots is very unclear, if you have to support them you can try https://prerender.io/. However they are also just able to render it with the shims

Hope this helps.


问:
How to read multiple .xls files in r?
I have 18 files(.xls) in list and I want to read them in one go

Here is my codes below:

filenames=list.files("C:/Users/ozgur.alptekin/Downloads/elif")

df.list=lapply(filenames, function(x) read_excel(file = x,sheetIndex = 1,as.data.frame = TRUE,header = TRUE))

it did not work

Could you please tell me what I have done wrong and how I should do it?

答:
Can you simply try a loop?

```<code>filenames=list.files("C:/Users/ozgur.alptekin/Downloads/elif")

for (i in 1:length(filenames) {
assign(paste0("file_", i),
read_excel(file = filenames[i],sheetIndex = 1, as.data.frame = TRUE, header = TRUE), envir = .GlobalEnv)
}
</code>```

reply if it works.

Title: How to read multiple .xls files in r?

Body:
Can you simply try a loop?

filenames=list.files("C:/Users/ozgur.alptekin/Downloads/elif")

for (i in 1:length(filenames) {
assign(paste0("file_", i),
read_excel(file = filenames[i],sheetIndex = 1, as.data.frame = TRUE, header = TRUE), envir = .GlobalEnv)
}

reply if it works.


问:
Is_Integer returning incorrect result - Python 2.X
```<code>dig = 16807
digcount = len(str(dig))
minroot = dig ** (1 / float(digcount))

print minroot
print minroot.is_integer()
</code>```

minroot returns as 7.0 as a float, but is_integer returns FALSE.

I tried (7.0).is_integer(), and it returns TRUE. What gives?

答:
If you want more exact decimal arithmetic, use the decimal module. Decimals do not have an is_integer method, but you can compare to the int value.

```<code>>>> from decimal import Decimal as D
>>> 7**5
16807
>>> from decimal import Decimal as D
>>> n = D(16807)**(D(1)/D(5))
>>> n
Decimal('7.000000000000000000000000000')
>>> int(n)
7
>>> n == int(n)
True
</code>```

To show that the test does what you want:

```<code>>>> m = D('7.000000000000000000000000001')
>>> m == int(m)
False
</code>```

Body:
dig = 16807
digcount = len(str(dig))
minroot = dig ** (1 / float(digcount))

print minroot
print minroot.is_integer()

minroot returns as 7.0 as a float, but is_integer returns FALSE.

I tried (7.0).is_integer(), and it returns TRUE. What gives?

Body:
If you want more exact decimal arithmetic, use the decimal module. Decimals do not have an is_integer method, but you can compare to the int value.

>>> from decimal import Decimal as D
>>> 7**5
16807
>>> from decimal import Decimal as D
>>> n = D(16807)**(D(1)/D(5))
>>> n
Decimal('7.000000000000000000000000000')
>>> int(n)
7
>>> n == int(n)
True

To show that the test does what you want:

>>> m = D('7.000000000000000000000000001')
>>> m == int(m)
False


问:
ownCloud 9 Code Signing and .htaccess
I have a modified .htaccess where I added a RewriteCond.

Now I get on every page load:

There were problems with the code integrity check. More information…

What is the right solution to prevent this error message? And of course, I don't want to use the original .htaccess.

答:
This is easy to fix without having to keep integrity check disabled:

1.) Open up the admin area where you can click Rescan, keep that window open (don't click rescan yet)

2.) Edit your config/config.php file, and add this line to it

```<code>'integrity.check.disabled' => true,
</code>```

3.) Click on Rescan in browser window from step 1 (wait for it to complete)

4.) Change the line added to config/config.php from true to false (or remove the line)

Voila! Profit!

Looks like when you disable integrity check and click the rescan, it will re-generate the signature.json file, and after doing that, you can then re-enable integrity check

:)

Title: ownCloud 9 Code Signing and .htaccess

Body:
This is easy to fix without having to keep integrity check disabled:

1.) Open up the admin area where you can click Rescan, keep that window open (don't click rescan yet)

2.) Edit your config/config.php file, and add this line to it

'integrity.check.disabled' => true,

3.) Click on Rescan in browser window from step 1 (wait for it to complete)

4.) Change the line added to config/config.php from true to false (or remove the line)

Voila! Profit!

Looks like when you disable integrity check and click the rescan, it will re-generate the signature.json file, and after doing that, you can then re-enable integrity check

:)


问:
Error for .NETStandard1.6 PCL: "Your project is not referencing the ".NETPlatform,Version=v5.0" framework"
To help reproduce the problem, the following steps are taken to create a .NETStandard1.6 PCL in Visual Studio 2015:

Create a new Class Library(Portable for iOS, Android and Windows).

In its Properties page, click "Target .NET Platform Standard".

Change .NETStandard form .NETStandard1.1 to .NETStandard1.6

Build this empty project.

The following error occurs:

```<code>>C:\Program Files (x86)\MSBuild\Microsoft\NuGet\Microsoft.NuGet.targets(140,5): error : Your project is not referencing the ".NETPlatform,Version=v5.0" framework. Add a reference to ".NETPlatform,Version=v5.0" in the "frameworks" section of your project.json, and then re-run NuGet restore.
</code>```

The following is project.json:

```<code>{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0"
  },
  "frameworks": {
    "netstandard1.6": {}
  }
}
</code>```

Could anyone offer a tip on how to Add a reference to ".NETPlatform,Version=v5.0" in the "frameworks" section?  I tried the following:

"donet5.4": {}

"donet5.0": {}

Neither works.

答:
I had the same error, I added the following in my project.json

```<code>"frameworks": {
            "netstandard1.4": {
                "imports": "portable-net45+win8+wpa81+wp8"
            }
            "netplatform50": {}
  }
</code>```

This worked for me

Body:
To help reproduce the problem, the following steps are taken to create a .NETStandard1.6 PCL in Visual Studio 2015:

Create a new Class Library(Portable for iOS, Android and Windows).

In its Properties page, click "Target .NET Platform Standard".

Change .NETStandard form .NETStandard1.1 to .NETStandard1.6

Build this empty project.

The following error occurs:

>C:\Program Files (x86)\MSBuild\Microsoft\NuGet\Microsoft.NuGet.targets(140,5): error : Your project is not referencing the ".NETPlatform,Version=v5.0" framework. Add a reference to ".NETPlatform,Version=v5.0" in the "frameworks" section of your project.json, and then re-run NuGet restore.

The following is project.json:

{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0"
  },
  "frameworks": {
    "netstandard1.6": {}
  }
}

Could anyone offer a tip on how to Add a reference to ".NETPlatform,Version=v5.0" in the "frameworks" section?  I tried the following:

"donet5.4": {}

"donet5.0": {}

Neither works.

Body:
I had the same error, I added the following in my project.json

"frameworks": {
            "netstandard1.4": {
                "imports": "portable-net45+win8+wpa81+wp8"
            }
            "netplatform50": {}
  }

This worked for me


问:
Java - Multiple fields of same data type in an object
I was practicing inheritance and composition after a lesson and decided to write a small program to try some things out, stumbled upon a problem, I'll show my code, it has 4 classes including the Main.java:

```<code>public class Main {

public static void main(String[] args) {

    Person person1 = new Person("Person1", 170); //"Name", height
    Person person2 = new Person("Person2", 200); //"Name", height

    Bed bed1 = new Bed(160);

    Bedroom bedroom1 = new Bedroom(bed1, person1);

    bedroom1.sleep();
</code>```

```<code>public class Bedroom {

private Bed theBed;
private Person thePerson;

//Constructors

public void sleep() {
    if(thePerson.getHeight() > 180) {
        System.out.println("You are too tall to sleep on this bed.");
    } else {
        theBed.sleepOnBed();
    }
}

//Getters
</code>```

```<code>public class Bed {

private Person thePerson;
private int height;

//Constructor

public void sleepOnBed() {
        System.out.println("You sleep on the bed.");
}

//Getters
</code>```

```<code>public class Person {

private String name;
private int height;

//Constructor

//Getters
</code>```

What I want to do is to use both person1 and person2 in my bedroom1 object in Main.java and then test the sleep() method on both of them but I just can't figure out a way to use it.

I tried things like:

```<code>public class Bedroom {

private Bed theBed;
private Person thePerson1;
private Person thePerson2;

public Bedroom(Bed theBed, Person thePerson1, Person thePerson2) {
    this.theBed = theBed;
    this.thePerson1 = thePerson1;
    this.thePerson2 = thePerson2;
}

public class Main {

public static void main(String[] args) {

    Person person1 = new Person("Person1", 170);
    Person person2 = new Person("Person2", 200);

    Bed bed1 = new Bed(160);

    Bedroom bedroom1 = new Bedroom(bed1, person1, person2);

    bedroom1.sleep();
</code>```

But as you might understand, that lead to nothing. I'm just so tired and can't find any leads online, might be because I use the wrong keywords idk.

I want my program to take multiple objects of data type Person and see if their height matches the conditions to sleep in the bed, that's pretty much it.

答:
You can replace Person with a List of Person objects in the bedroom class and then loop over the array in the sleep method.

```<code>public Bedroom(Bed bed1, List<Person> aListOfPersons)
{
  this.persons = aListOfPersons;
}

public void sleep()
{
  for(Person aPerson : persons)
   {
      //check for each aPerson if he fits in the bed
   }
 }
</code>```

Welcome to Stackoverflow and happy coding!

Body:
I was practicing inheritance and composition after a lesson and decided to write a small program to try some things out, stumbled upon a problem, I'll show my code, it has 4 classes including the Main.java:

public class Main {

public static void main(String[] args) {

    Person person1 = new Person("Person1", 170); //"Name", height
    Person person2 = new Person("Person2", 200); //"Name", height

    Bed bed1 = new Bed(160);

    Bedroom bedroom1 = new Bedroom(bed1, person1);

    bedroom1.sleep();

public class Bedroom {

private Bed theBed;
private Person thePerson;

//Constructors

public void sleep() {
    if(thePerson.getHeight() > 180) {
        System.out.println("You are too tall to sleep on this bed.");
    } else {
        theBed.sleepOnBed();
    }
}

//Getters

public class Bed {

private Person thePerson;
private int height;

//Constructor

public void sleepOnBed() {
        System.out.println("You sleep on the bed.");
}

//Getters

public class Person {

private String name;
private int height;

//Constructor

//Getters

What I want to do is to use both person1 and person2 in my bedroom1 object in Main.java and then test the sleep() method on both of them but I just can't figure out a way to use it.

I tried things like:

public class Bedroom {

private Bed theBed;
private Person thePerson1;
private Person thePerson2;

public Bedroom(Bed theBed, Person thePerson1, Person thePerson2) {
    this.theBed = theBed;
    this.thePerson1 = thePerson1;
    this.thePerson2 = thePerson2;
}

public class Main {

public static void main(String[] args) {

    Person person1 = new Person("Person1", 170);
    Person person2 = new Person("Person2", 200);

    Bed bed1 = new Bed(160);

    Bedroom bedroom1 = new Bedroom(bed1, person1, person2);

    bedroom1.sleep();

But as you might understand, that lead to nothing. I'm just so tired and can't find any leads online, might be because I use the wrong keywords idk.

I want my program to take multiple objects of data type Person and see if their height matches the conditions to sleep in the bed, that's pretty much it.

Body:
You can replace Person with a List of Person objects in the bedroom class and then loop over the array in the sleep method.

public Bedroom(Bed bed1, List<Person> aListOfPersons)
{
  this.persons = aListOfPersons;
}

public void sleep()
{
  for(Person aPerson : persons)
   {
      //check for each aPerson if he fits in the bed
   }
 }

Welcome to Stackoverflow and happy coding!


问:
What's the easiest/best way to profile a math intensive C++ application for speed on Mac OS X?
I am devolping a console math intensive application on Mac OS X. It's implemented in C++, and I'm using no special IDE, just a plain text editor, and GCC for compiling.

Currently, my implementation is quite slow with my data. What is the easiest/best way to profile it to know which parts to optimize?

I use valgrind, at a very basic level, to check for memory leaks. However, I never used it (callgrind) for computing speed profiling. How should I do it? I find callgrind documentation a little confusing/not very newbie friendly. Is there a kcachegrind equivalent for Mac? As far as I know, Maccachegrind only works with xdebug output, and doesn't work with callgrind 3.6.0 output.

Is it better to use valgrind or gprof for profiling? I am not familiar with neither.

Thanks.

答: You should be able to install kcachegrind from Macports (package kdesdk4) and maybe also fink (which I never used myself) and use it just as you do on Linux. I did that in the past and it worked fine.</p>


问:
How can I get the Current Date in a Cognos query expression?
I have a query expression in Cognos where I need to compare a past date to the current date. I don't see one in the functions list and I'm otherwise unsure how to put the query date inside a query object.

How can I use the current date in a query?

答: The best way is to use current_date. This method is data source agnostic and will be converted to the appropriate data source equivalent at run-time.