问:
How can I turn a directory of images into video? (node.js)
I'm trying to create a screen recording video by using a module to create multiple images and then somehow use these images to export to an mp4. However I don't know how to turn the directory of images into a video. Can anyone help with this?

Here is what I have so far:

```<code>const screenshot = require('desktop-screenshot');

let i = 0;
while(i <= 100){
    screenshot("screens/" + i + "_shot.png", function(error, complete) {
        if(error){
          console.log("Screenshot failed", error);
        }
        else{
          console.log("Screenshot succeeded");
        }

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

答:
Why don't you use an npm package for screen recording?

Also your while loop doesn't represent seconds but discrete steps. If you want a time based recording you need some implementation which respects time based steps with step delta to allow adjustment for different rendering speeds. (This is similar to game loops, the only difference is that your action is screen captures and not moving game characters.)

A good screen recording package should do that, as well as providing an API for export. Save your time and effort and use a package for that.

Good point to start: https://www.npmjs.com/search?q=screen+recording

Body:
I'm trying to create a screen recording video by using a module to create multiple images and then somehow use these images to export to an mp4. However I don't know how to turn the directory of images into a video. Can anyone help with this?

Here is what I have so far:

const screenshot = require('desktop-screenshot');

let i = 0;
while(i <= 100){
    screenshot("screens/" + i + "_shot.png", function(error, complete) {
        if(error){
          console.log("Screenshot failed", error);
        }
        else{
          console.log("Screenshot succeeded");
        }

    });
       i++;
}


来源: stackexchange

问:
FixedThreadPool memory leak
I have a Stream<String> and performing some actions on its items, which includes processing String and writing it to file.

Having the following groovy code, and processing 1 million items i'm running into the OutOfMemoryError.

```<code>ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())

stream.forEach { item ->
    executorService.execute {
        handle(item)
    }
}

executorService.shutdown()
executorService.awaitTermination(1, TimeUnit.DAYS)
</code>```

After some profiling, i've found out that the Runnable tasks are not handled by gc and kept alive within the BlockingQueue until the app fails.

Why ExecutorService keeps the finished Runnable in the queue? and how it's supposed to be cleaned up?

答:
The memory leak was caused because the BlockingQueue was filled up faster then ExecutorService pulled the tasks from it.

This was caused because iterating over stream with forEach method is pretty fast but tasks are running some more time.

Here's the solution I applied

```<code>def processors = Runtime.getRuntime().availableProcessors()
ExecutorService executorService = new ThreadPoolExecutor(
    processors, processors,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>(1000),
    new ThreadPoolExecutor.CallerRunsPolicy()
)
</code>```

Which basically just restrict the BlockingQueue size and make sure the master thread would take the job if the queue is full.

Thanks to @JBNizet and others for help in comments above.

ContentLicense: CC BY-SA 3.0

Title: FixedThreadPool memory leak

Body:
I have a Stream<String> and performing some actions on its items, which includes processing String and writing it to file.

Having the following groovy code, and processing 1 million items i'm running into the OutOfMemoryError.

ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())

stream.forEach { item ->
    executorService.execute {
        handle(item)
    }
}

executorService.shutdown()
executorService.awaitTermination(1, TimeUnit.DAYS)

After some profiling, i've found out that the Runnable tasks are not handled by gc and kept alive within the BlockingQueue until the app fails.

Why ExecutorService keeps the finished Runnable in the queue? and how it's supposed to be cleaned up?

Body:
The memory leak was caused because the BlockingQueue was filled up faster then ExecutorService pulled the tasks from it.

This was caused because iterating over stream with forEach method is pretty fast but tasks are running some more time.

Here's the solution I applied

def processors = Runtime.getRuntime().availableProcessors()
ExecutorService executorService = new ThreadPoolExecutor(
    processors, processors,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>(1000),
    new ThreadPoolExecutor.CallerRunsPolicy()
)

Which basically just restrict the BlockingQueue size and make sure the master thread would take the job if the queue is full.

Thanks to @JBNizet and others for help in comments above.


问:
Accessing IBM MQ via Domino agent - JMSException
Based upon thefollowing question:

Connecting to a Websphere MQ in Java with SSL/Keystore

I set up a Domino agent to access IBM MQ. However I get the message:

javax.jms.JMSException: MQJMS2005: failed to create MQQueueManager for 'ibmmq.mycorp.se:QMANAGER'

I am using the following code:

```<code>import lotus.domino.*;

import javax.jms.*;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.ibm.mq.jms.JMSC;
import com.ibm.mq.jms.MQQueueConnectionFactory;

import java.io.InputStream;
import java.security.KeyStore;

public class JavaAgent extends AgentBase {

    /*
     * not working. factory incorrect set?
     */

    private static final boolean debug = true;
    private static final boolean debugDefault = true;

    String msg;

