答:
This can be achived with a simple update with a $set operator </p>

```<code>db.collection.update({"_id" : ObjectId("557914833ac61e518e6103ab")},
{ $set: {"dataValue.default" : [
            "default A",
            "default B"
        ]}})
</code>```

Title: How to update data in mongodb?

Body:
This can be achived with a simple update with a $set operator

db.collection.update({"_id" : ObjectId("557914833ac61e518e6103ab")},
{ $set: {"dataValue.default" : [
            "default A",
            "default B"
        ]}})


来源: stackexchange

问:
Visual Studio Black Background?
I watch a lot of tutorials on the web, expesially ASP.NET tutorials - And constantly notice that everyone seems to have VS set with a black background and yellow/white text?

Why is this?  and how can I set up my version to look like it?

Thanks

答:
In Visual Studio 2017 you can do the following:

Tools -> Options.. -> Environment -> General -> Color theme -> Dark -> OK

ContentLicense: CC BY-SA 2.5

Title: Visual Studio Black Background?

ContentLicense: CC BY-SA 3.0


问:
Spring Boot - Key Store Password set in Code
Spring Boot Version: 1.5.4.RELEASE

I'm currently having an issue with setting my server.ssl.key-store-password within the code of my Spring Boot application. We store our passwords in a vault, and I was previously passing it in via a -D property. This, however, isn't an ideal solution for us.

The solution seemed simple, and below is what I did:

```<code>@Bean
public ServletContextInitializer initializer() {
    final String keyStorePassword;
    // ... Get Password
    return servletContext -> servletContext.setInitParameter("server.ssl.key-store-password", keyStorePassword);
}
</code>```

According to the Spring Boot Documentation this should be fine, as the ServletConfig is loaded before the application.properties.

Unfortunately, Tomcat refuses to start with the server.ssl.key-store-password set in this way. From what I can see, the AbstractNestablePropertyAccessor constructs an org.springframework.boot.context.embedded.Ssl object which is fed to Tomcat, and used to construct the keystore. This is done during SpringApplication.run(), which is obviously prior to construction of the ServletConfig bean.

So it seems that I need to 'refresh' the context (which from what I understand is destroying/recreating it), or find another approach. I could set the property using something like:

```<code>public static void main(String[] args) {
    String keyStorePassword = getKeystorePassword();
    HashMap<String, Object> props = new HashMap<>();
    props.put("server.ssl.key-store-password", keyStorePassword);
    new SpringApplicationBuilder()
            .sources(TesterApplication.class)
            .properties(props)
            .run(args);
}
</code>```

This has its own problems though. I was thinking of storing the 'label' for the vault password in my application.yml, but if I do so, then I don't have access to that label before Spring has started (without manually parsing the application.yml, which poses its own problems with multiple profiles).

Has anyone else encountered a solution to this issue? Perhaps my approach is wrong, and there's a simpler way of doing things.

答:
Right, figured it out. Was on the wrong track. What I should have done was the following:

```<code>@Component
public class KeystoreInit {

    private final Environment environment;

    @Autowired
    public KeystoreInit(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public ServerProperties serverProperties() {
        final ServerProperties serverProperties = new ServerProperties();
        final Ssl ssl = new Ssl();
        final String keystorePassword = getKeystorePassword();
        ssl.setKeyPassword(keystorePassword);
        System.setProperty("server.ssl.key-store-password", keystorePassword);
        serverProperties.setSsl(ssl);
        return serverProperties;
    }

    private String getKeystorePassword() {
        // ...
    }

}
</code>```

The idea here is that we're creating the initial ServerProperties bean. This bean is then loaded instead of a fresh ServerProperties, so our Ssl with the keystore password is set there already. This isn't overridden since we don't set server.ssl.key-store-password in our application.yml.

We @Autowire the Environment so that we can access out server.ssl.key-store-label property (which I had previously created), use that to load our actual server.ssl.key-store-password property, and then set that via System properties so that it can be accessed elsewhere in the application.

Body:
Spring Boot Version: 1.5.4.RELEASE

I'm currently having an issue with setting my server.ssl.key-store-password within the code of my Spring Boot application. We store our passwords in a vault, and I was previously passing it in via a -D property. This, however, isn't an ideal solution for us.

The solution seemed simple, and below is what I did:

@Bean
public ServletContextInitializer initializer() {
    final String keyStorePassword;
    // ... Get Password
    return servletContext -> servletContext.setInitParameter("server.ssl.key-store-password", keyStorePassword);
}

According to the Spring Boot Documentation this should be fine, as the ServletConfig is loaded before the application.properties.

Unfortunately, Tomcat refuses to start with the server.ssl.key-store-password set in this way. From what I can see, the AbstractNestablePropertyAccessor constructs an org.springframework.boot.context.embedded.Ssl object which is fed to Tomcat, and used to construct the keystore. This is done during SpringApplication.run(), which is obviously prior to construction of the ServletConfig bean.

So it seems that I need to 'refresh' the context (which from what I understand is destroying/recreating it), or find another approach. I could set the property using something like:

public static void main(String[] args) {
    String keyStorePassword = getKeystorePassword();
    HashMap<String, Object> props = new HashMap<>();
    props.put("server.ssl.key-store-password", keyStorePassword);
    new SpringApplicationBuilder()
            .sources(TesterApplication.class)
            .properties(props)
            .run(args);
}

This has its own problems though. I was thinking of storing the 'label' for the vault password in my application.yml, but if I do so, then I don't have access to that label before Spring has started (without manually parsing the application.yml, which poses its own problems with multiple profiles).

Has anyone else encountered a solution to this issue? Perhaps my approach is wrong, and there's a simpler way of doing things.

Body:
Right, figured it out. Was on the wrong track. What I should have done was the following:

@Component
public class KeystoreInit {

    private final Environment environment;