    public void NotesMain() {

        lotus.domino.Session s = getSession();
        OpenLogItem oli = new OpenLogItem(s);

        try {
            msg = "Agent started";
            toLogDebug(msg);

            Environment env = setEnvVariables();

            InputStream res = this.getClass().getResourceAsStream("key.jks");
            char[] pw = {'p','a','s','s','w','o','r','d'};

            KeyStore ks;
            ks = KeyStore.getInstance("JKS");
            ks.load(res, pw);

            msg = "after keystore loaded";
            toLogDebug(msg);

             // Create a keystore object for the truststore
            KeyStore trustStore = KeyStore.getInstance("JKS");

            InputStream res2 = this.getClass().getResourceAsStream("key.jks");

             // Open our file and read the truststore (no password)
            trustStore.load(res2, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            keyManagerFactory.init(ks, pw);
            trustManagerFactory.init(trustStore);

            msg = "After Managers .init.";
            toLogDebug(msg);

            SSLContext sslContext = SSLContext.getInstance("SSL_TLS");

            msg = "SSLContext provider: " + sslContext.getProvider().toString();
            toLogDebug(msg);

            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

            msg = "After sslContext.init.";
            toLogDebug(msg);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            msg = "After getSocketFactory()";
            toLogDebug(msg);

            // Create default MQ connection factory
            MQQueueConnectionFactory factory = new MQQueueConnectionFactory();

            msg = "After MQQueueConnectionFactory()";
            toLogDebug(msg);

            // Customize the factory
             factory.setSSLSocketFactory(sslSocketFactory);
             // Use javac SSLTest.java -Xlint:deprecation
             factory.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
             factory.setQueueManager(env.getQueManager());
             factory.setHostName(env.getHost());
             factory.setChannel(env.getChannel());
             factory.setPort(env.getPort());
             factory.setSSLFipsRequired(false);
             factory.setSSLCipherSuite("TLS_RSA_WITH_AES_256_CBC_SHA256");

             msg = "After factory set";
             toLogDebug(msg);

             QueueConnection connection = null;
             connection = factory.createQueueConnection("",""); //empty user, pass to avoid MQJMS2013 messages

             msg = "after createQueueConnection(\"\",\"\")";
             toLogDebug(msg);

             connection.start();
             msg = "JMS SSL client connection started!";
             toLogDebug(msg);
             connection.close();

            msg =  "Agent done!";
            toLogDebug(msg);
         } catch (JMSException ex) {
             oli.logError(ex);
          } catch (Exception ex){
             oli.logError(ex);
          }
    }

    public Environment setEnvVariables(){

        Environment env = null;

        lotus.domino.Session s = getSession();
        try{
            Database adminDb = s.getCurrentDatabase();
            if (adminDb.isOpen()){
                View adminVw = adminDb.getView("settings");
                if (null != adminVw){
                    adminVw.setAutoUpdate(false);
                    Document adminDoc = adminVw.getFirstDocument();
                    if (null != adminDoc){

                        env = new Environment();
                        if (adminDoc.hasItem("mqhost")){
                            env.setHost(adminDoc.getItemValueString("mqhost"));
                        }
                        if (adminDoc.hasItem("mqport")){
                            env.setPort(Integer.parseInt(adminDoc.getItemValueString("mqport")));
                        }
                        if (adminDoc.hasItem("mqchannel")){
                            env.setChannel(adminDoc.getItemValueString("mqchannel"));
                        }
                        if (adminDoc.hasItem("mqquemanager")){
                            env.setQueManager(adminDoc.getItemValueString("mqquemanager"));
                        }

                    }
                }

            }
        }catch(Exception e){
            //
        }

        return env;

    }

    public void toLogDebug(String msg){
        if (debug){
            lotus.domino.Session session = getSession();
            OpenLogItem oli = new OpenLogItem(session);
            oli.logEvent(msg, OpenLogItem.SEVERITY_LOW, null);
        }
    }

    public void toLogDefault(String msg){
        if (debugDefault){
            lotus.domino.Session session = getSession();
            OpenLogItem oli = new OpenLogItem(session);
            oli.logEvent(msg, OpenLogItem.SEVERITY_HIGH, null);
        }
    }

    public class Environment{

        String host;
        int port;
        String channel;
        String queManager;

        lotus.domino.Session s = getSession();
        OpenLogItem oli = new OpenLogItem(s);

        public Environment(){
            oli.logEvent("Environment constructor", OpenLogItem.SEVERITY_LOW, null);
        }

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public int getPort() {
            return port;
        }

        public void setPort(int port) {
            this.port = port;
        }

        public String getChannel() {
            return channel;
        }

        public void setChannel(String channel) {
            this.channel = channel;
        }

        public String getQueManager() {
            return queManager;
        }

        public void setQueManager(String queManager) {
            this.queManager = queManager;
        }
    }

}
</code>```

I am storing my environment variables in a Notes keyword document. Does anyone has a clue why this code breaks at:

```<code>connection = factory.createQueueConnection("","");
</code>```

?

The key file is included as a resource with the agent and was provided to me.

答:
Does anyone has a clue why this code breaks at:

```<code>connection = factory.createQueueConnection("","");
</code>```

That is the line of code that actually causes the client to connect to the queue manager.  Are you using an IBM JRE or Oracle JRE?  What is the error message in the queue manager error log?

You are supplying a blank UserId and Password. Very bad idea.  Also, the queue manager's CHLAUTH rules should block a blank UserId.

Body:
Based upon thefollowing question:

Connecting to a Websphere MQ in Java with SSL/Keystore

I set up a Domino agent to access IBM MQ. However I get the message:

javax.jms.JMSException: MQJMS2005: failed to create MQQueueManager for 'ibmmq.mycorp.se:QMANAGER'

I am using the following code:

import lotus.domino.*;

import javax.jms.*;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.ibm.mq.jms.JMSC;
import com.ibm.mq.jms.MQQueueConnectionFactory;

import java.io.InputStream;
import java.security.KeyStore;

public class JavaAgent extends AgentBase {

    /*
     * not working. factory incorrect set?
     */

    private static final boolean debug = true;
    private static final boolean debugDefault = true;

    String msg;

    public void NotesMain() {

        lotus.domino.Session s = getSession();
        OpenLogItem oli = new OpenLogItem(s);

        try {
            msg = "Agent started";
            toLogDebug(msg);

            Environment env = setEnvVariables();

            InputStream res = this.getClass().getResourceAsStream("key.jks");
            char[] pw = {'p','a','s','s','w','o','r','d'};

            KeyStore ks;
            ks = KeyStore.getInstance("JKS");
            ks.load(res, pw);

            msg = "after keystore loaded";
            toLogDebug(msg);

             // Create a keystore object for the truststore
            KeyStore trustStore = KeyStore.getInstance("JKS");

            InputStream res2 = this.getClass().getResourceAsStream("key.jks");

             // Open our file and read the truststore (no password)
            trustStore.load(res2, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            keyManagerFactory.init(ks, pw);
            trustManagerFactory.init(trustStore);

            msg = "After Managers .init.";
            toLogDebug(msg);

            SSLContext sslContext = SSLContext.getInstance("SSL_TLS");

            msg = "SSLContext provider: " + sslContext.getProvider().toString();
            toLogDebug(msg);

            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

            msg = "After sslContext.init.";
            toLogDebug(msg);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            msg = "After getSocketFactory()";
            toLogDebug(msg);

            // Create default MQ connection factory
            MQQueueConnectionFactory factory = new MQQueueConnectionFactory();

            msg = "After MQQueueConnectionFactory()";
            toLogDebug(msg);

            // Customize the factory
             factory.setSSLSocketFactory(sslSocketFactory);
             // Use javac SSLTest.java -Xlint:deprecation
             factory.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
             factory.setQueueManager(env.getQueManager());
             factory.setHostName(env.getHost());
             factory.setChannel(env.getChannel());
             factory.setPort(env.getPort());
             factory.setSSLFipsRequired(false);
             factory.setSSLCipherSuite("TLS_RSA_WITH_AES_256_CBC_SHA256");

             msg = "After factory set";
             toLogDebug(msg);

             QueueConnection connection = null;
             connection = factory.createQueueConnection("",""); //empty user, pass to avoid MQJMS2013 messages

             msg = "after createQueueConnection(\"\",\"\")";
             toLogDebug(msg);

             connection.start();
             msg = "JMS SSL client connection started!";
             toLogDebug(msg);
             connection.close();

            msg =  "Agent done!";
            toLogDebug(msg);
         } catch (JMSException ex) {
             oli.logError(ex);
          } catch (Exception ex){
             oli.logError(ex);
          }
    }

    public Environment setEnvVariables(){

        Environment env = null;

        lotus.domino.Session s = getSession();
        try{
            Database adminDb = s.getCurrentDatabase();
            if (adminDb.isOpen()){
                View adminVw = adminDb.getView("settings");
                if (null != adminVw){
                    adminVw.setAutoUpdate(false);
                    Document adminDoc = adminVw.getFirstDocument();
                    if (null != adminDoc){

                        env = new Environment();
                        if (adminDoc.hasItem("mqhost")){
                            env.setHost(adminDoc.getItemValueString("mqhost"));
                        }
                        if (adminDoc.hasItem("mqport")){
                            env.setPort(Integer.parseInt(adminDoc.getItemValueString("mqport")));
                        }
                        if (adminDoc.hasItem("mqchannel")){
                            env.setChannel(adminDoc.getItemValueString("mqchannel"));
                        }
                        if (adminDoc.hasItem("mqquemanager")){
                            env.setQueManager(adminDoc.getItemValueString("mqquemanager"));
                        }

                    }
                }

            }
        }catch(Exception e){
            //
        }

        return env;

    }

    public void toLogDebug(String msg){
        if (debug){
            lotus.domino.Session session = getSession();
            OpenLogItem oli = new OpenLogItem(session);
            oli.logEvent(msg, OpenLogItem.SEVERITY_LOW, null);
        }
    }

    public void toLogDefault(String msg){
        if (debugDefault){
            lotus.domino.Session session = getSession();
            OpenLogItem oli = new OpenLogItem(session);
            oli.logEvent(msg, OpenLogItem.SEVERITY_HIGH, null);
        }
    }

    public class Environment{

        String host;
        int port;
        String channel;
        String queManager;

        lotus.domino.Session s = getSession();
        OpenLogItem oli = new OpenLogItem(s);

        public Environment(){
            oli.logEvent("Environment constructor", OpenLogItem.SEVERITY_LOW, null);
        }

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public int getPort() {
            return port;
        }

        public void setPort(int port) {
            this.port = port;
        }

        public String getChannel() {
            return channel;
        }

        public void setChannel(String channel) {
            this.channel = channel;
        }

        public String getQueManager() {
            return queManager;
        }

        public void setQueManager(String queManager) {
            this.queManager = queManager;
        }
    }

}

I am storing my environment variables in a Notes keyword document. Does anyone has a clue why this code breaks at:

connection = factory.createQueueConnection("","");

?

The key file is included as a resource with the agent and was provided to me.

Body:
Does anyone has a clue why this code breaks at:

connection = factory.createQueueConnection("","");

That is the line of code that actually causes the client to connect to the queue manager.  Are you using an IBM JRE or Oracle JRE?  What is the error message in the queue manager error log?

You are supplying a blank UserId and Password. Very bad idea.  Also, the queue manager's CHLAUTH rules should block a blank UserId.


问:
lodash pick: set value if key not set
I have the following two arrays:

```<code>var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
]
</code>```

I'd like to clean up resultsArr such that it only has the keys found in headerKeys.
My desired output looks like this:

```<code>[
    { title:"test 1", name: "test1", address: "" },
    { title:"test 2", name: "test2", address: "" }
]
</code>```

This is the code I'm currently using:

```<code>_.chain(resultsArr).map(function(item){
    return _.chain(item).pick(headerKeys).value()
}).value()
</code>```

This outputs:

```<code>[
    { title:"test 1", name: "test1" },
    { title:"test 2", name: "test2" }
]
</code>```

It's pretty close to what I want, but it will not show address since it isn't set. Is there anyway to force it to show the key even if it has no value?

Also, if you have suggestions on how to improve my lodash chain, that would be great.

答:
You can create a function getModel() to return your model, and then without lodash:

getModel= ()=>({ title:'', name:'', address:'default' });

var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
];

var result = resultsArr.map(function(obj) {
  var model = getModel();
  for (var key in model) {
    if (obj.hasOwnProperty(key)) {
      model[key] = obj[key];
    }
  }
  return model;
});

console.log(result)```

Title: lodash pick: set value if key not set

Body:
I have the following two arrays:

var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
]

I'd like to clean up resultsArr such that it only has the keys found in headerKeys.
My desired output looks like this:

[
    { title:"test 1", name: "test1", address: "" },
    { title:"test 2", name: "test2", address: "" }
]

This is the code I'm currently using:

_.chain(resultsArr).map(function(item){
    return _.chain(item).pick(headerKeys).value()
}).value()

This outputs:

[
    { title:"test 1", name: "test1" },
    { title:"test 2", name: "test2" }
]

It's pretty close to what I want, but it will not show address since it isn't set. Is there anyway to force it to show the key even if it has no value?

Also, if you have suggestions on how to improve my lodash chain, that would be great.