    @Autowired
    public KeystoreInit(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public ServerProperties serverProperties() {
        final ServerProperties serverProperties = new ServerProperties();
        final Ssl ssl = new Ssl();
        final String keystorePassword = getKeystorePassword();
        ssl.setKeyPassword(keystorePassword);
        System.setProperty("server.ssl.key-store-password", keystorePassword);
        serverProperties.setSsl(ssl);
        return serverProperties;
    }

    private String getKeystorePassword() {
        // ...
    }

}

The idea here is that we're creating the initial ServerProperties bean. This bean is then loaded instead of a fresh ServerProperties, so our Ssl with the keystore password is set there already. This isn't overridden since we don't set server.ssl.key-store-password in our application.yml.

We @Autowire the Environment so that we can access out server.ssl.key-store-label property (which I had previously created), use that to load our actual server.ssl.key-store-password property, and then set that via System properties so that it can be accessed elsewhere in the application.


问:
Java cooldown system
I've been trying to make a cooldown system in java given three variables,

the cooldown time, for example 100 seconds,

the click timestamp(when it was last clicked)

the current timestamp.

I made it work before but it looks very complicated, I was wondering if there is a better way to do it.

My code to check if the click is on cooldown or not:

```<code>private boolean onCooldown(String playerUUID, int npcId, int cooldown) {
    boolean toReturn = false;
    try {
        String timeStamp = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss").format(Calendar.getInstance().getTime());
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
        Date savedTime;
        Date nowTime;
        String savedString = database.getTime(playerUUID, npcId);
        nowTime = df.parse(timeStamp);
        savedTime = df.parse(savedString);
        long diff = nowTime.getTime() - savedTime.getTime();
        long savedSeconds = diff / 1000 % 60;
        long savedMinutes = diff / (60 * 1000) % 60;
        long nowSeconds = cooldown  % 60;
        long nowMinutes = cooldown / 60 % 60;
        if (!((savedMinutes >= nowMinutes) && (savedSeconds >= nowSeconds))) {
            toReturn = true;
        }
    } catch (Exception e) {
        toReturn = false;
    }
    return toReturn;
}
</code>```

Is there a better or easier way than this?

Cheers.

答:
I'd recommend using a HashMap that stores the player's UUID and the current timestamp. Within the method you can then check if the map contains the player's key and if so check if the value stored and your desired cooldown is less/greater than the current time.

As Craigr8806 stated in the comments, I'd recommend using System.nanoTime() for the timestamps.

Title: Java cooldown system

Body:
I've been trying to make a cooldown system in java given three variables,

the cooldown time, for example 100 seconds,

the click timestamp(when it was last clicked)

the current timestamp.

I made it work before but it looks very complicated, I was wondering if there is a better way to do it.

My code to check if the click is on cooldown or not:

private boolean onCooldown(String playerUUID, int npcId, int cooldown) {
    boolean toReturn = false;
    try {
        String timeStamp = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss").format(Calendar.getInstance().getTime());
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
        Date savedTime;
        Date nowTime;
        String savedString = database.getTime(playerUUID, npcId);
        nowTime = df.parse(timeStamp);
        savedTime = df.parse(savedString);
        long diff = nowTime.getTime() - savedTime.getTime();
        long savedSeconds = diff / 1000 % 60;
        long savedMinutes = diff / (60 * 1000) % 60;
        long nowSeconds = cooldown  % 60;
        long nowMinutes = cooldown / 60 % 60;
        if (!((savedMinutes >= nowMinutes) && (savedSeconds >= nowSeconds))) {
            toReturn = true;
        }
    } catch (Exception e) {
        toReturn = false;
    }
    return toReturn;
}

Is there a better or easier way than this?

Cheers.


问:
How to store/query ledger data in couchdb or any other nosql DB in hyperledger
Can we store the distributed ledger data in some nosql db whenever new transaction happens.If so what are steps involved in this job.

Once we stored the data into nosql then how can we able to query the data from peers.

答:
You need to implement Ledger Interface with nosql backend of your choice. The interaction with db implemented on chaincode level base on ChaincodeStubInterface API.

Just to note, that Hyperledger Fabric has solution based on couchdb, so instead of plugging your own, you might consider to use it.


问:
Cloning a Class Definition (PCL)
The Question:
Is this possible to clone a class definition using reflection? I am not talking about shallow cloning nor deep cloning. I am talking about definition cloning. I want to have a class with a static variable not shared between all instances, but just the definition I created. And I (or the library) need to be able to create an instance from this class later on.

The Problem:
You see, I need this because of the following scenario,

There is this library that expects me to provides it with a type having a certain static method. However in my case this static method needs to compare two value one from a non static field of another type. This makes it impossible to pass the instance that has the information to the class because it is not yet initialized. Check out the following example of the situation:

```<code>class MasterClass
{
    public int SomeInfo {get; set;} = 10;
    public void PeresentClass()
    {
        SOMELIBRARY.RegisterType(typeof(StaticClass));
    }
}
class StaticClass
{
    public static bool CanCreate(int someVar)
    {
        // I need to compare someVar with the SomeInfo property of MasterClass instance that presented this type to the SOMELIBRARY.
    }
    public StaticClass()
    {
        // Something irrelevant
    }
}
</code>```

In the above example I have no control over the SOMELIBRARY and the way they decided to write the code. But it seems that they some how want to call the CanCreate method first and then create an instance of class if it meets the requirements.

However, for CanCreate to works correctly I need to have access to the instance of the class presented the StaticClass to the SOMELIBRARY in first place. And I cant make MasterClass static because there are more than one instance of this class active at every time.

Only way I could think of was to redefine a new StaticClass with a static field pointing to the MasterClass that defined it (or cloned the definition). However my knowledge of reflection failed me to do so yet. So here I am asking it this is even possible? And I really would like to be able to do it under PCL profiles.

Real World:
Just for more information, I am actually talking about XAMARIN.iOS and NSUrlProtocol class, specially CanInitWithRequest method.

Possible Solution: With more thinking, I found that another way to solve this problem is to make the StaticClass generic; Doing so allows me to have a static variable per type definition. However, for this to work I need to be able to create unique and possibly empty types at run-time. Is this possible?

XAMARIN.iOS: Unfortunately Reflection.Emit is not available on iOS so for now I don't believe that this is even possible in any way. Still waiting for your comments on the situation tho.

https://developer.xamarin.com/guides/ios/advanced_topics/limitations/#System.Reflection.Emit

答:
After a lot of searching, I found no way to create even an empty type in C# under Xamarin.iOS and so as the result, I had to change my code to fit the expectations of the Apple API.

In my case, I ended up keeping a list of all instances of MasterClass to use in the StaticClass; both the constructor and the static method go throghe the list and match the desired MasterClass with the request. There is a risk here that by doing so you end up having a memory leak because instances of MasterClass will never get collected, but in my case, this wasn't a concern.

Title: Cloning a Class Definition (PCL)

Body:
The Question:
Is this possible to clone a class definition using reflection? I am not talking about shallow cloning nor deep cloning. I am talking about definition cloning. I want to have a class with a static variable not shared between all instances, but just the definition I created. And I (or the library) need to be able to create an instance from this class later on.

The Problem:
You see, I need this because of the following scenario,

There is this library that expects me to provides it with a type having a certain static method. However in my case this static method needs to compare two value one from a non static field of another type. This makes it impossible to pass the instance that has the information to the class because it is not yet initialized. Check out the following example of the situation:

class MasterClass
{
    public int SomeInfo {get; set;} = 10;
    public void PeresentClass()
    {
        SOMELIBRARY.RegisterType(typeof(StaticClass));
    }
}
class StaticClass
{
    public static bool CanCreate(int someVar)
    {
        // I need to compare someVar with the SomeInfo property of MasterClass instance that presented this type to the SOMELIBRARY.
    }
    public StaticClass()
    {
        // Something irrelevant
    }
}

In the above example I have no control over the SOMELIBRARY and the way they decided to write the code. But it seems that they some how want to call the CanCreate method first and then create an instance of class if it meets the requirements.

However, for CanCreate to works correctly I need to have access to the instance of the class presented the StaticClass to the SOMELIBRARY in first place. And I cant make MasterClass static because there are more than one instance of this class active at every time.

Only way I could think of was to redefine a new StaticClass with a static field pointing to the MasterClass that defined it (or cloned the definition). However my knowledge of reflection failed me to do so yet. So here I am asking it this is even possible? And I really would like to be able to do it under PCL profiles.

Real World:
Just for more information, I am actually talking about XAMARIN.iOS and NSUrlProtocol class, specially CanInitWithRequest method.

Possible Solution: With more thinking, I found that another way to solve this problem is to make the StaticClass generic; Doing so allows me to have a static variable per type definition. However, for this to work I need to be able to create unique and possibly empty types at run-time. Is this possible?

XAMARIN.iOS: Unfortunately Reflection.Emit is not available on iOS so for now I don't believe that this is even possible in any way. Still waiting for your comments on the situation tho.

https://developer.xamarin.com/guides/ios/advanced_topics/limitations/#System.Reflection.Emit


问:
Error in asp.net c# code (mysql database connection)
My code is to update a record if it already exists in database else insert as a new record.

My code is as follows:

```<code>protected void Button3_Click(object sender, EventArgs e)
    {

        OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
        MyConnection.Open();
        String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
        OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
        MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
        MyCmd.Parameters.AddWithValue("", TextBox3.Text);
        using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
        {
            //**
            if (MyReader4.Read())
            {

                    String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
                    OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
                    MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
                    MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
                    MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
                    MyCmd1.ExecuteNonQuery();
                }

            else
            {

                // set the SQL string
                String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
                "VALUES (?,?,?)";

                // Create the Command and set its properties
                OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
                objCmd.Parameters.AddWithValue("", HiddenField4.Value);
                objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
                objCmd.Parameters.AddWithValue("", TextBox3.Text);

                // execute the command
                objCmd.ExecuteNonQuery();

            }

        }
    }
</code>```

I am getting the error as:

```<code>ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009','      &' at line 1
</code>```

The datatype for fields in table temp_save are:

```<code>fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)
</code>```

Please help me to resolve my error.

答:
order is a reserved word. For a complete list of Reserved Words, please review this document.

You can wrap it in back-ticks i.e.
(on my keyboard a back tick is under the ~ key)

```<code>INSERT INTO temp_save (fil_no,`order`,orderdate)....
</code>```

Body:
My code is to update a record if it already exists in database else insert as a new record.

My code is as follows:

protected void Button3_Click(object sender, EventArgs e)
    {

        OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
        MyConnection.Open();
        String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
        OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
        MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
        MyCmd.Parameters.AddWithValue("", TextBox3.Text);
        using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
        {
            //**
            if (MyReader4.Read())
            {

                    String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
                    OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
                    MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
                    MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
                    MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
                    MyCmd1.ExecuteNonQuery();
                }

            else
            {

                // set the SQL string
                String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
                "VALUES (?,?,?)";

                // Create the Command and set its properties
                OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
                objCmd.Parameters.AddWithValue("", HiddenField4.Value);
                objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
                objCmd.Parameters.AddWithValue("", TextBox3.Text);

                // execute the command
                objCmd.ExecuteNonQuery();

            }

        }
    }

I am getting the error as:

ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009','      &' at line 1

The datatype for fields in table temp_save are:

fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)

Please help me to resolve my error.

Body:
order is a reserved word. For a complete list of Reserved Words, please review this document.

You can wrap it in back-ticks i.e.
(on my keyboard a back tick is under the ~ key)

INSERT INTO temp_save (fil_no,`order`,orderdate)....


问:
Can xcodebuild manage automatic signing?
SUMMARY:

If you open a project in Xcode 8 with "Automatically manage signing" enabled and a new bundle ID, it will automatically create and download a provisioning profile for it. But how can I make the same thing happen with xcodebuild, so I can use it on a remote build server?

DETAILS:

I'm trying to build a Cordova app on a Mac. Cordova configures the Xcode project to use "Automatically manage signing", so I'm trying to use that.

I change the bundle ID often, so I want Cordova to be able to build it with a new bundle ID, that hasn't been used before.

But when I run cordova build ios --release --device --buildConfig build.json, I get a return code 65 and the following error:

```<code>Check dependencies
No profiles for 'com.my.bundle.id' were found:  Xcode couldn't find a provisioning profile matching 'com.my.bundle.id'.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

The following build commands failed:
    Check dependencies
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/cordova-project/platforms/ios/cordova/build-debug.xcconfig,-workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,MyApp.xcarchive,archive,CONFIGURATION_BUILD_DIR=/cordova-project/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/cordova-project/platforms/ios/build/sharedpch
</code>```