问:
Does the http client of angular2 throw an exception if status in Response is not in 2XX series?
While doing a map for the returned Observable from an HTTP request if the status code of the response doesn't belong to the 2xx series the control reaches the catch block on itself and doesn't even come under the success callback of the map. Is this how it is supposed to work? Where can I find a relevant code for this?
Am I correct in saying that its the status code in the response which makes it go to the catch (unless obviously, I don't have an error inside my map itself)?

答:
Yes. Angular's HTTP implementation examines the status code and emits an error from the observable if an unsucessful status code is received.

See the isSuccess method in http_utils.ts:

export const isSuccess = (status: number): boolean => (status >= 200 && status < 300);
```

<p>And the <code>XHRConnection</code> implementation in <code>xhr_backend.ts</code>:</p>

<pre class="lang-ts prettyprint-override"><code>const response = new Response(responseOptions);
response.ok = isSuccess(status);
if (response.ok) {
  responseObserver.next(response);
  // TODO(gdi2290): defer complete if array buffer until done
  responseObserver.complete();
  return;
}
responseObserver.error(response);
</code>```

Body:
Yes. Angular's HTTP implementation examines the status code and emits an error from the observable if an unsucessful status code is received.

See the isSuccess method in http_utils.ts:

export const isSuccess = (status: number): boolean => (status >= 200 && status < 300);

And the XHRConnection implementation in xhr_backend.ts:

const response = new Response(responseOptions);
response.ok = isSuccess(status);
if (response.ok) {
  responseObserver.next(response);
  // TODO(gdi2290): defer complete if array buffer until done
  responseObserver.complete();
  return;
}
responseObserver.error(response);


问:
npm install -g yo tunneling socket error
I am not able to run the command npm install -g yo .. and I am getting the following error !

E:\OneWeb\ngApp1>npm install -g yo
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "-g" "yo"
npm ERR! node v6.2.1
npm ERR! npm  v3.9.3
npm ERR! code ECONNRESET

npm ERR! network tunneling socket could not be established, cause=write EPROTO 101057795:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:794:
npm ERR! network
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     E:\OneWeb\ngApp1\npm-debug.log

答:
Also set strict-ssl to false with the command:
npm config set strict-ssl false


问:
Cannot resolve @style/Theme.AppCompat.Light.NoActionBar
I have an AppCompatActivity, and the moment I want to run my code. I get this error at the start of the Activity:

You need to use a Theme.AppCompat theme (or descendant) with this activity

If I use Theme.AppCompat as it advises me, but then I get this:

Cannot resolve @style/Theme.AppCompat.Light.NoActionBar

Neither in the AndroidManifest.xml, nor in the styles files I can use it.

I am using those dependencies:

```<code>compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:design:25.3.1'
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.parse:parse-android:1.15.8'
compile 'com.google.firebase:firebase-auth:10.2.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile "com.android.support:support-core-utils:25.4.0"
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:support-v4:25.4.0'
</code>```

答: Clean & rebuild your project !</p>

Body:
I have an AppCompatActivity, and the moment I want to run my code. I get this error at the start of the Activity:

You need to use a Theme.AppCompat theme (or descendant) with this activity

If I use Theme.AppCompat as it advises me, but then I get this:

Cannot resolve @style/Theme.AppCompat.Light.NoActionBar

Neither in the AndroidManifest.xml, nor in the styles files I can use it.

I am using those dependencies:

compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:design:25.3.1'
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.parse:parse-android:1.15.8'
compile 'com.google.firebase:firebase-auth:10.2.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile "com.android.support:support-core-utils:25.4.0"
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:support-v4:25.4.0'

Body: Clean & rebuild your project !


问:
How would I replace a single character in a string?
I'm coding a little python program for ROT13.

If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'.

A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front.

This means I need to replace each character, now who would I do that?

I tried importing the re function but It didn't work. This is what I got so far.

```<code>import re

Alpha = input("Input the word you would like translated")

Alpha = re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm',
Alpha)
print(Alpha)
</code>```

Help would be very much appreciated.

答:
I think you want this</p>

```<code>import string

inputchar = input('Enter input: ')
printables = [x for x in string.ascii_lowercase]
index = (printables.index(inputchar) + 13)%26
print(printables[index])
</code>```

Body:
I'm coding a little python program for ROT13.

If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'.

A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front.

This means I need to replace each character, now who would I do that?

I tried importing the re function but It didn't work. This is what I got so far.

import re

Alpha = input("Input the word you would like translated")

Alpha = re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm',
Alpha)
print(Alpha)

Help would be very much appreciated.

Body:
I think you want this

import string

inputchar = input('Enter input: ')
printables = [x for x in string.ascii_lowercase]
index = (printables.index(inputchar) + 13)%26
print(printables[index])


问:
WPF pre-render a list w/o actually showing it
Is there a way to "pre-render" a list in WPF without actually showing it to the user? I have a list that renders fairly slowly ( a few seconds ) the first time it is displayed to the user.

I'd like to pre-render/pre-draw the list so that the few seconds it takes to display the list to the users is not noticeable. I'd like this to happen while the app is starting up - while my splash screen is displayed.

What is the best way to accomplish this?

EDIT:

Here is my list item style. As you can see the target type is a Button. The button also has a RoutedEvent (Command) set on it.

```<code><Style x:Key="Button_ProductFinder_Item" TargetType="Button">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">

                <Grid Width="690" Height="181"   >

                    <Image Name="Up" Source="{StaticResource Img_ProductFinder_FriendUp}" Stretch="Uniform"/>
                    <Image Name="Down" Source="{StaticResource Img_ProductFinder_FriendDn}" Visibility="Hidden" Stretch="Uniform"/>

                    <Canvas Name="Clip" ClipToBounds="True" Height="162" Width="175" HorizontalAlignment="Left" Margin="0,10,0,0" >
                        <Image Name="DynamicFriend"  Stretch="UniformToFill" Canvas.Left="16" Canvas.Top="-10" HorizontalAlignment="Left"  Source="{Binding ImageSource}" Height="162" Width="162" />
                        <Canvas.RenderTransform>
                            <TransformGroup>
                                <TranslateTransform />
                            </TransformGroup>
                        </Canvas.RenderTransform>
                    </Canvas>

                    <TextBlock Name="DynamicName" Margin="210,69,0,0"  Style="{StaticResource ButtonFriend_Textstyle}"
                                   TextWrapping="Wrap" HorizontalAlignment="Left" Width="440" VerticalAlignment="Stretch" Height="Auto"
                                   Text="{Binding ProductName}"  />
                </Grid>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter TargetName="Up" Property="Visibility" Value="Hidden"/>
                        <Setter TargetName="Down" Property="Visibility" Value="Visible"/>
                        <Setter TargetName="Clip" Property="RenderTransform">
                            <Setter.Value>
                                <TransformGroup>
                                    <TranslateTransform Y="2"/>
                                </TransformGroup>
                            </Setter.Value>
                        </Setter>
                        <Setter TargetName="DynamicName" Property="RenderTransform">
                            <Setter.Value>
                                <TransformGroup>
                                    <TranslateTransform Y="2"/>
                                </TransformGroup>
                            </Setter.Value>
                        </Setter>
                        <Setter TargetName="DynamicName" Property="Foreground" Value="#FFFFFF"/>
                        <Trigger.EnterActions>
                            <ctrls:ButtonSoundPlayerAction SoundFile="buttonclick.wav"/>
                        </Trigger.EnterActions>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

答:
Check WHAT is slow. Really. Itf it is like the db filling up the list, your question is totally off (as the perforamnce is not WPF realted).

How large is the list? I have a list of 5000 elements rendering in a moments notice. Mosty because my 4.0 virtual list only renders what is on the list. You are not data bound while fillng up the list, or?

Finally, what is slow in the rndering? Use a wpf profiler to find out and tell us - because at the nd of the day you may simply try to optimize the wrong thing.

ContentLicense: CC BY-SA 2.5


问:
How do I convert a class property to integer
I have the following class:

```<code>class temp_con():
    def __init__(self):
        self.t = 0
    @property
    def t(self):
        return self.t
    @t.setter
    def t(self,value):
        self.t = value
</code>```

I need to use it to compare against a number following this logic:

```<code>if num <= temp_con.t - 2:
    #dothing
</code>```

However i get the error:

Type error: unsupported operand type for -: 'property' and 'int'<

I have tried int(temp_con.t) and getattr(temp_con, t) but those did not work.

How can I utilize the property as an int?

答:
You're accessing t on CLASS, not on an OBJECT of CLASS.

Try:

```<code>q = temp_con()
if num <= q.t - 2:
  pass
</code>```

In you code temp_con.t returns property object, which wraps getter (and setter) you've defined in your class code, but it doesnt execute it.

UPDATE: (memo: read twice)
There's also another problem with your code. First (well, it's second in code, but it will happen first) you define getter t, then later you OVERWRITE it with self.t = 0. As a result you'll get (as t) property accessible as a class member (which happens in your example) and value 0 as object's member.

ContentLicense: CC BY-SA 4.0

Body:
I have the following class:

class temp_con():
    def __init__(self):
        self.t = 0
    @property
    def t(self):
        return self.t
    @t.setter
    def t(self,value):
        self.t = value

I need to use it to compare against a number following this logic:

if num <= temp_con.t - 2:
    #dothing

However i get the error:

Type error: unsupported operand type for -: 'property' and 'int'<

I have tried int(temp_con.t) and getattr(temp_con, t) but those did not work.

How can I utilize the property as an int?

Body:
You're accessing t on CLASS, not on an OBJECT of CLASS.

Try:

q = temp_con()
if num <= q.t - 2:
  pass

In you code temp_con.t returns property object, which wraps getter (and setter) you've defined in your class code, but it doesnt execute it.

UPDATE: (memo: read twice)
There's also another problem with your code. First (well, it's second in code, but it will happen first) you define getter t, then later you OVERWRITE it with self.t = 0. As a result you'll get (as t) property accessible as a class member (which happens in your example) and value 0 as object's member.


问:
Django create a Datatable using MSSQL
Hello I am new to using Django and would like to create a datatable with data that is stored in a database of an MSSQL server. I have managed to connect Django via django_mssql but I do not know how to access a table since there are many in the database. Thanks for your help. </p>

答: first configure your db in Django setting and then read this docfile https://docs.djangoproject.com/en/1.11/howto/legacy-databases/</p>

Title: Django create a Datatable using MSSQL


问:
Android Local Unit Test returns error with a new Intent
I'm trying to make a simple Local Unit Test on an Android method, but when I call new Intent (), it returns an error: Method threw 'java.lang.RuntimeException' exception. Cannot evaluate android.content.Intent.toString()

I tried to @mock Intent intent and also @PrepareForTest({Intent.class}), but I still get the same error...

Am I doing something wrong? Do I need anything else? Do I need to use Instrumented test for this?

Here's the code:

```<code>@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({Intent.class})
public class TimeFrameManagerTest
{

@Mock
Context mMockContext;

@Before
public void setUp ()
{

}

@Test
public void alarmSchedulePosteriorTime ()
{

    Intent intent = new Intent (); //Method threw 'java.lang.RuntimeException' exception. Cannot evaluate android.content.Intent.toString()

}

}
</code>```

答:
Go to:
Settings -> Build, Execution, Deployment -> Debugger -> Data Views -> Java and uncheck the option Enable 'toString()' object view

Body:
I'm trying to make a simple Local Unit Test on an Android method, but when I call new Intent (), it returns an error: Method threw 'java.lang.RuntimeException' exception. Cannot evaluate android.content.Intent.toString()

I tried to @mock Intent intent and also @PrepareForTest({Intent.class}), but I still get the same error...

Am I doing something wrong? Do I need anything else? Do I need to use Instrumented test for this?

Here's the code:

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({Intent.class})
public class TimeFrameManagerTest
{

@Mock
Context mMockContext;

@Before
public void setUp ()
{

}

@Test
public void alarmSchedulePosteriorTime ()
{

    Intent intent = new Intent (); //Method threw 'java.lang.RuntimeException' exception. Cannot evaluate android.content.Intent.toString()

}

}


答:
Ecmascript5 alternative:

var headerKeys = ["title","name","address"],
    resultsArr = [
        { title:"test 1", name: "test1", unrelatedKey: "blah" },
        { title:"test 2", name: "test2" }
    ];

resultsArr = resultsArr.map(function(o,i){
    var new_obj = {};
    headerKeys.forEach(function(k){
        new_obj[k] = o[k] || "";
    });
    return new_obj;
});

console.log(resultsArr);```

Title: lodash pick: set value if key not set


问:
GET Requests vs JavaScript
Alright, I have a JavaScript doing HTTP Requests to a PHP file onto the same directory. Then it's returning it's output.

Let's say there are over 50+ people doing this request simultaneously ... will it slow down anything? Yes, this may seem like a dumb question - but sorry. :|

Thank you.

答: Dealing with multiple requests at once will need server resources. It may or may not slow things down appreciably depending on how much load the server and network connection can handle.</p>

Title: GET Requests vs JavaScript


答:
I think you should use Activity instead of AppCompatActivity

Check this answer :
https://stackoverflow.com/a/21815015/8239508

Title: Cannot resolve @style/Theme.AppCompat.Light.NoActionBar


答:
You need an instance of the class in order to use the property and, as pointed out in other answers, you need to use a different name for your object variable. Try:

```<code>class temp_con():
    def __init__(self):
        self._t = 0

    @property
    def t(self):
        return self._t

    @t.setter
    def t(self,value):
        self._t = value

my_temp_con = temp_con()

if num <= my_temp_con.t - 2:
    pass
</code>```

Thus, to access the value of the property and not the property function, you have to access it through my_temp_con.t.

Title: How do I convert a class property to integer

Body:
You need an instance of the class in order to use the property and, as pointed out in other answers, you need to use a different name for your object variable. Try:

class temp_con():
    def __init__(self):
        self._t = 0

    @property
    def t(self):
        return self._t

    @t.setter
    def t(self,value):
        self._t = value

my_temp_con = temp_con()

if num <= my_temp_con.t - 2:
    pass

Thus, to access the value of the property and not the property function, you have to access it through my_temp_con.t.


答:
You need to use separate names for the property and the attribute it wraps. A good convention is to use the property name prefixed with a _ as the attribute name.

```<code>class TempCon:
    def __init__(self):
        self._t = 0

    @property
    def t(self):
        return self._t

    @t.setter
    def t(self, value):
        self._t = value
</code>```

Then you can access the property on an instance of the class.

```<code>temp_con = TempCon()
print(temp_con.t)
temp_con.t = 5
print(temp_con.t)
</code>```

Body:
You need to use separate names for the property and the attribute it wraps. A good convention is to use the property name prefixed with a _ as the attribute name.

class TempCon:
    def __init__(self):
        self._t = 0

    @property
    def t(self):
        return self._t

    @t.setter
    def t(self, value):
        self._t = value

Then you can access the property on an instance of the class.

temp_con = TempCon()
print(temp_con.t)
temp_con.t = 5
print(temp_con.t)


问:
Selecting fixed number of results through Django get_object_or_404
Through normal python, in views.py in Django, my code is:

```<code>latest_question_list = Question.objects.order_by('-pub_date')[:5]
</code>```

(Question is the name of my model)

I need to order my results as well as display only 5 results.

How do i do the same thing with get_object_or_404 function?

答:
You can use get_list_or_404 with your current Queryset, thereby wrapping the 404 logic in the function:

```<code>from django.shortcuts import get_list_or_404

latest_question_list = get_list_or_404(Question.objects.order_by('-pub_date')[:5])
</code>```

Body:
Through normal python, in views.py in Django, my code is:

latest_question_list = Question.objects.order_by('-pub_date')[:5]

(Question is the name of my model)

I need to order my results as well as display only 5 results.

How do i do the same thing with get_object_or_404 function?

Body:
You can use get_list_or_404 with your current Queryset, thereby wrapping the 404 logic in the function:

from django.shortcuts import get_list_or_404

latest_question_list = get_list_or_404(Question.objects.order_by('-pub_date')[:5])


问:
Adding null conditional to function throw not defined
I´m new with Angular and JS and I have a funcion that load a simple select like this:

Angular Ctrl

```<code>function detalleRegistrosCtrl($scope, apiService, notificationService, $rootScope, $location, $stateParams, $http, $state) {
        Dropzone.autoDiscover = false;
        $scope.catalogoPadre = $stateParams.catalogopadre;

        cargarCatalogo();

    $scope.regresar = function () {
        $state.go("root.catalogosgenericos");
    }

    function errorCatalogo(res) {
        bootbox.alert("Error al cargar el catalogo" + res.data);
    }

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {

                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);
</code>```

Problem is when I try to add an if conditional into cargarCatalogo() function. When I do it as:

```<code>    if ($scope.catalogoPadre != null) {

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {
                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);
     }
</code>```

I´m getting into chrome console:

Error: cargarCatalogo is not defined

Can someone explain me what is wrong? I just add a conditional to a function.

答:
It is simple because cargarCatalogo() is defined inside an if statement.

You will have to define it outside if.

And then while using it wrap it the function call in if statement.

If you define it inside if it will never get defined until you run the code and the if statement is executed. Hence it will throw error.

Body:
I´m new with Angular and JS and I have a funcion that load a simple select like this:

Angular Ctrl