(I can manually run that xcodebuild command and get the same error, so it's probably not a Cordova issue.)

My build.json file looks like this:

```<code>{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "enterprise"
        }
    }
}
</code>```

I'm using cordova 7.0.1, cordova-ios 4.4.0, Xcode 8.3.3, and MacOS 10.12.5. I have an Apple Enterprise account.

WHAT I TRIED:

If I open the generated project in Xcode, it fixes the automatic signing, and from then on I can run cordova successfully with that bundle ID. But if I try to run it with a different bundle ID, it will fail again.

I tried using security unlock-keychain ~/Library/Keychains/login.keychain-db first, since that's worked in the past, but it didn't help.

I also tried opening my private signing key in Keychain Access and setting it to "Allow all applications to access this item", without any luck.

I get the same error regardless of whether I pass --debug or --release to cordova.

答:
Answer is yes. What I used and what I can confirm is working and it is great:

https://fastlane.tools/

You can set up everything to be automatic:

Signing keys

Taking screenshots

Uploading on iTunes

and many other things

In background it is using  xcodebuild command line. I was skeptic that something like this is possible, but just set up, start and enjoy.

Body:
SUMMARY:

If you open a project in Xcode 8 with "Automatically manage signing" enabled and a new bundle ID, it will automatically create and download a provisioning profile for it. But how can I make the same thing happen with xcodebuild, so I can use it on a remote build server?

DETAILS:

I'm trying to build a Cordova app on a Mac. Cordova configures the Xcode project to use "Automatically manage signing", so I'm trying to use that.

I change the bundle ID often, so I want Cordova to be able to build it with a new bundle ID, that hasn't been used before.

But when I run cordova build ios --release --device --buildConfig build.json, I get a return code 65 and the following error:

Check dependencies
No profiles for 'com.my.bundle.id' were found:  Xcode couldn't find a provisioning profile matching 'com.my.bundle.id'.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

The following build commands failed:
    Check dependencies
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/cordova-project/platforms/ios/cordova/build-debug.xcconfig,-workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,MyApp.xcarchive,archive,CONFIGURATION_BUILD_DIR=/cordova-project/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/cordova-project/platforms/ios/build/sharedpch

(I can manually run that xcodebuild command and get the same error, so it's probably not a Cordova issue.)

My build.json file looks like this:

{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "enterprise"
        }
    }
}

I'm using cordova 7.0.1, cordova-ios 4.4.0, Xcode 8.3.3, and MacOS 10.12.5. I have an Apple Enterprise account.

WHAT I TRIED:

If I open the generated project in Xcode, it fixes the automatic signing, and from then on I can run cordova successfully with that bundle ID. But if I try to run it with a different bundle ID, it will fail again.

I tried using security unlock-keychain ~/Library/Keychains/login.keychain-db first, since that's worked in the past, but it didn't help.

I also tried opening my private signing key in Keychain Access and setting it to "Allow all applications to access this item", without any luck.

I get the same error regardless of whether I pass --debug or --release to cordova.


问:
Server side rendering with Apollo: getaddrinfo ENOTFOUND
I'm running Apollo/React with Express and I'm trying to get server side rendering to work. The Apollo docs suggest the following initialisation code for connecting to the API server:

```<code>app.use((req, res) => {
  match({ routes, location: req.originalUrl }, (error, redirectLocation, renderProps) => {
    const client = new ApolloClient({
      ssrMode: true,
      networkInterface: createNetworkInterface({
        uri: 'http://localhost:3000', // Instead of 3010
        opts: {
          credentials: 'same-origin',
          headers: {
            cookie: req.header('Cookie'),
          },
        },
      }),
    });

    const app = (
      <ApolloProvider client={client}>
        <RouterContext {...renderProps} />
      </ApolloProvider>
    );

    getDataFromTree(app).then(() => {
      const content = ReactDOM.renderToString(app);
      const initialState = {[client.reduxRootKey]: client.getInitialState()  };
      const html = <Html content={content} state={initialState} />;
      res.status(200);
      res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`);
      res.end();
    });

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

which uses the match() function from React Router v3 (as evidenced by package.json in the "GitHunt" example linked from the docs). I'm using React Router v4 from which match() is absent, so I refactored the code as follows, using renderRoutes() from the react-router-config package.

```<code>app.use((req, res) => {
  const client = new ApolloClient(/* Same as above */)

  const context = {}

  const app = (
    <ApolloProvider client={client}>
      <StaticRouter context={context} location={req.originalUrl}>
        { renderRoutes(routes) }
      </StaticRouter>
    </ApolloProvider>
  )

  getDataFromTree(app).then(/* Same as above */)
})
</code>```

My understanding is that <StaticRouter> obviates the use of match(). However react-router-config provides a matchRoutes() function which seems to provide a similar functionality (albeit without the callback) if needed.

When I visit http://localhost:3000, the page loads as expected and I can follow links to subdirectories (e.g. http://localhost:3000/folder). When I try to directly load a subdirectory by typing in the name in the address bar, my browser keeps waiting for the server to respond. After about six seconds, Terminal shows one of the following errors (not sure what causes the error to change on subsequent tries):

(node:1938) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: Network error: request to
  http://localhost:3000 failed, reason: getaddrinfo ENOTFOUND localhost
  localhost:3000

or

(node:8691) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: Network error: request to
  http://localhost:3000 failed, reason: socket hang up

I've been struggling with this problem for a few hours now, but can't seem to figure it out. The solution to a similar problem seems unrelated to this case. Any help will be much appreciated!

Further information

If I don't kill the nodemon server, after some time I get thousands of the following errors:

POST / - - ms - -

(node:1938) UnhandledPromiseRejectionWarning:
  Unhandled promise rejection (rejection id: 4443): Error: Network
  error: request to http://localhost:3000 failed, reason: socket hang up

If I do kill the server, however, I immediately get this error instead:

/Users/.../node_modules/duplexer/index.js:31

```<code>writer.on("drain", function() {

      ^
</code>```

TypeError: Cannot read property 'on' of undefined

at duplex (/Users/.../node_modules/duplexer/index.js:31:11)

at Object.module.exports (/Users/.../node_modules/stream-combiner/index.js:8:17)

at childrenOfPid (/Users/.../node_modules/ps-tree/index.js:50:6)

at kill (/Users/.../node_modules/nodemon/lib/monitor/run.js:271:7)

at Bus.onQuit (/Users/.../node_modules/nodemon/lib/monitor/run.js:327:5)

at emitNone (events.js:91:20)

at Bus.emit (events.js:188:7)

at process. (/Users/.../node_modules/nodemon/lib/monitor/run.js:349:9)

at Object.onceWrapper (events.js:293:19)

at emitNone (events.js:86:13)

Also, port 3000 is correct. If I change the number, I get a different error instead:

(node:2056) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: Network error: request to
  http://localhost:3010 failed, reason: connect ECONNREFUSED
  127.0.0.1:3010

答:
Are you running your server / project inside a container / containers. I had the same issue as this and ended up doing the following to fix it.

const networkInterface = createNetworkInterface({
   uri: process.browser
         ? 'http://0.0.0.0:1111/graphql'
         : 'http://my-docker-container-name:8080/graphql'
})

I have an internal docker network created for my containers in my docker-compose.yml, which allows the containers to communicate with each other, however the browser communicates to the GQL server on a different URL, causing the issue you described on SSR the getaddrinfo ENOTFOUND, so although it was working client side, on the SSR it would fail.

I am using nextJS framework which gives the ability to detect the browser or SSR, i'm sure you could do the same outside of nextJS.

Body:
I'm running Apollo/React with Express and I'm trying to get server side rendering to work. The Apollo docs suggest the following initialisation code for connecting to the API server:

app.use((req, res) => {
  match({ routes, location: req.originalUrl }, (error, redirectLocation, renderProps) => {
    const client = new ApolloClient({
      ssrMode: true,
      networkInterface: createNetworkInterface({
        uri: 'http://localhost:3000', // Instead of 3010
        opts: {
          credentials: 'same-origin',
          headers: {
            cookie: req.header('Cookie'),
          },
        },
      }),
    });

    const app = (
      <ApolloProvider client={client}>
        <RouterContext {...renderProps} />
      </ApolloProvider>
    );

    getDataFromTree(app).then(() => {
      const content = ReactDOM.renderToString(app);
      const initialState = {[client.reduxRootKey]: client.getInitialState()  };
      const html = ;
      res.status(200);
      res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`);
      res.end();
    });

  });
});

which uses the match() function from React Router v3 (as evidenced by package.json in the "GitHunt" example linked from the docs). I'm using React Router v4 from which match() is absent, so I refactored the code as follows, using renderRoutes() from the react-router-config package.

app.use((req, res) => {
  const client = new ApolloClient(/* Same as above */)

  const context = {}

  const app = (
    <ApolloProvider client={client}>
      <StaticRouter context={context} location={req.originalUrl}>
        { renderRoutes(routes) }
      </StaticRouter>
    </ApolloProvider>
  )

  getDataFromTree(app).then(/* Same as above */)
})

My understanding is that <StaticRouter> obviates the use of match(). However react-router-config provides a matchRoutes() function which seems to provide a similar functionality (albeit without the callback) if needed.

When I visit http://localhost:3000, the page loads as expected and I can follow links to subdirectories (e.g. http://localhost:3000/folder). When I try to directly load a subdirectory by typing in the name in the address bar, my browser keeps waiting for the server to respond. After about six seconds, Terminal shows one of the following errors (not sure what causes the error to change on subsequent tries):

(node:1938) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: Network error: request to
  http://localhost:3000 failed, reason: getaddrinfo ENOTFOUND localhost
  localhost:3000

or

(node:8691) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: Network error: request to
  http://localhost:3000 failed, reason: socket hang up

I've been struggling with this problem for a few hours now, but can't seem to figure it out. The solution to a similar problem seems unrelated to this case. Any help will be much appreciated!

Further information

If I don't kill the nodemon server, after some time I get thousands of the following errors:

POST / - - ms - -

(node:1938) UnhandledPromiseRejectionWarning:
  Unhandled promise rejection (rejection id: 4443): Error: Network
  error: request to http://localhost:3000 failed, reason: socket hang up

If I do kill the server, however, I immediately get this error instead:

/Users/.../node_modules/duplexer/index.js:31

writer.on("drain", function() {

      ^

TypeError: Cannot read property 'on' of undefined

at duplex (/Users/.../node_modules/duplexer/index.js:31:11)

at Object.module.exports (/Users/.../node_modules/stream-combiner/index.js:8:17)

at childrenOfPid (/Users/.../node_modules/ps-tree/index.js:50:6)

at kill (/Users/.../node_modules/nodemon/lib/monitor/run.js:271:7)

at Bus.onQuit (/Users/.../node_modules/nodemon/lib/monitor/run.js:327:5)

at emitNone (events.js:91:20)

at Bus.emit (events.js:188:7)

at process. (/Users/.../node_modules/nodemon/lib/monitor/run.js:349:9)

at Object.onceWrapper (events.js:293:19)

at emitNone (events.js:86:13)

Also, port 3000 is correct. If I change the number, I get a different error instead:

(node:2056) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection (rejection id: 1): Error: Network error: request to
  http://localhost:3010 failed, reason: connect ECONNREFUSED
  127.0.0.1:3010


问:
jquery multiselect reload
How can I add or remove options in JQuery UI Multiselect ? I am initializing the multiselect on page load and I need to remove existing values and add new values based on another selection. I am initializing the multiselect on page load using:

```<code>$("#multipleselectboxId").multiselect();
</code>```

After that, I am adding values to the multiple drop down using jQuery append() and remove() methods which are working fine with original dropdown but in the multiselect are not getting reflected.

Can anyone help with this?

答:
```<code>var valArr = ["1", "2"],
         i = 0,
      size = valArr.length,
  $options = $('#MySelect option');

for (i; i < size; i++) {
  $options.filter('[value="' + valArr[i] + '"]').prop('selected', true);
}

$('#MySelect').multiselect('reload');
</code>```

1.valArr is values of select Options

2.for loop to set selected to matched option based on valArr

3.our changes is only in hidden select element

4.to change in multiselect generated elements we need to reload

5.every pluggin may have different name to reload eg:update,refresh

Title: jquery multiselect reload

Body:
How can I add or remove options in JQuery UI Multiselect ? I am initializing the multiselect on page load and I need to remove existing values and add new values based on another selection. I am initializing the multiselect on page load using:

$("#multipleselectboxId").multiselect();

After that, I am adding values to the multiple drop down using jQuery append() and remove() methods which are working fine with original dropdown but in the multiselect are not getting reflected.

Can anyone help with this?

Body:
var valArr = ["1", "2"],
         i = 0,
      size = valArr.length,
  $options = $('#MySelect option');

for (i; i < size; i++) {
  $options.filter('[value="' + valArr[i] + '"]').prop('selected', true);
}

$('#MySelect').multiselect('reload');

1.valArr is values of select Options

2.for loop to set selected to matched option based on valArr

3.our changes is only in hidden select element

4.to change in multiselect generated elements we need to reload

5.every pluggin may have different name to reload eg:update,refresh


问:
selecting row in a dataframe according to defined values
I have an annual record of temperature. I need to select special row (days) with five rows before them (to take the mean of five days) and then take the mean of the selected groups. here is my data frame and the following code that i applied but didn't work.</p>

```<code>Day  T.m
1      22
2      21
3      34
4      28
5      14
6      7
7      12
8      22
9      11
10     12
11     14
12     3
13     4
14     11
15     16

a <- c(8, 12,14)

apply(DF [c((a-5):a),2], 1, mean)
</code>```

Body:
I have an annual record of temperature. I need to select special row (days) with five rows before them (to take the mean of five days) and then take the mean of the selected groups. here is my data frame and the following code that i applied but didn't work.

Day  T.m
1      22
2      21
3      34
4      28
5      14
6      7
7      12
8      22
9      11
10     12
11     14
12     3
13     4
14     11
15     16

a <- c(8, 12,14)

apply(DF [c((a-5):a),2], 1, mean)

Body:
We can use mapply

mapply(function(x, y) mean(DF[[2]][x:y]), a-5, a)
#[1] 19.500000 12.333333  9.166667

Or a vectorized approach would be

tapply(DF[[2]][rep(a-5 , each = 6) + 0:5], rep(1:3, each = 6), FUN = mean)
#        1         2         3
#19.500000 12.333333  9.166667


问:
asp.net mvc2: Why to minimize the code in controllers?
I heard a bit about we should keep the code in controllers as less as possible. So where do we put those code?</p>

答:
This will depend on what code you are talking about. For example if you are talking about validation, this should go into the model, if you are talking about data access this should also go into a repository or the model (personally I prefer repository), if you are talking about a business logic this should go into a service, so that all that's left into the controller is to call this thing and pass the result to the view.

I would recommend you watching this video presentation about how to put your controllers on a diet from Jimmy Bogard.


问:
LINQ and column with Null
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

```<code>MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

答:
You mentioned that A is nullable, so I assume in your definition you have something like:

```<code>int? A { get; set; }
</code>```

or something similar. Note the(?) to make the property nullable. If that's set, then you can do:

```<code>var query = from  tbl in dt.AsEnumerable()
            where tbl?.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

Also note the (?) before property A. Another way is to use a ternary operation approach, for example:

```<code>var query = from  tbl in dt.AsEnumerable()
            where tbl.A == null ? true : tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

If property A is null, it resolves to true and skips to the next condition.

Title: LINQ and column with Null

Body:
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

Body:
You mentioned that A is nullable, so I assume in your definition you have something like:

int? A { get; set; }

or something similar. Note the(?) to make the property nullable. If that's set, then you can do:

var query = from  tbl in dt.AsEnumerable()
            where tbl?.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };

Also note the (?) before property A. Another way is to use a ternary operation approach, for example:

var query = from  tbl in dt.AsEnumerable()
            where tbl.A == null ? true : tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };

If property A is null, it resolves to true and skips to the next condition.


问:
What's the reason that don't use staging buffer?
Recently I was wondering for a game, if there are many models and each one of them needs vertex buffer to draw. Like below three options, which one is most efficient?

Create several small vertex buffers and update it with vkMapMemory before draw those models.

Create several small vertex buffers and use staging buffer to update.

Create several big enough vertex buffers and use it.

答:
You're conflating two different issues... memory management and memory updates.

For memory management, conventional wisdom for both OpenGL and Vulkan is that you want to make few allocations in the underlying API and do memory management yourself, so that you can store multiple vertex data sets in a single buffer at different offsets.  This is critical for being able to do indirect drawing, where you execute a single command to render many models.  Because you can't change the bindings within that command you can only render models that are all within a single vertex buffer.

For memory updates, you need to keep in mind that not all memory can necessarily be mapped using vkMapMemory.  Often only system memory can be mapped, while GPU local memory cannot.  The best performance is going to come when the vertex data is on the GPU, so the best practice is to use a staging buffer composed of mappable memory, and then use it to transfer to the real buffer of device local memory.


问:
How to disable the next ng-select items, based on previous selected items in Angular?
For example: I have select with 4 items. When I selected first item in select, it will show second select with the same items as in previous, but item which I selected will be disabled. And the same for the next selects, until it remains 1 available item for select.

P.s. the every next one select, should automatically will be selected with first available item.

I attached snipper below, where I visually showed, what the flow I want to achieve.

var app = angular.module('ngoptions', []);

app.controller('MainCtrl', function($scope) {

  $scope.rules1 = [{
    type: 'first item',
    value: 'first item',
    disabled: false
  }, {
    type: 'second item',
    value: 'second item',
    disabled: false
  }, {
    type: 'third item',
    value: 'third item',
    disabled: false
  }, {
    type: 'fourth item',
    value: 'fourth item',
    disabled: false
  }];

  $scope.rules2 = [{
    type: 'first item',
    value: 'first item',
    disabled: true
  }, {
    type: 'second item',
    value: 'second item',
    disabled: false
  }, {
    type: 'third item',
    value: 'third item',
    disabled: false
  }, {
    type: 'fourth item',
    value: 'fourth item',
    disabled: false
  }];

  $scope.rules3 = [{
    type: 'first item',
    value: 'first item',
    disabled: true
  }, {
    type: 'second item',
    value: 'second item',
    disabled: true
  }, {
    type: 'third item',
    value: 'third item',
    disabled: false
  }, {
    type: 'fourth item',
    value: 'fourth item',
    disabled: false
  }];
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Put your css in here */</code>```

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />

  <select ng-model="item" ng-options="item.type as item.value disable when item.disabled for item in rules1">
    <option value="" style="display: none" selected="selected">Select When
    </option>
  </select>

  after selecting first select, first item:

  <select ng-model="item1" ng-options="item.type as item.value disable when item.disabled for item in rules2">
    <option value="" style="display: none" selected="selected">Select When
    </option>
  </select>

  after selecting second select, second item:

        <select ng-model="item2" ng-options="item.type as item.value disable when item.disabled for item in rules3">
    <option value="" style="display: none" selected="selected">Select When
    </option>
  </select>

```

Please help me with this. Will be greatful!

答:
Since your rule1, rule2, and rule3 arrays are the exact same, I'd first just make this into one: rules. If not, you'd need to make sure three identical arrays are updated in the same way.

ng-change usually works pretty great with these types of inputs. When you select an option, it will fire that change event, and you can make custom functions to handle it.

Side note, you have your ng-model named the same as your item in your loop, but these aren't the same thing.

```<code><select ng-model="item" ng-options="item.type as item.value disable when item.disabled for item in rules" data-ng-change="select(item)">
    <option value="" style="display: none" selected="selected">Select When
    </option>
</select>
</code>```

I added that select function that passes in the input's model (the value of the input option you've selected).

Then in your controller, you could have some type of function to handle the change, like:

```<code>scope.select = function (value) {

    if (!value) { return; }

    for (var i=0;i<$scope.rules.length;++i) {
      if ($scope.rules[i].value === value) {
        $scope.rules[i].disabled = true;
      }
    }
};
</code>```

http://jsbin.com/tomoma/edit?html,js,console,output

Body:
For example: I have select with 4 items. When I selected first item in select, it will show second select with the same items as in previous, but item which I selected will be disabled. And the same for the next selects, until it remains 1 available item for select.

P.s. the every next one select, should automatically will be selected with first available item.

I attached snipper below, where I visually showed, what the flow I want to achieve.

var app = angular.module('ngoptions', []);

app.controller('MainCtrl', function($scope) {

  $scope.rules1 = [{
    type: 'first item',
    value: 'first item',
    disabled: false
  }, {
    type: 'second item',
    value: 'second item',
    disabled: false
  }, {
    type: 'third item',
    value: 'third item',
    disabled: false
  }, {
    type: 'fourth item',
    value: 'fourth item',
    disabled: false
  }];

  $scope.rules2 = [{
    type: 'first item',
    value: 'first item',
    disabled: true
  }, {
    type: 'second item',
    value: 'second item',
    disabled: false
  }, {
    type: 'third item',
    value: 'third item',
    disabled: false
  }, {
    type: 'fourth item',
    value: 'fourth item',
    disabled: false
  }];

  $scope.rules3 = [{
    type: 'first item',
    value: 'first item',
    disabled: true
  }, {
    type: 'second item',
    value: 'second item',
    disabled: true
  }, {
    type: 'third item',
    value: 'third item',
    disabled: false
  }, {
    type: 'fourth item',
    value: 'fourth item',
    disabled: false
  }];
});

/* Put your css in here */

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />

  <select ng-model="item" ng-options="item.type as item.value disable when item.disabled for item in rules1">
    <option value="" style="display: none" selected="selected">Select When
    </option>
  </select>

  after selecting first select, first item:

  <select ng-model="item1" ng-options="item.type as item.value disable when item.disabled for item in rules2">
    <option value="" style="display: none" selected="selected">Select When
    </option>
  </select>

  after selecting second select, second item:

        <select ng-model="item2" ng-options="item.type as item.value disable when item.disabled for item in rules3">
    <option value="" style="display: none" selected="selected">Select When
    </option>
  </select>

Please help me with this. Will be greatful!

Body:
Since your rule1, rule2, and rule3 arrays are the exact same, I'd first just make this into one: rules. If not, you'd need to make sure three identical arrays are updated in the same way.

ng-change usually works pretty great with these types of inputs. When you select an option, it will fire that change event, and you can make custom functions to handle it.

Side note, you have your ng-model named the same as your item in your loop, but these aren't the same thing.

<select ng-model="item" ng-options="item.type as item.value disable when item.disabled for item in rules" data-ng-change="select(item)">
    <option value="" style="display: none" selected="selected">Select When
    </option>
</select>

I added that select function that passes in the input's model (the value of the input option you've selected).

Then in your controller, you could have some type of function to handle the change, like:

scope.select = function (value) {

    if (!value) { return; }

    for (var i=0;i<$scope.rules.length;++i) {
      if ($scope.rules[i].value === value) {
        $scope.rules[i].disabled = true;
      }
    }
};

http://jsbin.com/tomoma/edit?html,js,console,output


问:
emacs init - splitting window and opening files next to each other
I am trying to customize my Emacs init file in such a way that Emacs opens with two windows split and the ansi-term opened in one side and my init file on the other side. Now, the function I wrote (switch-to-next-window) works perfectly if Emacs is open already.

I was hoping to make the cursor switch to the other window and then open my init file there. However, if I try to run this upon start-up (actually after start up, at least this is what I am thinking) I get the following error: window-live-p, nil

I am gessing that there is no "next window". But I just don't know a work around here since I do think that I am only calling my function after Emacs has fully started up? If anyone could point me to where I am going wrong in my logic, that would be great!

```<code>(split-window-horizontally)
(setq initial-buffer-choice "*ansi-term*")

(defun switch-to-next-window ()
  (interactive)
  (let* ((next-window (get-buffer-window (other-buffer (current-buffer) t))))
    (select-window next-window)))

(add-hook 'emacs-startup-hook (lambda ()(ansi-term "/bin/bash")))
(with-eval-after-load "~/.emacs.d/init.el"
  (switch-to-next-window)
  (setq initial-buffer-choice "~/.emacs.d/init.el"))
</code>```

答:
Changing initial-buffer-choice after the initial buffer has been opened won't have any effect.

What helps is putting everything into the emacs-startup-hook and using the find-file-other-window function:

(add-hook 'emacs-startup-hook
          (lambda ()
            (ansi-term "/bin/bash")
            (split-window-horizontally)
            (find-file-other-window "~/.emacs.d/init.el")))
```

Body:
I am trying to customize my Emacs init file in such a way that Emacs opens with two windows split and the ansi-term opened in one side and my init file on the other side. Now, the function I wrote (switch-to-next-window) works perfectly if Emacs is open already.

I was hoping to make the cursor switch to the other window and then open my init file there. However, if I try to run this upon start-up (actually after start up, at least this is what I am thinking) I get the following error: window-live-p, nil

I am gessing that there is no "next window". But I just don't know a work around here since I do think that I am only calling my function after Emacs has fully started up? If anyone could point me to where I am going wrong in my logic, that would be great!

(split-window-horizontally)
(setq initial-buffer-choice "*ansi-term*")

(defun switch-to-next-window ()
  (interactive)
  (let* ((next-window (get-buffer-window (other-buffer (current-buffer) t))))
    (select-window next-window)))

(add-hook 'emacs-startup-hook (lambda ()(ansi-term "/bin/bash")))
(with-eval-after-load "~/.emacs.d/init.el"
  (switch-to-next-window)
  (setq initial-buffer-choice "~/.emacs.d/init.el"))


问:
Large Text File 1 > GB Frequency of KeyValuePair using File.ReadLine
I'm new to C# and object-oriented programming in general. I have an application which parses a very large text file.

I have two dictionaries:

Dictionary<string, string> parsingDict //key: original value, value: replacement
Dictionary<int, string> Frequency // key: count, value: counted string

I am finding the frequency of each key. I am able to get the desired output which is:

System1 has been replaced with MachineA 5 time(s)

System2 has been replaced with MachineB 7 time(s)

System3 has been replaced with MachineC 10 time(s)

System4 has been replaced with MachineD 19 time(s)

Following is my code:

```<code>String[] arrayofLine = File.ReadAllLines(File);
           foreach (var replacement in parsingDict.Keys)
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                if (arrayofLine[i].Contains(replacement))
                {
                    countr++;

                    Frequency.Add(countr, Convert.ToString(replacement));
                }
            }

        }

        Frequency = Frequency.GroupBy(s => s.Value)
                .Select(g => g.First())
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);  //Get only the distinct records.

        foreach (var freq in Frequency)
        {
            sbFreq.AppendLine(string.Format("The text {0} was replaced {2} time(s) with {1} \n",
            freq.Value, parsingDict[freq.Value],
            arrayofLine.Where(x => x.Contains(freq.Value)).Count()));
        }
</code>```

Using String[] arrayofLine = File.ReadAllLines(File); increases memory utilization.

How can arrayofLine.Where(x => x.Contains(freq.Value)).Count()) be achieve using File.ReadLine as it is memory friendly.

答:
```<code>string line = string.Empty;
Dictionary<string, int> found = new Dictionary<int, string>();
using(System.IO.StreamReader file = new System.IO.StreamReader(@"c:\Path\To\BigFile.txt"))
{
   while(!file.EndOfStream)
   {
      line = file.ReadLine();
      // Matches found logic
      if (!found.ContainsKey(line)) found.Add(line, 1);
      else found[line] = found[line] + 1;
    }
}
</code>```

Body:
I'm new to C# and object-oriented programming in general. I have an application which parses a very large text file.

I have two dictionaries:

Dictionary<string, string> parsingDict //key: original value, value: replacement
Dictionary<int, string> Frequency // key: count, value: counted string

I am finding the frequency of each key. I am able to get the desired output which is:

System1 has been replaced with MachineA 5 time(s)

System2 has been replaced with MachineB 7 time(s)

System3 has been replaced with MachineC 10 time(s)

System4 has been replaced with MachineD 19 time(s)

Following is my code:

String[] arrayofLine = File.ReadAllLines(File);
           foreach (var replacement in parsingDict.Keys)
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                if (arrayofLine[i].Contains(replacement))
                {
                    countr++;

                    Frequency.Add(countr, Convert.ToString(replacement));
                }
            }

        }

        Frequency = Frequency.GroupBy(s => s.Value)
                .Select(g => g.First())
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);  //Get only the distinct records.

        foreach (var freq in Frequency)
        {
            sbFreq.AppendLine(string.Format("The text {0} was replaced {2} time(s) with {1} \n",
            freq.Value, parsingDict[freq.Value],
            arrayofLine.Where(x => x.Contains(freq.Value)).Count()));
        }

Using String[] arrayofLine = File.ReadAllLines(File); increases memory utilization.

How can arrayofLine.Where(x => x.Contains(freq.Value)).Count()) be achieve using File.ReadLine as it is memory friendly.


问:
Keeping state of logged in user in ASP .Net Core Web API
I have an ASP .Net Core 1.1 Web Api, which serves requests from a front end web app and phone app. The app is for real estate agents to perform inspections on properties. The system therefore has entities such as inspections, properties, users, agencies, etc. Users (i.e. real estate agents) and properties belong to agencies. So an estate agency can have one or more users and one or more properties.

As an example, a user might want to view a list of all properties inspected by anyone in his estate agency. In this case, he clicks somewhere in the web/phone app, and the app sends off an HTTP GET request to the API to retrieve the list of properties. The Web API, upon receiving this request, first checks which user is requesting this, and then checks which agency this user belongs to, and then returns all the properties that belong to this agency. So... these are the [simplified] models that I have:

```<code>[Table("agency")]
public class Agency
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("agency_id")]
    public int? Id { get; set; }

    [Column("name")]
    public string Name { get; set; }
}