function detalleRegistrosCtrl($scope, apiService, notificationService, $rootScope, $location, $stateParams, $http, $state) {
        Dropzone.autoDiscover = false;
        $scope.catalogoPadre = $stateParams.catalogopadre;

        cargarCatalogo();

    $scope.regresar = function () {
        $state.go("root.catalogosgenericos");
    }

    function errorCatalogo(res) {
        bootbox.alert("Error al cargar el catalogo" + res.data);
    }

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {

                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);

Problem is when I try to add an if conditional into cargarCatalogo() function. When I do it as:

    if ($scope.catalogoPadre != null) {

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {
                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);
     }

I´m getting into chrome console:

Error: cargarCatalogo is not defined

Can someone explain me what is wrong? I just add a conditional to a function.


问:
How can I customize the tab-to-space conversion factor?
How do I customize the tab-to-space conversion factor when using Visual Studio Code?

For instance, right now in HTML it appears to produce two spaces per press of TAB, but in TypeScript it produces 4.

答:
That is lonefy.vscode-js-css-html-formatter to blame. Disable it, and install HookyQR.beautify.

Now on save your tabs wouldn't be converted.


问:
Index numbers for row-wise duplicate entries using numpy/pandas in python
I have a numpy array/pandas data frame

```<code>[[0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [0 0 1 0],
 [0 0 1 0]]
</code>```

I need index number of row duplicates for this array. The results should be something like (0,2,4), (1,3), (5,6).

So far I have a work around, like I am running loops, one with unique values of the array rows against the actual array rows. That gives me results but not in the fashion I would want them to be.
This is the code I have made which gives me pairs but for a large array, this is very messy.

```<code>for i, row in enumerate(array):
    for j, row1 in enumerate(unique(array)):
        if tuple(row)==tuple(row1):
            pair.append(tuple([j,i]))
</code>```

my results looks like this:

```<code> [(0, 276),(1, 2931),(2, 3891),(3, 2165),(4, 1822),(5, 1241),
 (5, 2635),(5, 2644),(5, 2862),(5, 3296)]
</code>```

My array is very big, so this way I am manually choosing tuples based on the first value as the indicator for duplicates, then I choose the actual row number which is a duplicate. for Ex. - tuples having 5 as their first value mean row 1241 is duplicated at 2635, 2644, 2862 and 3296.

Can anyone suggest me a better way to work on this problem.
I have looked around here but nothing concrete I could get.

答:
a being your array, a efficient way to do that is to consider each row like bytes, to accelerate row comparisons:

```<code>v=np.array(a)
rows=v.view(dtype=np.void(v.strides[0]))
</code>```

As exemple :

```<code>In [4]: a,b=randint(0,1,(2,10000))

In [5]: %timeit tuple(a)==tuple(b)
100 loops, best of 3: 3.12 ms per loop

In [6]: %timeit str(a)==str(b)
1000 loops, best of 3: 901 µs per loop

In [7]: %timeit typ=np.void(a.strides[0]);a.view(typ)==b.view(typ)
1000 loops, best of 3: 227 µs per loop
</code>```

rows is now :

```<code>array([[[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]],
       [[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]]],
      dtype='|V16')
</code>```

Then you can sort them, locating the base member with the return_inverse parameter of np.unique  :

```<code>uniq,inverse=np.unique(rows,return_inverse=True)
</code>```

And pretty print the results :

```<code>In [28]: [(a[i] , list((inverse==i).nonzero()[0])) for i in range(uniq.size)]
Out[28]: [([0, 0, 0, 1], [0, 2, 4]), ([1, 0, 0, 1], [5, 6]), ([0, 0, 0, 1], [1, 3])]
</code>```

Body:
I have a numpy array/pandas data frame

[[0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [0 0 1 0],
 [0 0 1 0]]

I need index number of row duplicates for this array. The results should be something like (0,2,4), (1,3), (5,6).

So far I have a work around, like I am running loops, one with unique values of the array rows against the actual array rows. That gives me results but not in the fashion I would want them to be.
This is the code I have made which gives me pairs but for a large array, this is very messy.

for i, row in enumerate(array):
    for j, row1 in enumerate(unique(array)):
        if tuple(row)==tuple(row1):
            pair.append(tuple([j,i]))

my results looks like this:

 [(0, 276),(1, 2931),(2, 3891),(3, 2165),(4, 1822),(5, 1241),
 (5, 2635),(5, 2644),(5, 2862),(5, 3296)]

My array is very big, so this way I am manually choosing tuples based on the first value as the indicator for duplicates, then I choose the actual row number which is a duplicate. for Ex. - tuples having 5 as their first value mean row 1241 is duplicated at 2635, 2644, 2862 and 3296.

Can anyone suggest me a better way to work on this problem.
I have looked around here but nothing concrete I could get.

Body:
a being your array, a efficient way to do that is to consider each row like bytes, to accelerate row comparisons:

v=np.array(a)
rows=v.view(dtype=np.void(v.strides[0]))

As exemple :

In [4]: a,b=randint(0,1,(2,10000))

In [5]: %timeit tuple(a)==tuple(b)
100 loops, best of 3: 3.12 ms per loop

In [6]: %timeit str(a)==str(b)
1000 loops, best of 3: 901 µs per loop

In [7]: %timeit typ=np.void(a.strides[0]);a.view(typ)==b.view(typ)
1000 loops, best of 3: 227 µs per loop

rows is now :

array([[[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]],
       [[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]],
       [[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]]],
      dtype='|V16')

Then you can sort them, locating the base member with the return_inverse parameter of np.unique  :

uniq,inverse=np.unique(rows,return_inverse=True)

And pretty print the results :

In [28]: [(a[i] , list((inverse==i).nonzero()[0])) for i in range(uniq.size)]
Out[28]: [([0, 0, 0, 1], [0, 2, 4]), ([1, 0, 0, 1], [5, 6]), ([0, 0, 0, 1], [1, 3])]


问:
Set select rails with no related model collection
Im trying to setup a combobox with a no related model collection, it will be displayed in my Stand model new view, but they are not related directly.

It is like show the classic country -> state -> city relation form where country and city are not directly related, so what I want to do is just show a "country" combo when I am creating a new city to display just related states! PLS HELP! IM DYING DOING THIS!

I want to do something like this:

```<code>      <div class="form-group">
        <%
          concat f.cr_ubicacion.select :codpabellon,
          Mtopabellon.order(:nombre), :codpabellon, :nombre, {},
          {class: "store-select"}
        %>
      </div>
</code>```

答:
Solved it!

```<code>        <%
          concat f.select :idubicacion, Mtopabellon.all.collect {|p| [
          p.nombre, p.codpabellon ] }, {prompt: 'Seleccione una
          pabellon'}, :class=>'form-control', :id => 'cmbPab'
        %>
</code>```

Just setup the collection I needed even using a different :idubicacion and it works!

Body:
Im trying to setup a combobox with a no related model collection, it will be displayed in my Stand model new view, but they are not related directly.

It is like show the classic country -> state -> city relation form where country and city are not directly related, so what I want to do is just show a "country" combo when I am creating a new city to display just related states! PLS HELP! IM DYING DOING THIS!

I want to do something like this:

        <%
          concat f.cr_ubicacion.select :codpabellon,
          Mtopabellon.order(:nombre), :codpabellon, :nombre, {},
          {class: "store-select"}
        %>

Body:
Solved it!

        <%
          concat f.select :idubicacion, Mtopabellon.all.collect {|p| [
          p.nombre, p.codpabellon ] }, {prompt: 'Seleccione una
          pabellon'}, :class=>'form-control', :id => 'cmbPab'
        %>

Just setup the collection I needed even using a different :idubicacion and it works!


问:
Publishing multiple versions of one app on Google Market
I have an Android app that I would like to display high quality images with. However there are many different screen sizes and ratios. I know there are filters to show apps in Market only for devices with small/medium/large screens.

If I put images of both sizes in 1 app it will double the size of the app, right?

Is it a good practice to make multiple versions for different screen sizes?

I would like to make 1 app in 3 versions for such devices:

medium screen mdpi

medium screen hdpi + large screen mdpi

large (tablets)

If it's possible to do it how can I specify them in manifests? Or is it somewhere in market?

答:
Android has a built-in mechanism for having resources designed for different screen sizes and pixel densities. It's called resource directory qualifiers, and you can read all about it here.

For example, for small screen sizes, you could create a specific layout file and place it in the res/layout-small directory. For a larger screen, you could create a layout file with the same name and place it in the res/layout-large (or res/layout-xlarge) directory.

For pixel density, you could create a small version of your image resources and place them in the res/drawable-ldpi directory (lower pixel densities). And for higher pixel densities, you could create alternate versions and place them in the res/drawable-hdpi directory.

I'd encourage you to read the page on Supporting Multiple Screens, and let Android help you out with its built-in mechanisms. Creating three separate copies of your app is harder for you to maintain, and it confuses potential users (most of whom probably neither know nor care about "pixel densities"). What's to stop them from downloading the wrong version of your app, and getting a lousy experience because of it?


答:
Similar to your original code, you can add a _.set function within the _.map function: https://codepen.io/aprouja1/pen/xrzRjN?editors=0010

```<code>_.map(resultsArr,(el)=>{
  return _.pick(_.set(el,'address',""),headerKeys)
})
</code>```

Title: lodash pick: set value if key not set

Body:
I have the following two arrays:

var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
]

I'd like to clean up resultsArr such that it only has the keys found in headerKeys.
My desired output looks like this:

[
    { title:"test 1", name: "test1", address: "" },
    { title:"test 2", name: "test2", address: "" }
]

This is the code I'm currently using:

_.chain(resultsArr).map(function(item){
    return _.chain(item).pick(headerKeys).value()
}).value()

This outputs:

[
    { title:"test 1", name: "test1" },
    { title:"test 2", name: "test2" }
]

It's pretty close to what I want, but it will not show address since it isn't set. Is there anyway to force it to show the key even if it has no value?

Also, if you have suggestions on how to improve my lodash chain, that would be great.

Body:
Similar to your original code, you can add a _.set function within the _.map function: https://codepen.io/aprouja1/pen/xrzRjN?editors=0010

_.map(resultsArr,(el)=>{
  return _.pick(_.set(el,'address',""),headerKeys)
})


问:
Animation moves just on first button click
I have one question.
I have a button ant when I click on it, imageView (with objectAnimator) goes down. I have my ˝animation down˝ in onClick and every thing is very simple, I click on the button and image goes down - there I have a question.

First, there is my code:

```<code>ObjectAnimator objectAnimatorBlock1 = getDownObjectAnimator(imageBlock1);
    animatorSetBlock1 = new AnimatorSet();
    animatorSetBlock1.play(objectAnimatorBlock1);
    animatorSetBlock1.start();

private ObjectAnimator getDownObjectAnimator(View v) {
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(v, "translationY", 0.0f, 860.0f);
        objectAnimator.setDuration(2000);
        return objectAnimator;

and XML:

<ImageView
        android:contentDescription="@string/image_description"
        android:layout_marginRight="202dp"
        android:layout_marginEnd="202dp"
        android:layout_marginTop="-155dp"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:id="@+id/imageBlock1"
        android:layout_gravity="end|center_vertical"
        android:src="@drawable/distance11" />
<Button
    android:layout_width="60dp"
    android:onClick="countIN"
    android:layout_marginLeft="20dp"
    android:layout_height="61dp"
    android:text="DROP THE BLOCK"
    android:id="@+id/button2"
    android:layout_gravity="start|center_vertical"
    android:background="@drawable/layout100"
    android:textStyle="normal|bold|italic" />
</code>```

My problem is: First time when I click on the button, image goes down and there also stand still(that is correct), but I would like that image goes down JUST when I first time click on a button. After first click animation is clear(finish animation) - then on second, third, fourth,... click , there is not any effect on image(it do not move). How can I do these?

答:
You can use AnimationUtils instead of ObjectAnimator. You can write your animation in xml and store it in the R.anim folder. Then, you can apply it to the button's onClick listener as follows:

```<code>//image is your ImageView
button.setOnClickListener(

...

//Suppose your animation is saved as moveDown.xml
Animation moveDown = AnimationUtils.loadAnimation(getApplicationContext, R.anim.
image.startAnimation(moveDown);

...

});
</code>```

This will make your ImageView (image) perform the animation each time you click the button. I hope this helps you out.

Body:
I have one question.
I have a button ant when I click on it, imageView (with objectAnimator) goes down. I have my ˝animation down˝ in onClick and every thing is very simple, I click on the button and image goes down - there I have a question.

First, there is my code:

ObjectAnimator objectAnimatorBlock1 = getDownObjectAnimator(imageBlock1);
    animatorSetBlock1 = new AnimatorSet();
    animatorSetBlock1.play(objectAnimatorBlock1);
    animatorSetBlock1.start();

private ObjectAnimator getDownObjectAnimator(View v) {
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(v, "translationY", 0.0f, 860.0f);
        objectAnimator.setDuration(2000);
        return objectAnimator;

and XML:

<ImageView
        android:contentDescription="@string/image_description"
        android:layout_marginRight="202dp"
        android:layout_marginEnd="202dp"
        android:layout_marginTop="-155dp"
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:id="@+id/imageBlock1"
        android:layout_gravity="end|center_vertical"
        android:src="@drawable/distance11" />
<Button
    android:layout_width="60dp"
    android:onClick="countIN"
    android:layout_marginLeft="20dp"
    android:layout_height="61dp"
    android:text="DROP THE BLOCK"
    android:id="@+id/button2"
    android:layout_gravity="start|center_vertical"
    android:background="@drawable/layout100"
    android:textStyle="normal|bold|italic" />

My problem is: First time when I click on the button, image goes down and there also stand still(that is correct), but I would like that image goes down JUST when I first time click on a button. After first click animation is clear(finish animation) - then on second, third, fourth,... click , there is not any effect on image(it do not move). How can I do these?

Body:
You can use AnimationUtils instead of ObjectAnimator. You can write your animation in xml and store it in the R.anim folder. Then, you can apply it to the button's onClick listener as follows:

//image is your ImageView
button.setOnClickListener(

...

//Suppose your animation is saved as moveDown.xml
Animation moveDown = AnimationUtils.loadAnimation(getApplicationContext, R.anim.
image.startAnimation(moveDown);

...

});

This will make your ImageView (image) perform the animation each time you click the button. I hope this helps you out.


问:
How can I cancel a ProgressBar?
So, I have switched to using a ProgressBar from ProgressDialog and I don't find now any method to make the ProgressBar cancellable meaning if I click anywhere outside the ProgressBar's view area, it will dismiss and also I want to attach a listener to it so that I am able to execute some code when it does get canceled.

This ProgressBar is the simplest, indeterminate, non-customized one, I have:

```<code><ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>
</code>```

How can I achieve the above?

答: I assume your ProgressBar sits in some layout e.g. a LinearLayout. You could create an OnTouchListener and apply it to the layout which contains your ProgressBar, apply the same OnTouchListener to any other Views which are visible. You can dismiss the ProgressBar and execute other code from within the OnTouchListener. </p>

Title: How can I cancel a ProgressBar?

Body:
So, I have switched to using a ProgressBar from ProgressDialog and I don't find now any method to make the ProgressBar cancellable meaning if I click anywhere outside the ProgressBar's view area, it will dismiss and also I want to attach a listener to it so that I am able to execute some code when it does get canceled.

This ProgressBar is the simplest, indeterminate, non-customized one, I have:

<ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

How can I achieve the above?


问:
My footer will not stick to the bottom
So I am making a website like a little mock up one as I have just started learning and the footer just won't stay at the bottom and it is killing me. When I load the page it starts at the bottom and then when I scroll down it stays in the same place and is stuck where it started and won't start at the bottom of the page.

```<code>#footer {
    text-align: right;
    padding: 10px;
    background-color: #07889B;
    position: absolute;
    bottom: 0;
    width: 1200px;
</code>```

}

答:
This should work </p>

```<code>#footer {
    text-align: right;
    padding: 10px;
    background-color: #07889B;
    position: fixed;
    bottom: 0;
    left:0;
    width: 1200px;//or width:100%;
}
</code>```

Title: My footer will not stick to the bottom

Body:
So I am making a website like a little mock up one as I have just started learning and the footer just won't stay at the bottom and it is killing me. When I load the page it starts at the bottom and then when I scroll down it stays in the same place and is stuck where it started and won't start at the bottom of the page.

#footer {
    text-align: right;
    padding: 10px;
    background-color: #07889B;
    position: absolute;
    bottom: 0;
    width: 1200px;

}

Body:
This should work

#footer {
    text-align: right;
    padding: 10px;
    background-color: #07889B;
    position: fixed;
    bottom: 0;
    left:0;
    width: 1200px;//or width:100%;
}