[Table("user")]
public class User
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("user_id")]
    public int? Id { get; set; }

    [Column("username")]
    public string Username { get; set; }

    [Column("agency_id")]
    public int AgencyId { get; set; }

    [ForeignKey("AgencyId")]
    public Agency Agency { get; set; }
}

[Table("property")]
public class Property
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("property_id")]
    public int? Id { get; set; }

    [Column("address")]
    public string Address { get; set; }

    [Column("agency_id")]
    public int AgencyId { get; set; }

    [ForeignKey("AgencyId")]
    public Agency Agency { get; set; }
}
</code>```

The controller action on the Web API that handles the aforementioned request looks like this:

```<code>[Authorize]
[HttpGet]
public async Task<IActionResult> GetProperties()
{
    // Get Auth0 identifier for the user performing the request
    string nameIdentifier = User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
    // Retrieve this user from the database
    User user = await _context.User.SingleOrDefaultAsync(u => u.Username == nameIdentifier);
    // Return a list of properties that belong to the user's agency
    return Ok(_context.Properties
        .Where(p.AgencyId == user.AgencyId));
}
</code>```

Now, all GET requests to the API are filtered like this - where the API returns records that pertain to the logged in user's agency. Whether the user requests a list of inspections, or landlords, or tenants, the API always returns only records that belong to the user's agency.

Now I know ASP .Net Core is stateless, so I can't save the user object on the server when the user logs in, and have it in memory ready to be called in each controller action. But I feel like this round trip to the database EVERY time the API receives any GET request to find out which agency this user belongs to is wasteful. Is there a better way to do this? I'm fairly new to ASP and web development in general. Any ideas/hints/pointers would be greatly appreciated.

答:
Now I know ASP .Net Core is stateless, so I can't save the user object on the server when the user logs in, and have it in memory ready to be called in each controller action. But I feel like this round trip to the database EVERY time the API receives any GET request to find out which agency this user belongs to is wasteful.

Welcome to the web, it is a stateless environment.  If you need the user record to handle each http request you basically have a few choices:

Get it from the database on ever request

Place the part of the record you need into session

Place the part of the record you need into a cookie

Each approach has pros and cons.

Option 1 will give you the absolute latest info from the user record but comes at the cost of an additional database round trip for ever request.  And if you have multiple different records you need to handle the request you may end up with multiple database round trips for each request depending on how you architect things,

Option 2 can eliminate that database round trip for ever request if you have your Asp.Net Core app configured to use the In-Memory Session Provider. But the downside is that if the web app is recycled (which is pretty common if running behind IIS) then session will be cleared.  If you have session configured to use a database provider like SqlServer then you will still incur a database round trip for each request as it reads in session from the database (but that will be only one round trip instead of possibly several depending on what you have placed in session and how many db round trips to took to compile the info.) A downside to placing info in database backed session is that it forces a database round trip for every request even if the request doesn't need any of the info that is placed in session. And if you are not careful the size of the data stored in session (and queried from the database each request) get quite large quickly.  It can sometimes be too easy to "just throw it into session" which can lead ultimately to performance problems.

Option 3 places the needed data in a cookie that will travel along with each request in the header of the http request.  The downside of this is that it makes every file request marginally larger (often even image requests) and you will probably want to limit the cookie to only https requests to keep the info from being transmitted in the clear over the internet. This approach is typically only used for very small amounts of data.

This summary is in no way exhaustive, there are additional ways to keep track of state (query parameters, etc) and additional security considerations for any method chosen.  The main takeaway is that, yes the web is a stateless environment, but there are still ways to keep track of state, however all of them have pros and cons and no single way is always the best.  Most large web apps use variations of all the available approaches for different aspects of their web application.

You can read more about Asp.NET Core session and application state here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state

Body:
I have an ASP .Net Core 1.1 Web Api, which serves requests from a front end web app and phone app. The app is for real estate agents to perform inspections on properties. The system therefore has entities such as inspections, properties, users, agencies, etc. Users (i.e. real estate agents) and properties belong to agencies. So an estate agency can have one or more users and one or more properties.

As an example, a user might want to view a list of all properties inspected by anyone in his estate agency. In this case, he clicks somewhere in the web/phone app, and the app sends off an HTTP GET request to the API to retrieve the list of properties. The Web API, upon receiving this request, first checks which user is requesting this, and then checks which agency this user belongs to, and then returns all the properties that belong to this agency. So... these are the [simplified] models that I have:

[Table("agency")]
public class Agency
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("agency_id")]
    public int? Id { get; set; }

    [Column("name")]
    public string Name { get; set; }
}

[Table("user")]
public class User
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("user_id")]
    public int? Id { get; set; }

    [Column("username")]
    public string Username { get; set; }

    [Column("agency_id")]
    public int AgencyId { get; set; }

    [ForeignKey("AgencyId")]
    public Agency Agency { get; set; }
}

[Table("property")]
public class Property
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("property_id")]
    public int? Id { get; set; }

    [Column("address")]
    public string Address { get; set; }

    [Column("agency_id")]
    public int AgencyId { get; set; }

    [ForeignKey("AgencyId")]
    public Agency Agency { get; set; }
}

The controller action on the Web API that handles the aforementioned request looks like this:

[Authorize]
[HttpGet]
public async Task<IActionResult> GetProperties()
{
    // Get Auth0 identifier for the user performing the request
    string nameIdentifier = User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
    // Retrieve this user from the database
    User user = await _context.User.SingleOrDefaultAsync(u => u.Username == nameIdentifier);
    // Return a list of properties that belong to the user's agency
    return Ok(_context.Properties
        .Where(p.AgencyId == user.AgencyId));
}

Now, all GET requests to the API are filtered like this - where the API returns records that pertain to the logged in user's agency. Whether the user requests a list of inspections, or landlords, or tenants, the API always returns only records that belong to the user's agency.

Now I know ASP .Net Core is stateless, so I can't save the user object on the server when the user logs in, and have it in memory ready to be called in each controller action. But I feel like this round trip to the database EVERY time the API receives any GET request to find out which agency this user belongs to is wasteful. Is there a better way to do this? I'm fairly new to ASP and web development in general. Any ideas/hints/pointers would be greatly appreciated.

ContentLicense: CC BY-SA 4.0


问:
Doctrine transactions - count number of pending requests
Is there a way to find out the number of pending requests in a transaction before launching the commit action ?

I want to launch my commit only if I get a sufficient number of queries (that I can not count one by one before in my particular case...)

答:
OK I find this in the UOF

http://www.doctrine-project.org/api/orm/2.3/source-class-Doctrine.ORM.UnitOfWork.html#3134

so this method will do the job

```<code>count($em->getUnitOfWork()->getScheduledEntityInsertions())
</code>```

Body:
OK I find this in the UOF

http://www.doctrine-project.org/api/orm/2.3/source-class-Doctrine.ORM.UnitOfWork.html#3134

so this method will do the job

count($em->getUnitOfWork()->getScheduledEntityInsertions())


问:
Elisp: Asking yes-or-no in interactive commands
I'm new to Emacs and am trying to write a few Emacs Lisp functions.

I'd like to write a function that takes two parameters and can handle being interactive. However, one of the parameters is a boolean — it'd be perfect if I could use (y-or-no-p), but (interactive) doesn't seem to have a character code for that.

Any ideas?

Update: I'm using GNU Emacs 23.

Also, here's what my function looks like so far:

```<code>(defun foo (str bool)
  (interactive "sSome text: \nsDo the thing?")
  (some-func str)
  (if bool (some-other-func str)))
</code>```

答:
Not quite sure what you're asking, but I can't find a function called y-or-no-p.  Did you mean yes-or-no-p?

That seems to do what I would expect.

Body:
I'm new to Emacs and am trying to write a few Emacs Lisp functions.

I'd like to write a function that takes two parameters and can handle being interactive. However, one of the parameters is a boolean — it'd be perfect if I could use (y-or-no-p), but (interactive) doesn't seem to have a character code for that.

Any ideas?

Update: I'm using GNU Emacs 23.

Also, here's what my function looks like so far:

(defun foo (str bool)
  (interactive "sSome text: \nsDo the thing?")
  (some-func str)
  (if bool (some-other-func str)))


问:
Nginx 403 error for single file while others work
I have a simple Flask/Nginx server and 3 files in location /opt/hosting/files:

```<code>[adam@localhost]$ namei -om /opt/hosting/files
    f: /opt/hosting/files
     dr-xr-xr-x root  root  /
     drwxr-xr-x root  root  opt
     drwxr-xr-x root  root  hosting
     drwxr-xr-x nginx nginx files
</code>```

In the folder files I have 3 files: two images and a bigger zip file:

```<code>[adam@localhost]$ ls -lh /opt/hosting/files/
total 424M
-rwx-----x. 1 nginx nginx  19K 03-06 01:29 file1.jpg
-rwx-----x. 1 nginx nginx  18M 03-06 03:34 file2.png
-rwxr-xr-x. 1 nginx nginx 406M 07-07 13:07 file3.zip
</code>```

I am serving these files and while the first two appear without a problem, I get 403 Forbidden for the zip file both through www and using wget. I think directories permissions are set correctly, since the two other files are fine. Zip file properties are even higher so this shouldn't be an issue as well.

I tried using chown root:root and chown 777 for file and folders and couldn't access the file anyway. After making changes I'm restarting nginx with sudo systemctl restart uwsgi. SELinux shows Enforcing.

What is the problem here?

答:
Got it. Reading a comment by tinesoft here made me check SELinux context of files (yes, I'm running CentOS, forgot to mention that) and it was:

```<code>[adam@localhost]$ ls -lZ /opt/hosting/files
-rwx-----x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 file1.jpg
-rwx-----x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 file2.png
-rwxr-xr-x. nginx nginx unconfined_u:object_r:user_home_t:s0 file3.zip
</code>```

Then, following SELinux documentation from RedHat I managed to change the type of SELinux context from user_home_t to httpd_sys_content_t using

```<code>sudo chcon -t httpd_sys_content_t file3.zip
</code>```

That was it.

Body:
I have a simple Flask/Nginx server and 3 files in location /opt/hosting/files:

[adam@localhost]$ namei -om /opt/hosting/files
    f: /opt/hosting/files
     dr-xr-xr-x root  root  /
     drwxr-xr-x root  root  opt
     drwxr-xr-x root  root  hosting
     drwxr-xr-x nginx nginx files

In the folder files I have 3 files: two images and a bigger zip file:

[adam@localhost]$ ls -lh /opt/hosting/files/
total 424M
-rwx-----x. 1 nginx nginx  19K 03-06 01:29 file1.jpg
-rwx-----x. 1 nginx nginx  18M 03-06 03:34 file2.png
-rwxr-xr-x. 1 nginx nginx 406M 07-07 13:07 file3.zip

I am serving these files and while the first two appear without a problem, I get 403 Forbidden for the zip file both through www and using wget. I think directories permissions are set correctly, since the two other files are fine. Zip file properties are even higher so this shouldn't be an issue as well.

I tried using chown root:root and chown 777 for file and folders and couldn't access the file anyway. After making changes I'm restarting nginx with sudo systemctl restart uwsgi. SELinux shows Enforcing.

What is the problem here?

Body:
Got it. Reading a comment by tinesoft here made me check SELinux context of files (yes, I'm running CentOS, forgot to mention that) and it was:

[adam@localhost]$ ls -lZ /opt/hosting/files
-rwx-----x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 file1.jpg
-rwx-----x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 file2.png
-rwxr-xr-x. nginx nginx unconfined_u:object_r:user_home_t:s0 file3.zip

Then, following SELinux documentation from RedHat I managed to change the type of SELinux context from user_home_t to httpd_sys_content_t using

sudo chcon -t httpd_sys_content_t file3.zip

That was it.


问:
selectable headers in viewForHeaderInSection swift 3.1
I have the below code which adds headers to 4 columns in a tableView.
I would like to preform a sort based on which header a users clicks on, is that possible with the way I have created the column headers?</p>

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let  v = UIView()
        let segmentedControl = UISegmentedControl(frame: CGRect(x:3, y: 5, width: tableView.frame.width-6, height: 30))
        v.addSubview(segmentedControl)
        v.backgroundColor = UIColor.white
        segmentedControl.insertSegment(withTitle: "Name", at: 0, animated: false)
        segmentedControl.insertSegment(withTitle: "Points", at: 1, animated: false)
        segmentedControl.insertSegment(withTitle: "Played", at: 2, animated: false)
        segmentedControl.insertSegment(withTitle: "Ave", at: 3, animated: false)

        return v
    }
</code>```