问:
Upload .env environment variables to elastic beanstalk
As far as I know the only way to set environment variables to elastic beanstalk is either:

The AWS Online Console.

The eb setenv command.

I have a .env file in my project that contains all of my environment variables over 100 variables and I'm looking for a way to push them all to the eb instance at the same time.

答:
First off, you should note that Elastic Beanstalk has a limit of fifty (50) environment variables per environment.

Now, if you've got a bunch of environment variables set in a .env file, an easy way to set them en-mass is to just dump them all into the eb setenv command like this...

```<code>eb setenv `cat .env | sed '/^#/ d' | sed '/^$/ d'`
</code>```

This will set them all in one shot and save you spending all night on the aws console page. The sed command remove commented lines and new lines.

Explain Shell

Body:
First off, you should note that Elastic Beanstalk has a limit of fifty (50) environment variables per environment.

Now, if you've got a bunch of environment variables set in a .env file, an easy way to set them en-mass is to just dump them all into the eb setenv command like this...

eb setenv `cat .env | sed '/^#/ d' | sed '/^$/ d'`

This will set them all in one shot and save you spending all night on the aws console page. The sed command remove commented lines and new lines.

Explain Shell


问:
How to filter and map array of documents in MongoDB query?
So I've got these documents in my people collection:

```<code>{
        "_id" : ObjectId("595c0630939a8ae59053a9c3"),
        "name" : "John Smith",
        "age" : 37,
        "location" : "San Francisco, CA",
        "hobbies" : [
                {
                        "name" : "Cooking",
                        "type" : "Indoor",
                        "regular" : true
                },
                {
                        "name" : "Baseball",
                        "type" : "Outdoor",
                        "regular" : false
                }
        ]
}
{
        "_id" : ObjectId("595c06b7939a8ae59053a9c4"),
        "name" : "Miranda Thompson",
        "age" : 26,
        "location" : "Modesto, CA",
        "hobbies" : [
                {
                        "name" : "Lego building",
                        "type" : "Indoor",
                        "regular" : false
                },
                {
                        "name" : "Yoga",
                        "type" : "Indoor",
                        "regular" : false
                }
        ]
}
{
        "_id" : ObjectId("595c078e939a8ae59053a9c5"),
        "name" : "Shelly Simon",
        "age" : 26,
        "location" : "Salt Lake City, UT",
        "hobbies" : [
                {
                        "name" : "Hunting",
                        "type" : "Outdoor",
                        "regular" : false
                },
                {
                        "name" : "Soccer",
                        "type" : "Outdoor",
                        "regular" : true
                }
        ]
}
</code>```

I am trying to filter my "hobbies" array only to regular hobbies AND project the fields _id, name, age and hobby's name and type.

I want my output to be something like this:

```<code>{
        "_id" : ObjectId("595c0630939a8ae59053a9c3"),
        "name" : "John Smith",
        "age" : 37,
        "hobbies" : [
                {
                        "name" : "Cooking",
                        "type" : "Indoor"
                }
        ]
}
{
        "_id" : ObjectId("595c06b7939a8ae59053a9c4"),
        "name" : "Miranda Thompson",
        "age" : 26,
        "hobbies" : []
}
{
        "_id" : ObjectId("595c078e939a8ae59053a9c5"),
        "name" : "Shelly Simon",
        "age" : 26,
        "hobbies" : [
                {
                        "name" : "Soccer",
                        "type" : "Outdoor"
                }
        ]
}
</code>```

Well... I can achieve this output using this command in mongo shell:

```<code>db.people.aggregate([
    {
        $project: {
            hobbies: {
                $filter: {
                    input: "$hobbies",
                    as: "hobby",
                    cond: { $eq: ["$$hobby.regular", true] }
                }
            },
            name: 1,
            age: 1
        }
    },
    {
        $project: {
            "hobbies.name": 1,
            "hobbies.type": 1,
            name: 1,
            age: 1
        }
    }
])
</code>```

As you can see, I had to use two $project operators in sequence and I think this smells bad.

Is there a way to achieve the same result with another query that does not use the same operator twice and in sequence?

答:
You can wrap the $filter expression inside $map to map the output values.

```<code>db.people.aggregate([
  {
    "$project": {
      "name": 1,
      "age": 1,
      "hobbies": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$hobbies",
              "as": "hobbyf",
              "cond": "$$hobbyf.regular"
            }
          },
          "as": "hobbym",
          "in": {
            "name": "$$hobbym.name",
            "type": "$$hobbym.type"
          }
        }
      }
    }
  }
])
</code>```

Body:
So I've got these documents in my people collection:

{
        "_id" : ObjectId("595c0630939a8ae59053a9c3"),
        "name" : "John Smith",
        "age" : 37,
        "location" : "San Francisco, CA",
        "hobbies" : [
                {
                        "name" : "Cooking",
                        "type" : "Indoor",
                        "regular" : true
                },
                {
                        "name" : "Baseball",
                        "type" : "Outdoor",
                        "regular" : false
                }
        ]
}
{
        "_id" : ObjectId("595c06b7939a8ae59053a9c4"),
        "name" : "Miranda Thompson",
        "age" : 26,
        "location" : "Modesto, CA",
        "hobbies" : [
                {
                        "name" : "Lego building",
                        "type" : "Indoor",
                        "regular" : false
                },
                {
                        "name" : "Yoga",
                        "type" : "Indoor",
                        "regular" : false
                }
        ]
}
{
        "_id" : ObjectId("595c078e939a8ae59053a9c5"),
        "name" : "Shelly Simon",
        "age" : 26,
        "location" : "Salt Lake City, UT",
        "hobbies" : [
                {
                        "name" : "Hunting",
                        "type" : "Outdoor",
                        "regular" : false
                },
                {
                        "name" : "Soccer",
                        "type" : "Outdoor",
                        "regular" : true
                }
        ]
}

I am trying to filter my "hobbies" array only to regular hobbies AND project the fields _id, name, age and hobby's name and type.

I want my output to be something like this:

{
        "_id" : ObjectId("595c0630939a8ae59053a9c3"),
        "name" : "John Smith",
        "age" : 37,
        "hobbies" : [
                {
                        "name" : "Cooking",
                        "type" : "Indoor"
                }
        ]
}
{
        "_id" : ObjectId("595c06b7939a8ae59053a9c4"),
        "name" : "Miranda Thompson",
        "age" : 26,
        "hobbies" : []
}
{
        "_id" : ObjectId("595c078e939a8ae59053a9c5"),
        "name" : "Shelly Simon",
        "age" : 26,
        "hobbies" : [
                {
                        "name" : "Soccer",
                        "type" : "Outdoor"
                }
        ]
}

Well... I can achieve this output using this command in mongo shell:

db.people.aggregate([
    {
        $project: {
            hobbies: {
                $filter: {
                    input: "$hobbies",
                    as: "hobby",
                    cond: { $eq: ["$$hobby.regular", true] }
                }
            },
            name: 1,
            age: 1
        }
    },
    {
        $project: {
            "hobbies.name": 1,
            "hobbies.type": 1,
            name: 1,
            age: 1
        }
    }
])

As you can see, I had to use two $project operators in sequence and I think this smells bad.

Is there a way to achieve the same result with another query that does not use the same operator twice and in sequence?

Body:
You can wrap the $filter expression inside $map to map the output values.

db.people.aggregate([
  {
    "$project": {
      "name": 1,
      "age": 1,
      "hobbies": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$hobbies",
              "as": "hobbyf",
              "cond": "$$hobbyf.regular"
            }
          },
          "as": "hobbym",
          "in": {
            "name": "$$hobbym.name",
            "type": "$$hobbym.type"
          }
        }
      }
    }
  }
])


问:
Error when redirecting between components in Angular 2
This is the home page of my app.  It gets redirected to if someone tries to access a page when they aren't logged in.

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

import { AuthenticationService } from '../_services/authentication.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  model: any = { username: "", password: "" };
  loading = false;
  error = '';
  isLoggedIn = false;
  public currentUser: any = null;
  constructor(private _auth: AuthenticationService, private router: Router) { }

  ngOnInit() {
    if(this._auth.isLoggedIn()) {
      this.isLoggedIn = true;
      this.router.navigate(['/census']);
    }
    else {

    }

    this.currentUser = this._auth.getCurrentUser().subscribe(result => {
      this.currentUser = result;
    });

    /*let timer = Observable.timer(29000, 29000);
    timer.subscribe(t => {

      //this.refresh();
    });*/
  }

  login() {
        this.loading = true;
        this._auth.login(this.model.username, this.model.password)
            .subscribe(result => {
                if (result === true) {
                    // login successful
                    this.isLoggedIn = true;
                    this.router.navigate(['/census']);
                } else {
                    // login failed
                    this.error = 'Username or password is incorrect';
                    this.loading = false;
                }
            });
    }

}
</code>```

I have the same problem on any page I try redirecting to.  The line that has

```<code>this.currentUser = this._auth.getCurrentUser().subscribe(result => {
  this.currentUser = result;
});
</code>```

The error is

```<code>error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: this._auth.getCurrentUser(...).subscribe is not a function
</code>```

Gives me an error.  It only gives an error if I redirected to the page using router.navigate(['/']);

I've tried navigateByUrl and get the same result.  This is on the top of every page, and I get the error any time I redirect to the page.

This is the getCurrentUser method from the AuthenticationService

```<code>    getCurrentUser(): Observable<any> {
        if (this.currentUser == null) {
            let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('token') });
            let options = new RequestOptions({ headers: headers });
            return this.http.get(  this._api.apiUrl + 'users/0', options)
                .map((response: Response) => {
                    this.currentUser = response.json();
                    return this.currentUser;
                });
        }
        else {
            return this.currentUser;
        }
  }
</code>```

答:
Rather than returning the user object when it already exists, transform it with the Observable of operator to return an Observable.

Change return this.currentUser; to return Observable.of(this.currentUser); in the Authentication Service.

Also this is a bit off:

```<code>this.currentUser = this._auth.getCurrentUser().subscribe(result => {
  this.currentUser = result;
});
</code>```

currentUser is being set to the Subscription of getCurrentUser() and then subsequently the result (subscribe() returns a Subscription).

Body:
This is the home page of my app.  It gets redirected to if someone tries to access a page when they aren't logged in.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

import { AuthenticationService } from '../_services/authentication.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  model: any = { username: "", password: "" };
  loading = false;
  error = '';
  isLoggedIn = false;
  public currentUser: any = null;
  constructor(private _auth: AuthenticationService, private router: Router) { }

  ngOnInit() {
    if(this._auth.isLoggedIn()) {
      this.isLoggedIn = true;
      this.router.navigate(['/census']);
    }
    else {

    }

    this.currentUser = this._auth.getCurrentUser().subscribe(result => {
      this.currentUser = result;
    });

    /*let timer = Observable.timer(29000, 29000);
    timer.subscribe(t => {

      //this.refresh();
    });*/
  }

  login() {
        this.loading = true;
        this._auth.login(this.model.username, this.model.password)
            .subscribe(result => {
                if (result === true) {
                    // login successful
                    this.isLoggedIn = true;
                    this.router.navigate(['/census']);
                } else {
                    // login failed
                    this.error = 'Username or password is incorrect';
                    this.loading = false;
                }
            });
    }

}

I have the same problem on any page I try redirecting to.  The line that has

this.currentUser = this._auth.getCurrentUser().subscribe(result => {
  this.currentUser = result;
});

The error is

error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: this._auth.getCurrentUser(...).subscribe is not a function

Gives me an error.  It only gives an error if I redirected to the page using router.navigate(['/']);

I've tried navigateByUrl and get the same result.  This is on the top of every page, and I get the error any time I redirect to the page.

This is the getCurrentUser method from the AuthenticationService

    getCurrentUser(): Observable<any> {
        if (this.currentUser == null) {
            let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('token') });
            let options = new RequestOptions({ headers: headers });
            return this.http.get(  this._api.apiUrl + 'users/0', options)
                .map((response: Response) => {
                    this.currentUser = response.json();
                    return this.currentUser;
                });
        }
        else {
            return this.currentUser;
        }
  }

Body:
Rather than returning the user object when it already exists, transform it with the Observable of operator to return an Observable.

Change return this.currentUser; to return Observable.of(this.currentUser); in the Authentication Service.

Also this is a bit off:

this.currentUser = this._auth.getCurrentUser().subscribe(result => {
  this.currentUser = result;
});

currentUser is being set to the Subscription of getCurrentUser() and then subsequently the result (subscribe() returns a Subscription).


问:
Sort Vector with custom sort
This works for cmp function having A.num>B.num but for lesser than it outputs zeros for all the values, idk why thanks. i'd like to know if im doing something wrong when im calling the function?

```<code>#include <bits/stdc++.h>
using namespace std;

typedef struct node
{
    int num;
}Node;
</code>```

this gives an error when A.num

```<code>bool cmpNode(Node A,Node B){
    return A.num<=B.num;
}

int main(){

    int n;
    cin>>n;

    //std::vector<char> v;
    vector<Node> vec(n);

    for (int i = 0; i < n; ++i)
    {
        Node temp;//    =new Node;
        cin>>temp.num;
        vec.push_back(temp);

    }

    sort(vec.begin(), vec.end(),cmpNode);

    for (int i = 0; i < n; ++i)
    {
        cout<<vec[i].num<<" ";
    }
    return 0;
}
</code>```

答:
Let's go through each mistake:

Issue 1:

You are calling push_back on a vector that has already been sized to n entries.  Thus in the input loop, you're just adding more items to the end of the vector, thus increasing its size.

The correction should be as follows:

```<code>vector<Node> vec;
</code>```

Issue 2:

The comparison function for std::sort requires a strict-weak-order.  In other words, your function must uniquely state, when given two items, which item comes first in the sorted order by returning true if the first item comes before the second item, false otherwise.

Your comparison function violates this,  since you return true if A == B, and true again if B == A.  So does A come before B or B come before A?

Of course, this will not work correctly and will totally throw off the sorting algorithm if you have duplicate items in the vector (this is what Visual C++ debug runtime does to check if you have a valid comparison function -- the comparison function is called twice and checks the return value for both calls).

The correction should be as follows:

```<code>bool cmpNode(const Node& A, const Node& B){
    return A.num < B.num;
}
</code>```

Also note the usage of passing by reference instead of by value.

Title: Sort Vector with custom sort

Body:
This works for cmp function having A.num>B.num but for lesser than it outputs zeros for all the values, idk why thanks. i'd like to know if im doing something wrong when im calling the function?

#include <bits/stdc++.h>
using namespace std;

typedef struct node
{
    int num;
}Node;

this gives an error when A.num

bool cmpNode(Node A,Node B){
    return A.num<=B.num;
}

int main(){

    int n;
    cin>>n;

    //std::vector<char> v;
    vector<Node> vec(n);

    for (int i = 0; i < n; ++i)
    {
        Node temp;//    =new Node;
        cin>>temp.num;
        vec.push_back(temp);

    }

    sort(vec.begin(), vec.end(),cmpNode);

    for (int i = 0; i < n; ++i)
    {
        cout<<vec[i].num<<" ";
    }
    return 0;
}

Body:
Let's go through each mistake:

Issue 1:

You are calling push_back on a vector that has already been sized to n entries.  Thus in the input loop, you're just adding more items to the end of the vector, thus increasing its size.

The correction should be as follows:

vector<Node> vec;

Issue 2:

The comparison function for std::sort requires a strict-weak-order.  In other words, your function must uniquely state, when given two items, which item comes first in the sorted order by returning true if the first item comes before the second item, false otherwise.

Your comparison function violates this,  since you return true if A == B, and true again if B == A.  So does A come before B or B come before A?

Of course, this will not work correctly and will totally throw off the sorting algorithm if you have duplicate items in the vector (this is what Visual C++ debug runtime does to check if you have a valid comparison function -- the comparison function is called twice and checks the return value for both calls).

The correction should be as follows:

bool cmpNode(const Node& A, const Node& B){
    return A.num < B.num;
}

Also note the usage of passing by reference instead of by value.


问:
Perform spread on nested data frame
I'd like to perform spread on a nested data frame but can't work it out. Here's a toy data frame for using spread on a normal data frame:

```<code>df <- data.frame( A = 1:4, B = 5:8)
df %>% spread(A,B)

  1 2 3 4