答:
I added buttons to the header like so:</p>

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  v = UIView()
    let segmentedControl = UISegmentedControl(frame: CGRect(x:0, y: 5, width: tableView.frame.width-6, height: 40))
    v.addSubview(segmentedControl)
    v.backgroundColor = UIColor.white

    let btnName: UIButton = UIButton(frame: CGRect(x: 5, y: 5, width: 120, height: 30))
    btnName.backgroundColor = UIColor.white
    btnName.showsTouchWhenHighlighted = true
    btnName.layer.borderWidth = 1
    btnName.layer.borderColor = UIColor.lightGray.cgColor
    btnName.setTitle("Name", for: .normal)
    btnName.setTitleColor(UIColor.blue, for: .normal)
    btnName.setTitleColor(UIColor.red, for: .selected)
    btnName.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnName.tag = 1
    v.addSubview(btnName)

    let btnPoints: UIButton = UIButton(frame: CGRect(x: 125, y: 5, width: 80, height: 30))
    btnPoints.backgroundColor = UIColor.white
    btnPoints.showsTouchWhenHighlighted = true
    btnPoints.layer.borderWidth = 1
    btnPoints.layer.borderColor = UIColor.lightGray.cgColor
    btnPoints.setTitle("Points", for: .normal)
    btnPoints.setTitleColor(UIColor.blue, for: .normal)
    btnPoints.setTitleColor(UIColor.red, for: .selected)
    btnPoints.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnPoints.tag = 2
    v.addSubview(btnPoints)

    let btnPlayed: UIButton = UIButton(frame: CGRect(x: 205, y: 5, width: 80, height: 30))
    btnPlayed.backgroundColor = UIColor.white
    btnPlayed.showsTouchWhenHighlighted = true
    btnPlayed.layer.borderWidth = 1
    btnPlayed.layer.borderColor = UIColor.lightGray.cgColor
    btnPlayed.setTitle("Played", for: .normal)
    btnPlayed.setTitleColor(UIColor.blue, for: .normal)
    btnPlayed.setTitleColor(UIColor.red, for: .focused)
    btnPlayed.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnPlayed.tag = 4
    v.addSubview(btnPlayed)

    let btnAve: UIButton = UIButton(frame: CGRect(x: 285, y: 5, width: 80, height: 30))
    btnAve.backgroundColor = UIColor.white
    btnAve.showsTouchWhenHighlighted = true
    btnAve.layer.borderWidth = 1
    btnAve.layer.borderColor = UIColor.lightGray.cgColor
    btnAve.setTitle("Ave", for: .normal)
    btnAve.setTitleColor(UIColor.blue, for: .normal)
    btnAve.setTitleColor(UIColor.red, for: .highlighted)
    btnAve.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnAve.tag = 3
    v.addSubview(btnAve)

    return v
}

func buttonAction(sender: UIButton!) {
    let btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {
        btnNamePressed = !btnNamePressed
        if btnNamePressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Name < $1.Name})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Name > $1.Name})
        }
    }

    if btnsendtag.tag == 2 {
        btnPointsPressed = !btnPointsPressed
        if btnPointsPressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Points < $1.Points})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Points > $1.Points})
        }
    }

    if btnsendtag.tag == 3 {
        btnPlayedPressed = !btnPlayedPressed
        if btnPlayedPressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Played < $1.Played})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Played > $1.Played})
        }
    }

    if btnsendtag.tag == 4 {
        btnAvePressed = !btnAvePressed
        if btnAvePressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Average < $1.Average})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Average > $1.Average})
        }
    }

    tableView.reloadData()
}
</code>```

Body:
I have the below code which adds headers to 4 columns in a tableView.
I would like to preform a sort based on which header a users clicks on, is that possible with the way I have created the column headers?

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let  v = UIView()
        let segmentedControl = UISegmentedControl(frame: CGRect(x:3, y: 5, width: tableView.frame.width-6, height: 30))
        v.addSubview(segmentedControl)
        v.backgroundColor = UIColor.white
        segmentedControl.insertSegment(withTitle: "Name", at: 0, animated: false)
        segmentedControl.insertSegment(withTitle: "Points", at: 1, animated: false)
        segmentedControl.insertSegment(withTitle: "Played", at: 2, animated: false)
        segmentedControl.insertSegment(withTitle: "Ave", at: 3, animated: false)

        return v
    }

Body:
I added buttons to the header like so:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  v = UIView()
    let segmentedControl = UISegmentedControl(frame: CGRect(x:0, y: 5, width: tableView.frame.width-6, height: 40))
    v.addSubview(segmentedControl)
    v.backgroundColor = UIColor.white

    let btnName: UIButton = UIButton(frame: CGRect(x: 5, y: 5, width: 120, height: 30))
    btnName.backgroundColor = UIColor.white
    btnName.showsTouchWhenHighlighted = true
    btnName.layer.borderWidth = 1
    btnName.layer.borderColor = UIColor.lightGray.cgColor
    btnName.setTitle("Name", for: .normal)
    btnName.setTitleColor(UIColor.blue, for: .normal)
    btnName.setTitleColor(UIColor.red, for: .selected)
    btnName.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnName.tag = 1
    v.addSubview(btnName)

    let btnPoints: UIButton = UIButton(frame: CGRect(x: 125, y: 5, width: 80, height: 30))
    btnPoints.backgroundColor = UIColor.white
    btnPoints.showsTouchWhenHighlighted = true
    btnPoints.layer.borderWidth = 1
    btnPoints.layer.borderColor = UIColor.lightGray.cgColor
    btnPoints.setTitle("Points", for: .normal)
    btnPoints.setTitleColor(UIColor.blue, for: .normal)
    btnPoints.setTitleColor(UIColor.red, for: .selected)
    btnPoints.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnPoints.tag = 2
    v.addSubview(btnPoints)

    let btnPlayed: UIButton = UIButton(frame: CGRect(x: 205, y: 5, width: 80, height: 30))
    btnPlayed.backgroundColor = UIColor.white
    btnPlayed.showsTouchWhenHighlighted = true
    btnPlayed.layer.borderWidth = 1
    btnPlayed.layer.borderColor = UIColor.lightGray.cgColor
    btnPlayed.setTitle("Played", for: .normal)
    btnPlayed.setTitleColor(UIColor.blue, for: .normal)
    btnPlayed.setTitleColor(UIColor.red, for: .focused)
    btnPlayed.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnPlayed.tag = 4
    v.addSubview(btnPlayed)

    let btnAve: UIButton = UIButton(frame: CGRect(x: 285, y: 5, width: 80, height: 30))
    btnAve.backgroundColor = UIColor.white
    btnAve.showsTouchWhenHighlighted = true
    btnAve.layer.borderWidth = 1
    btnAve.layer.borderColor = UIColor.lightGray.cgColor
    btnAve.setTitle("Ave", for: .normal)
    btnAve.setTitleColor(UIColor.blue, for: .normal)
    btnAve.setTitleColor(UIColor.red, for: .highlighted)
    btnAve.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    btnAve.tag = 3
    v.addSubview(btnAve)

    return v
}

func buttonAction(sender: UIButton!) {
    let btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {
        btnNamePressed = !btnNamePressed
        if btnNamePressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Name < $1.Name})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Name > $1.Name})
        }
    }

    if btnsendtag.tag == 2 {
        btnPointsPressed = !btnPointsPressed
        if btnPointsPressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Points < $1.Points})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Points > $1.Points})
        }
    }

    if btnsendtag.tag == 3 {
        btnPlayedPressed = !btnPlayedPressed
        if btnPlayedPressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Played < $1.Played})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Played > $1.Played})
        }
    }

    if btnsendtag.tag == 4 {
        btnAvePressed = !btnAvePressed
        if btnAvePressed == true
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Average < $1.Average})
        }
        else
        {
            GlobalVar.listOf = GlobalVar.listOf.sorted(by: {$0.Average > $1.Average})
        }
    }

    tableView.reloadData()
}


问:
How to select rows where date is greater than the date in another row?
I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are  two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table CUSTOMER_CARDS.

```<code>card_id | customer_id | card_type | last_used
----------------------------------------------
      1 |          c1 |         A | 2017-07-07
      2 |          c1 |         B | 2016-04-01
      3 |          c2 |         A | 2017-06-04
      4 |          c2 |         B | 2017-07-03
      5 |          c3 |         A | 2016-02-23
      6 |          c3 |         B | 2017-04-17