1 5 6 7 8
</code>```

Here's a toy example for a nested data frame and what I've tried (but doesn't work):

```<code>df <- data.frame( dummy=c(1,1,2,2), A = 1:4, B = 5:8)
df %>%
   nest(-dummy) %>%
   mutate(data = map(data, ~spread(.x$A,.x$B)))

Error in mutate_impl(.data, dots) :
   Evaluation error: Invalid column specification.
</code>```

Thanks for any help!

答:
```<code>df <- data.frame( dummy=c(1,1,2,2), A = 1:4, B = 5:8)
df %>%
  nest(-dummy) %>%
  mutate(data = map(data, ~spread(.x, key = A, value = B)))
</code>```

Title: Perform spread on nested data frame

Body:
I'd like to perform spread on a nested data frame but can't work it out. Here's a toy data frame for using spread on a normal data frame:

df <- data.frame( A = 1:4, B = 5:8)
df %>% spread(A,B)

  1 2 3 4
1 5 6 7 8

Here's a toy example for a nested data frame and what I've tried (but doesn't work):

df <- data.frame( dummy=c(1,1,2,2), A = 1:4, B = 5:8)
df %>%
   nest(-dummy) %>%
   mutate(data = map(data, ~spread(.x$A,.x$B)))

Error in mutate_impl(.data, dots) :
   Evaluation error: Invalid column specification.

Thanks for any help!


问:
Supporting ODataQueryOptions in existing Web API
I have a Web API project which has been used for several years without OData support, just with standard URL params.

I now wish to add OData support to this API, but as the API is not built on a queryable model the intention is to receive the ODataQueryOptions<T> object and pass this down to a repository.

Everything I can find to read about supporting OData either assumes that I have a queryable model or is overly simplistic and simply tells me how to make sense of the ODataQueryOptions object. Consequently I'm unable to get a simple method up and running.

Here's what I currently have.

```<code>[Route("test")]
[HttpGet]
[EnableQuery]
public IHttpActionResult Test(ODataQueryOptions<TestOptions> options)
{
    var settings = new ODataValidationSettings {
            AllowedFunctions = AllowedFunctions.None,
            AllowedLogicalOperators = AllowedLogicalOperators.Equal,
            AllowedArithmeticOperators = AllowedArithmeticOperators.None,
            AllowedQueryOptions = AllowedQueryOptions.Filter
        };
    try
    {
        options.Validate(settings);
    }
    catch (ODataException exception)
    {
        return BadRequest(exception.Message);
    }

    var binaryOperator = options.Filter?.FilterClause?.Expression as BinaryOperatorNode;
    if (binaryOperator != null)
    {
        var property = binaryOperator.Left as SingleValuePropertyAccessNode ?? binaryOperator.Right as SingleValuePropertyAccessNode;
        var constant = binaryOperator.Left as ConstantNode ?? binaryOperator.Right as ConstantNode;

        if (property?.Property != null && constant?.Value != null)
        {
            ;
        }
    }

    return Ok();
}
</code>```

The TestOptions class (in the ODataQueryOptions<TestOptions> param) is currently an empty class:

```<code>public class TestOptions
{
}
</code>```

I've also added

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // existing code

        config.AddODataQueryFilter();
    }
}
</code>```

However, upon calling this from a REST API client...

{

      "Message": "An error has occurred.",

      "ExceptionMessage": "No non-OData HTTP route registered.",

      "ExceptionType": "System.InvalidOperationException",

      "StackTrace": " ...  "

  }

What have I missed? I would have thought that I might have to register OData-enabled methods in the global.asax or similar, but the exception implies that the problem is with non-OData methods, but all the other methods still return as expected (i.e., without any OData involvement).

答:
Did you add this to your Startup?

```<code>public void Configuration(IAppBuilder appBuilder)
        {
            // Set up server configuration
            var config = new HttpConfiguration();
            config.Routes.MapODataRoute(routeName: "OData", routePrefix: "odata", model: GetEdmModel());
            appBuilder.UseWebApi(config);
        }

        private IEdmModel GetEdmModel()
        {
            var modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet<Customer>("customer");
            modelBuilder.EntitySet<Order>("order");
            modelBuilder.EntitySet<Customer>("response");
            return modelBuilder.GetEdmModel();
        }
</code>```

I am trying to do the same thing you are, but with a .Net Core Web Api. I downloaded the samples from https://github.com/OData/ODataSamples and he has a working project that does exactly what we're trying to do. Look at ODataQueryableSample.csproj. It doesn't use EntityFramework either, just creates a list in memory.

Also, I don't think you need both the [EnableQuery] attribute and ODataQueryOptions parameter - the sample gives an example for both and doesn't use them together.

I haven't gotten this working with my project either, but I have seen it working on my PC so I believe its just a configuration thing (for instance, my Startup uses IApplicationBuilder instead of IAppBuilder). You might also try to hit it from a browser to get a better exception message.

Body:
I have a Web API project which has been used for several years without OData support, just with standard URL params.

I now wish to add OData support to this API, but as the API is not built on a queryable model the intention is to receive the ODataQueryOptions<T> object and pass this down to a repository.

Everything I can find to read about supporting OData either assumes that I have a queryable model or is overly simplistic and simply tells me how to make sense of the ODataQueryOptions object. Consequently I'm unable to get a simple method up and running.

Here's what I currently have.

[Route("test")]
[HttpGet]
[EnableQuery]
public IHttpActionResult Test(ODataQueryOptions<TestOptions> options)
{
    var settings = new ODataValidationSettings {
            AllowedFunctions = AllowedFunctions.None,
            AllowedLogicalOperators = AllowedLogicalOperators.Equal,
            AllowedArithmeticOperators = AllowedArithmeticOperators.None,
            AllowedQueryOptions = AllowedQueryOptions.Filter
        };
    try
    {
        options.Validate(settings);
    }
    catch (ODataException exception)
    {
        return BadRequest(exception.Message);
    }

    var binaryOperator = options.Filter?.FilterClause?.Expression as BinaryOperatorNode;
    if (binaryOperator != null)
    {
        var property = binaryOperator.Left as SingleValuePropertyAccessNode ?? binaryOperator.Right as SingleValuePropertyAccessNode;
        var constant = binaryOperator.Left as ConstantNode ?? binaryOperator.Right as ConstantNode;

        if (property?.Property != null && constant?.Value != null)
        {
            ;
        }
    }

    return Ok();
}

The TestOptions class (in the ODataQueryOptions<TestOptions> param) is currently an empty class:

public class TestOptions
{
}

I've also added

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // existing code

        config.AddODataQueryFilter();
    }
}

However, upon calling this from a REST API client...

{

      "Message": "An error has occurred.",

      "ExceptionMessage": "No non-OData HTTP route registered.",

      "ExceptionType": "System.InvalidOperationException",

      "StackTrace": " ...  "

  }

What have I missed? I would have thought that I might have to register OData-enabled methods in the global.asax or similar, but the exception implies that the problem is with non-OData methods, but all the other methods still return as expected (i.e., without any OData involvement).

Body:
Did you add this to your Startup?

public void Configuration(IAppBuilder appBuilder)
        {
            // Set up server configuration
            var config = new HttpConfiguration();
            config.Routes.MapODataRoute(routeName: "OData", routePrefix: "odata", model: GetEdmModel());
            appBuilder.UseWebApi(config);
        }

        private IEdmModel GetEdmModel()
        {
            var modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet<Customer>("customer");
            modelBuilder.EntitySet<Order>("order");
            modelBuilder.EntitySet<Customer>("response");
            return modelBuilder.GetEdmModel();
        }

I am trying to do the same thing you are, but with a .Net Core Web Api. I downloaded the samples from https://github.com/OData/ODataSamples and he has a working project that does exactly what we're trying to do. Look at ODataQueryableSample.csproj. It doesn't use EntityFramework either, just creates a list in memory.

Also, I don't think you need both the [EnableQuery] attribute and ODataQueryOptions parameter - the sample gives an example for both and doesn't use them together.

I haven't gotten this working with my project either, but I have seen it working on my PC so I believe its just a configuration thing (for instance, my Startup uses IApplicationBuilder instead of IAppBuilder). You might also try to hit it from a browser to get a better exception message.


问:
Cloudfront Distribution: Deployed but not enabled
Is it possible to test a Cloudfront distribution that's been deployed but not enabled?

Would be nice to test things before flicking the switch!

答:
I would advise against enabling/disabling a CloudFront distribution. When a CloudFront distribution is created, it is fully functional. Thus, you can fully test it once it is created.

There is no cost in having an 'enabled' CloudFront distribution -- charges only relate to data throughput.

If you are referring to the ability to 'test' a change to your CloudFront distribution, then you could create a second distribution to test the configuration before updating the 'live' distribution, or even a test path within the distribution.