</code>```

I need a select statement which selects the customer_id of customer c2, who has a card of type B which is younger then his cards of type A. How do I achieve this?

答:
You need Group By and Having clause

```<code>select customer_id
from yourtable
Group by customer_id
Having Min(case when card_type = 'B' then last_used end) >  Max(case when card_type = 'A' then last_used end)
</code>```

Body:
I have a table with customer cards. A customer can have several cards. For every customer card there is one row. If a customer has several cards, there are several rows. There are  two different card types A and B. For every card the last_used date is stored.

I want to check if there are customers with both customer cards of type A and B, where the last_used date of card B is younger then the last_used date of card A.

This is my table CUSTOMER_CARDS.

card_id | customer_id | card_type | last_used
----------------------------------------------
      1 |          c1 |         A | 2017-07-07
      2 |          c1 |         B | 2016-04-01
      3 |          c2 |         A | 2017-06-04
      4 |          c2 |         B | 2017-07-03
      5 |          c3 |         A | 2016-02-23
      6 |          c3 |         B | 2017-04-17

I need a select statement which selects the customer_id of customer c2, who has a card of type B which is younger then his cards of type A. How do I achieve this?

Body:
You need Group By and Having clause

select customer_id
from yourtable
Group by customer_id
Having Min(case when card_type = 'B' then last_used end) >  Max(case when card_type = 'A' then last_used end)


问:
Spark process history logs Bluemix (DSX)
I'm working with my notebook in DSX using the spark instance related to it and I can't see the spark history log. If I access from bluemix I saw the following error:

Not aouthorized
spaceGuid: XXXXXXXXXXXXXXXX

What could be wrong?

Thanks in advance.

Santiago.

答: You can access the Spark history logs on DSX Notebooks by accessing the Notebook Info->Environment panel on the right-hand side of the UI. There is link View Spark History Server which directs you to the Spark history server UI.


问:
Dividing a number by instances of my class in Python
I have a class called Time, and I need to implement a Frequency class. How can I implement dividing ints or floats by an instance of Time to get an instance of Frequency ?

I already know about __div__, __truediv__, __floordiv__ and other Python special methods, and I already use them in my code to divide instances of classes by numbers or instances of other classes, but I cannot find a way to divide a number by an instance of my class.

Is it possible to implement dividing a number by an instance of a class in Python ?

答:
Yes. You just have to make sure that Time.__rtruediv__() returns a Frequency instance when it receives a float or integer.

Usage:

```<code>>>> 100 / Time(2)
Frequency(50.0)
>>> 2.5 / Time(5)
Frequency(0.5)
</code>```

Implementation:

```<code>class Time:
  def __init__(self, value):
    self.value = value

  def __rtruediv__(self, other):
    if not isinstance(other, (int, float)):
      return NotImplemented
    return Frequency(other / self.value)

class Frequency:
  def __init__(self, value):
    self.value = value

  def __repr__(self):
    return '{}({})'.format(self.__class__.__name__, self.value)
</code>```

The python docs contains a full example on implementing the arithmetic operations for your custom classes.

The proper way to handle incompatible types is to return the special value NotImplemented.

NotImplemented

Special value which should be returned by the binary
  special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.)
  to indicate that the operation is not implemented with respect to the
  other type

Suppose you try to use a unsupported complex number, returning NotImplemented will eventually cause a TypeError with a correct error message. (at least in python 3)

```<code>>>> 100j / Time(2)

Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'complex' and 'Time'
</code>```

Body:
Yes. You just have to make sure that Time.__rtruediv__() returns a Frequency instance when it receives a float or integer.

Usage:

>>> 100 / Time(2)
Frequency(50.0)
>>> 2.5 / Time(5)
Frequency(0.5)

Implementation:

class Time:
  def __init__(self, value):
    self.value = value

  def __rtruediv__(self, other):
    if not isinstance(other, (int, float)):
      return NotImplemented
    return Frequency(other / self.value)

class Frequency:
  def __init__(self, value):
    self.value = value

  def __repr__(self):
    return '{}({})'.format(self.__class__.__name__, self.value)

The python docs contains a full example on implementing the arithmetic operations for your custom classes.

The proper way to handle incompatible types is to return the special value NotImplemented.

NotImplemented

Special value which should be returned by the binary
  special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.)
  to indicate that the operation is not implemented with respect to the
  other type

Suppose you try to use a unsupported complex number, returning NotImplemented will eventually cause a TypeError with a correct error message. (at least in python 3)

>>> 100j / Time(2)

Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'complex' and 'Time'


问:
Android : How can I open a file using OpenCV C++ ?
I have a video file saved on my Android device.

Using a getPath() function I got "sdcard/video_app/sample_video.mp4".

I'm now trying to use this video file in my OpenCV C++ code (I'm using NDK and JNI) with this :

```<code>String filename = "sdcard/video_app/sample_video.mp4";

VideoCapture capture(filename);

Mat img;

capture >> img;

imwrite("sdcard/video_app/test.jpg", img);
</code>```

I added :

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

Nothing is happening. What am I doing wrong ?

答:
You can try,</p>

```<code>VideoCapture capture=new VideoCapture();
capture.open("sdcard/video_app/sample_video.mp4");
Mat frames = new Mat();

 // to read each frame and to save in Mat class
for(;;)
{
   capture.read(frames);
   imwrite("sdcard/video_app/test.jpg",frame);
}
</code>```

Body:
I have a video file saved on my Android device.

Using a getPath() function I got "sdcard/video_app/sample_video.mp4".

I'm now trying to use this video file in my OpenCV C++ code (I'm using NDK and JNI) with this :

String filename = "sdcard/video_app/sample_video.mp4";

VideoCapture capture(filename);

Mat img;

capture >> img;

imwrite("sdcard/video_app/test.jpg", img);

I added :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Nothing is happening. What am I doing wrong ?

Body:
You can try,

VideoCapture capture=new VideoCapture();
capture.open("sdcard/video_app/sample_video.mp4");
Mat frames = new Mat();

 // to read each frame and to save in Mat class
for(;;)
{
   capture.read(frames);
   imwrite("sdcard/video_app/test.jpg",frame);
}


问:
Multiple Rex Expressions
I'm using the rex expressions below to search for the following fields in my raw data:

Address Line 1
Address Line 2
Address Line 3
Address Line 4, and
Postcode

```<code>| rex "Address Line 1=(?<address1>[^,]*)"
| rex "Address Line 2=(?<address2>[^,]*)"
| rex "Address Line 3=(?<address3>[^,]*)"
| rex "Address Line 4=(?<address4>[^,]*)"
| rex "Postcode=(?<postcode>[^,]*)"
</code>```

As you can see by the expression, each of these fields is then assigned a variable so for Address Line 1, the variable is address1, Address Line 2 is 'address2' and so on.

As you will also no doubt see, the above expression contains multiple rex expressions, could someone perhaps tell me please, is there a way to combine these into one rex expression.

答:
The first example on page https://docs.splunk.com/Documentation/Splunk/6.6.1/SearchReference/Rex shows how to extract multiple fields with a single rex command. If your _raw is multiline, use \n or \r as appropriate.
http://docs.splunk.com/Documentation/Splunk/6.6.1/Knowledge/AboutSplunkregularexpressions

Title: Multiple Rex Expressions

Body:
I'm using the rex expressions below to search for the following fields in my raw data:

Address Line 1
Address Line 2
Address Line 3
Address Line 4, and
Postcode

| rex "Address Line 1=(?<address1>[^,]*)"
| rex "Address Line 2=(?<address2>[^,]*)"
| rex "Address Line 3=(?<address3>[^,]*)"
| rex "Address Line 4=(?<address4>[^,]*)"
| rex "Postcode=(?<postcode>[^,]*)"

As you can see by the expression, each of these fields is then assigned a variable so for Address Line 1, the variable is address1, Address Line 2 is 'address2' and so on.

As you will also no doubt see, the above expression contains multiple rex expressions, could someone perhaps tell me please, is there a way to combine these into one rex expression.