问:
Pack two adjacent views in a spread-chain ConstraintLayout
I have a set of half a dozen widgets chained together in a spread chain in a ConstraintLayout.  There are no other layouts in this view, only the ConstraintLayout and the widgets.

Two of the widgets in the center should be closer together, because one is the title for the other:

```<code>widget-title
widget-EditText
</code>```

I want to use a spread chain (Center Vertically) on all of the widgets in my view, but I want these two in particular to be packed vertically together, while honoring the bottom margin in the top one and the top margin in the bottom one.

I can't figure out how to do it.  I tried putting them together as children of a vertical LinearLayout, but it refuses to participate properly in the spread chain -- it goes to the top and many of the other widgets disappear.

I've tried adding additional constraints to the two views, but the spread chain seems to override all the additional constraints and they have no effect.  The only exception is aligning their baselines, which DOES work but smushes them together, which I don't want.

I don't see a way to create multiple spread chains within the same ConstraintLayout, in such a way that they all spread evenly.

How do you group two (or more) widgets within a chain so that their spread rules are different from the rest of the chain?  Or failing that, how do you construct multiple chains that all spread the same?

答:
Something must have gone wrong when you mapped the two center widgets in a LinearLayout. The following layout does just that and seems to work the way I think you want it to. I didn't add a lot of Views in the chain, but it is enough to get the idea. Check it out.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView1"
        app:layout_constraintBottom_toTopOf="@id/layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="spread" />

    <LinearLayout
        android:id="@+id/layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@id/textView4"
        app:layout_constraintTop_toBottomOf="@id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="TextView2" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="TextView3" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/layout" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I have a set of half a dozen widgets chained together in a spread chain in a ConstraintLayout.  There are no other layouts in this view, only the ConstraintLayout and the widgets.

Two of the widgets in the center should be closer together, because one is the title for the other:

widget-title
widget-EditText

I want to use a spread chain (Center Vertically) on all of the widgets in my view, but I want these two in particular to be packed vertically together, while honoring the bottom margin in the top one and the top margin in the bottom one.

I can't figure out how to do it.  I tried putting them together as children of a vertical LinearLayout, but it refuses to participate properly in the spread chain -- it goes to the top and many of the other widgets disappear.

I've tried adding additional constraints to the two views, but the spread chain seems to override all the additional constraints and they have no effect.  The only exception is aligning their baselines, which DOES work but smushes them together, which I don't want.

I don't see a way to create multiple spread chains within the same ConstraintLayout, in such a way that they all spread evenly.

How do you group two (or more) widgets within a chain so that their spread rules are different from the rest of the chain?  Or failing that, how do you construct multiple chains that all spread the same?

Body:
Something must have gone wrong when you mapped the two center widgets in a LinearLayout. The following layout does just that and seems to work the way I think you want it to. I didn't add a lot of Views in the chain, but it is enough to get the idea. Check it out.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView1"
        app:layout_constraintBottom_toTopOf="@id/layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="spread" />

    <LinearLayout
        android:id="@+id/layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@id/textView4"
        app:layout_constraintTop_toBottomOf="@id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="TextView2" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="TextView3" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/layout" />

</android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
How to add circle on click event in JavaScript?
Could you tell me how to add circle on click event in JavaScript? Actually, I want to achieve that if user click anywhere in div element, it add circle at that position. Currently, it added anywhere not added in correct position. It should be added where user clicks.

This is my code.

```<code>$(function(){
  $('#fx').click(function(e){
    var circle=$('<div class="circle"></div>');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});
</code>```

答:
You have to change the following line of code:</p>

```<code>circle.css('top', e.pageY);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Could you tell me how to add circle on click event in JavaScript? Actually, I want to achieve that if user click anywhere in div element, it add circle at that position. Currently, it added anywhere not added in correct position. It should be added where user clicks.

This is my code.

$(function(){
  $('#fx').click(function(e){
    var circle=$('

');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});

Body:
You have to change the following line of code:

circle.css('top', e.pageY);


问:
Testing Against Stored R Objects
Is there a simple workflow to write tests that store objects as .rds or .rda so that future runs of a test can compare the result of code execution vs. the stored object?  This would make it easy to check that functions that return somewhat complex values are still behaving as they should.

For example, something like:

```<code>test_obj(res <- lm(y ~ x, data.frame(x=1:3, y=5:7)))
</code>```

which, if *extdata/test_obj.res.rds* doesn't exist, would create it in *inst/extdata/test_obj.res.rds*, with res from above, but if it does exist, would identical/all.equal etc. the newly generated object with the one recovered from the rds.

I would find such tests super useful, and I am a bit surprised that RUnit/svUnit / testthat don't implement something of the sort (I'm hoping they do, and I just haven't found it).

testthat::make_expectation is close, but I'd prefer to have an automated store/retrieve rds rather than copy paste the text representation to a file, which I think is how you're supposed to use testthat::make_expectation (I guess I could pipe stdout() to a .R file, but even then there is a bit of automation that could facilitate the process).

答: As of 2017, testthat has the feature expect_equal_to_reference, which does exactly what the question asks. I guess Hadley W. figured out a way.

Title: Testing Against Stored R Objects

Body:
Is there a simple workflow to write tests that store objects as .rds or .rda so that future runs of a test can compare the result of code execution vs. the stored object?  This would make it easy to check that functions that return somewhat complex values are still behaving as they should.

For example, something like:

test_obj(res <- lm(y ~ x, data.frame(x=1:3, y=5:7)))

which, if *extdata/test_obj.res.rds* doesn't exist, would create it in *inst/extdata/test_obj.res.rds*, with res from above, but if it does exist, would identical/all.equal etc. the newly generated object with the one recovered from the rds.

I would find such tests super useful, and I am a bit surprised that RUnit/svUnit / testthat don't implement something of the sort (I'm hoping they do, and I just haven't found it).

testthat::make_expectation is close, but I'd prefer to have an automated store/retrieve rds rather than copy paste the text representation to a file, which I think is how you're supposed to use testthat::make_expectation (I guess I could pipe stdout() to a .R file, but even then there is a bit of automation that could facilitate the process).


问:
Permission denied when using matplotlib animation
Trying to make an animation using example code found here. I have installed both ffmpeg and yasm, but when I run the code, including the line

```<code>ani.save('test.mp4', writer = FFwriter, dpi = 40)
</code>```

I get the following error.

```<code>PermissionError: [Errno 13] Permission denied
</code>```

(where FFwriter = animation.FFMpegWriter(fps = 30) is defined in the beginning of my Jupyter doc). I have tried so much, but can't get anything to work. Even tried changing the permissions of ffmpeg but still can't get the error to go away.

EDIT
Here is my imports and such to include more detail

```<code>import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams['animation.ffmpeg_path'] = '/usr/local/Cellar/ffmpeg/'
FFwriter = animation.FFMpegWriter(fps = 30)
</code>```

答: You do not have permission to save in your working directory. Either write a full filepath to a place where you do have permission or run your script with sudo so that you do have permission.</p>

Body:
Trying to make an animation using example code found here. I have installed both ffmpeg and yasm, but when I run the code, including the line

ani.save('test.mp4', writer = FFwriter, dpi = 40)

I get the following error.

PermissionError: [Errno 13] Permission denied

(where FFwriter = animation.FFMpegWriter(fps = 30) is defined in the beginning of my Jupyter doc). I have tried so much, but can't get anything to work. Even tried changing the permissions of ffmpeg but still can't get the error to go away.

EDIT
Here is my imports and such to include more detail

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams['animation.ffmpeg_path'] = '/usr/local/Cellar/ffmpeg/'
FFwriter = animation.FFMpegWriter(fps = 30)


问:
Implementation of Kraken API in Java
So I currently working on an implementation of the Kraken API for Java. I am using this sample code I found on http://pastebin.com/nHJDAbH8.

The general usage as described by Kraken (https://www.kraken.com/help/api) is:

API-Key = API key

API-Sign = Message signature using HMAC-SHA512 of

  ( URI path + SHA256( nonce + POST data ) ) and base64 decoded secret API
  key

and

nonce = always increasing unsigned 64 bit integer

  otp = two-factor password ( if two-factor enabled, otherwise not required )

however I am facing the following response:

```<code>{"error":["EAPI:Invalid key"]}
</code>```

I already tried a couple of ways ( getting a new API, trying to change the sha256 methods, because I thought something is wrong with the way it is hashed )

So this is the code:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class KrakenClient {

        protected static String key = "myAPIKey";     // API key
        protected static String secret = "MySecret====";  // API secret
        protected static String url = "api.kraken.com";     // API base URL
        protected static String version = "0"; // API version

        public static void main(String[] args) throws Exception {
                queryPrivateMethod("Balance");
        }

        public static void queryPrivateMethod(String method) throws NoSuchAlgorithmException, IOException{

                long nonce = System.currentTimeMillis();

                String path = "/" + version + "/private/" + method; // The path like "/0/private/Balance"

                String urlComp = "https://"+url+path; // The complete url like "https://api.kraken.com/0/private/Balance"

                String postdata = "nonce="+nonce;

                String sign = createSignature(nonce, path, postdata);

                postConnection(urlComp, sign, postdata);
        }

        /**
         * @param nonce
         * @param path
         * @param postdata
         * @return
         * @throws NoSuchAlgorithmException
         * @throws IOException
         */
        private static String createSignature(long nonce, String path,
                        String postdata) throws NoSuchAlgorithmException, IOException {

                return hmac(path+sha256(nonce + postdata),  new String(Base64.decodeBase64(secret)));
        }

        public static String sha256Hex(String text) throws NoSuchAlgorithmException, IOException{
                return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        }

        public static byte[] sha256(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException{
                MessageDigest md = MessageDigest.getInstance("SHA-256");

                md.update(text.getBytes());
                byte[] digest = md.digest();

                return digest;
        }

        public static void postConnection(String url1, String sign, String postData) throws IOException{

                URL url = new URL( url1 );
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.addRequestProperty("API-Key", key);
                connection.addRequestProperty("API-Sign", Base64.encodeBase64String(sign.getBytes()));
                //              connection.addRequestProperty("API-Sign", sign);
                connection.addRequestProperty("User-Agent", "Mozilla/4.0");
                connection.setRequestMethod( "POST" );
                connection.setDoInput( true );
                connection.setDoOutput( true );
                connection.setUseCaches( false );
                //              connection.setRequestProperty( "Content-Type",
                //                              "application/x-www-form-urlencoded" );
                connection.setRequestProperty( "Content-Length", String.valueOf(postData.length()) );

                OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() );
                writer.write( postData );
                writer.flush();

                BufferedReader reader = new BufferedReader(
                                new InputStreamReader(connection.getInputStream()) );

                for ( String line; (line = reader.readLine()) != null; )
                {
                        System.out.println( line );
                }

                writer.close();
                reader.close();
        }

        public static String hmac(String text, String secret){

                Mac mac =null;
                SecretKeySpec key = null;

                // Create a new secret key
                try {
                        key = new SecretKeySpec( secret.getBytes( "UTF-8"), "HmacSHA512" );
                } catch( UnsupportedEncodingException uee) {
                        System.err.println( "Unsupported encoding exception: " + uee.toString());
                        return null;
                }
                // Create a new mac
                try {
                        mac = Mac.getInstance( "HmacSHA512" );
                } catch( NoSuchAlgorithmException nsae) {
                        System.err.println( "No such algorithm exception: " + nsae.toString());
                        return null;
                }

                // Init mac with key.
                try {
                        mac.init( key);
                } catch( InvalidKeyException ike) {
                        System.err.println( "Invalid key exception: " + ike.toString());
                        return null;
                }

                // Encode the text with the secret
                try {

                        return new String( mac.doFinal(text.getBytes( "UTF-8")));
                } catch( UnsupportedEncodingException uee) {
                        System.err.println( "Unsupported encoding exception: " + uee.toString());
                        return null;
                }
        }
}
</code>```

答:
Here is a working example:</p>

```<code>static String key = "---myKey---";
static String secret = "---mySecret---";
String nonce, signature, data, path;
static String domain = "https://api.kraken.com";

void account_balance() {
    nonce = String.valueOf(System.currentTimeMillis());
    data = "nonce=" + nonce;
    path = "/0/private/Balance";
    calculateSignature();
    String answer = post(domain + path, data);
    // on empty accounts, returns {"error":[],"result":{}}
    // this is a known Kraken bug
    ...
}

String post(String address, String output) {
    String answer = "";
    HttpsURLConnection c = null;
    try {
        URL u = new URL(address);
        c = (HttpsURLConnection)u.openConnection();
        c.setRequestMethod("POST");
        c.setRequestProperty("API-Key", key);
        c.setRequestProperty("API-Sign", signature);
        c.setDoOutput(true);
        DataOutputStream os = new DataOutputStream(c.getOutputStream());
        os.writeBytes(output);
        os.flush();
        os.close();
        BufferedReader br = null;
        if(c.getResponseCode() >= 400) {
            System.exit(1);
        }
        br = new BufferedReader(new InputStreamReader((c.getInputStream())));
        String line;
        while ((line = br.readLine()) != null)
            answer += line;
    } catch (Exception x) {
        System.exit(1);
    } finally {
        c.disconnect();
    }
    return answer;
}

void calculateSignature() {
    signature = "";
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update((nonce + data).getBytes());
        Mac mac = Mac.getInstance("HmacSHA512");
        mac.init(new SecretKeySpec(Base64.decodeBase64(secret.getBytes()), "HmacSHA512"));
        mac.update(path.getBytes());
        signature = new String(Base64.encodeBase64(mac.doFinal(md.digest())));
    } catch(Exception e) {}
    return;
}
</code>```

Title: Implementation of Kraken API in Java

Body:
So I currently working on an implementation of the Kraken API for Java. I am using this sample code I found on http://pastebin.com/nHJDAbH8.

The general usage as described by Kraken (https://www.kraken.com/help/api) is:

API-Key = API key

API-Sign = Message signature using HMAC-SHA512 of

  ( URI path + SHA256( nonce + POST data ) ) and base64 decoded secret API
  key

and

nonce = always increasing unsigned 64 bit integer

  otp = two-factor password ( if two-factor enabled, otherwise not required )

however I am facing the following response:

{"error":["EAPI:Invalid key"]}

I already tried a couple of ways ( getting a new API, trying to change the sha256 methods, because I thought something is wrong with the way it is hashed )

So this is the code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class KrakenClient {

        protected static String key = "myAPIKey";     // API key
        protected static String secret = "MySecret====";  // API secret
        protected static String url = "api.kraken.com";     // API base URL
        protected static String version = "0"; // API version

        public static void main(String[] args) throws Exception {
                queryPrivateMethod("Balance");
        }

        public static void queryPrivateMethod(String method) throws NoSuchAlgorithmException, IOException{

                long nonce = System.currentTimeMillis();

                String path = "/" + version + "/private/" + method; // The path like "/0/private/Balance"

                String urlComp = "https://"+url+path; // The complete url like "https://api.kraken.com/0/private/Balance"

                String postdata = "nonce="+nonce;

                String sign = createSignature(nonce, path, postdata);

                postConnection(urlComp, sign, postdata);
        }

        /**
         * @param nonce
         * @param path
         * @param postdata
         * @return
         * @throws NoSuchAlgorithmException
         * @throws IOException
         */
        private static String createSignature(long nonce, String path,
                        String postdata) throws NoSuchAlgorithmException, IOException {

                return hmac(path+sha256(nonce + postdata),  new String(Base64.decodeBase64(secret)));
        }

        public static String sha256Hex(String text) throws NoSuchAlgorithmException, IOException{
                return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        }

        public static byte[] sha256(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException{
                MessageDigest md = MessageDigest.getInstance("SHA-256");

                md.update(text.getBytes());
                byte[] digest = md.digest();

                return digest;
        }

        public static void postConnection(String url1, String sign, String postData) throws IOException{

                URL url = new URL( url1 );
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.addRequestProperty("API-Key", key);
                connection.addRequestProperty("API-Sign", Base64.encodeBase64String(sign.getBytes()));
                //              connection.addRequestProperty("API-Sign", sign);
                connection.addRequestProperty("User-Agent", "Mozilla/4.0");
                connection.setRequestMethod( "POST" );
                connection.setDoInput( true );
                connection.setDoOutput( true );
                connection.setUseCaches( false );
                //              connection.setRequestProperty( "Content-Type",
                //                              "application/x-www-form-urlencoded" );
                connection.setRequestProperty( "Content-Length", String.valueOf(postData.length()) );

                OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() );
                writer.write( postData );
                writer.flush();

                BufferedReader reader = new BufferedReader(
                                new InputStreamReader(connection.getInputStream()) );

                for ( String line; (line = reader.readLine()) != null; )
                {
                        System.out.println( line );
                }

                writer.close();
                reader.close();
        }

        public static String hmac(String text, String secret){

                Mac mac =null;
                SecretKeySpec key = null;

                // Create a new secret key
                try {
                        key = new SecretKeySpec( secret.getBytes( "UTF-8"), "HmacSHA512" );
                } catch( UnsupportedEncodingException uee) {
                        System.err.println( "Unsupported encoding exception: " + uee.toString());
                        return null;
                }
                // Create a new mac
                try {
                        mac = Mac.getInstance( "HmacSHA512" );
                } catch( NoSuchAlgorithmException nsae) {
                        System.err.println( "No such algorithm exception: " + nsae.toString());
                        return null;
                }

                // Init mac with key.
                try {
                        mac.init( key);
                } catch( InvalidKeyException ike) {
                        System.err.println( "Invalid key exception: " + ike.toString());
                        return null;
                }

                // Encode the text with the secret
                try {

                        return new String( mac.doFinal(text.getBytes( "UTF-8")));
                } catch( UnsupportedEncodingException uee) {
                        System.err.println( "Unsupported encoding exception: " + uee.toString());
                        return null;
                }
        }
}

Body:
Here is a working example:

static String key = "---myKey---";
static String secret = "---mySecret---";
String nonce, signature, data, path;
static String domain = "https://api.kraken.com";

void account_balance() {
    nonce = String.valueOf(System.currentTimeMillis());
    data = "nonce=" + nonce;
    path = "/0/private/Balance";
    calculateSignature();
    String answer = post(domain + path, data);
    // on empty accounts, returns {"error":[],"result":{}}
    // this is a known Kraken bug
    ...
}

String post(String address, String output) {
    String answer = "";
    HttpsURLConnection c = null;
    try {
        URL u = new URL(address);
        c = (HttpsURLConnection)u.openConnection();
        c.setRequestMethod("POST");
        c.setRequestProperty("API-Key", key);
        c.setRequestProperty("API-Sign", signature);
        c.setDoOutput(true);
        DataOutputStream os = new DataOutputStream(c.getOutputStream());
        os.writeBytes(output);
        os.flush();
        os.close();
        BufferedReader br = null;
        if(c.getResponseCode() >= 400) {
            System.exit(1);
        }
        br = new BufferedReader(new InputStreamReader((c.getInputStream())));
        String line;
        while ((line = br.readLine()) != null)
            answer += line;
    } catch (Exception x) {
        System.exit(1);
    } finally {
        c.disconnect();
    }
    return answer;
}

void calculateSignature() {
    signature = "";
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update((nonce + data).getBytes());
        Mac mac = Mac.getInstance("HmacSHA512");
        mac.init(new SecretKeySpec(Base64.decodeBase64(secret.getBytes()), "HmacSHA512"));
        mac.update(path.getBytes());
        signature = new String(Base64.encodeBase64(mac.doFinal(md.digest())));
    } catch(Exception e) {}
    return;
}


问:
javascript function call timing
I am trying to implement a for loop that iterates through a list and subsequently calls two functions, only if the first function results are found.

The issue is that the second function (search.similar) might be taking longer to fetch results.

With the code below, when I run, all of the appropriate output from (search.locate) is correct, but only the last element's results from myList are stored from the (search.similar) function.

ie.     all_results = [[cat_res1,mouse_res2],[dog_res1,mouse_res2],[mouse_res1,mouse_res2]]

How do I fix this to append the right results in the right order?

ie.     all_results = [[cat_res1,cat_res2],[dog_res1,dog_res2],[mouse_res1,mouse_res2]]

```<code>var search = require('./search');
var myList = ['cat','dog','mouse'];
var all_results = [];
for (i=0; i<myList.length; i++){
  /* locate function*/
  search.locate(myList[i], function (err, searchResult){
    if (err){
      console.log("Error");
      return;
    }

    if (!searchResult){
      console.log("Cannot find it");
      return;
    }

    /*similarity function*/
    /* seems to take longer*/
    search.similar(myList[i], function (err, similarResult){
      if (err){
        return;
      }

      if (!similarResult){
        return;
      }

      var res1 = searchResult.data;
      var res2 = similarResult.data;
      /* append results to array*/
      all_results.push([res1,res2]);
    }
  });
}
</code>```

答:
Javascript can be thought of as asynchronous, in that the execution of particular functions do not necessarily happen synchronously, however "describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms"

In order to accomplish your goal, though you may still get some ordering issues with the top array, you will need to wrap your .similar() call in another function that takes both arguments.  Your reference to the "item" on the top search is changing:

```<code>function searchNestedSimilar(item, topRes) {
    search.similar(item, function (err, similarResult) {

        if (err){
            return;
        }
        if (!topRes){
            return;
        }

        var res1 = topRes.data
        var res2 = similarResult.data

        // append results to array
        all_results.push([res1,res2])

    }
}

function searchLocate(item) {
   search.locate(item, function (err, searchResult) {

    if (err){
        console.log("Error");
        return;
    }
    if (!searchResult){
        console.log("Cannot find it");
        return;
    }
    searchNestedSimilar(item, searchResults);
}
</code>```

I encapsulated both calls to keep it modular, but since "item" is in the closure, you really only need the searchLocate() function to wrap your capture your item reference during iteration.

Title: javascript function call timing

Body:
I am trying to implement a for loop that iterates through a list and subsequently calls two functions, only if the first function results are found.

The issue is that the second function (search.similar) might be taking longer to fetch results.

With the code below, when I run, all of the appropriate output from (search.locate) is correct, but only the last element's results from myList are stored from the (search.similar) function.

ie.     all_results = [[cat_res1,mouse_res2],[dog_res1,mouse_res2],[mouse_res1,mouse_res2]]

How do I fix this to append the right results in the right order?

ie.     all_results = [[cat_res1,cat_res2],[dog_res1,dog_res2],[mouse_res1,mouse_res2]]

var search = require('./search');
var myList = ['cat','dog','mouse'];
var all_results = [];
for (i=0; i<myList.length; i++){
  /* locate function*/
  search.locate(myList[i], function (err, searchResult){
    if (err){
      console.log("Error");
      return;
    }

    if (!searchResult){
      console.log("Cannot find it");
      return;
    }

    /*similarity function*/
    /* seems to take longer*/
    search.similar(myList[i], function (err, similarResult){
      if (err){
        return;
      }

      if (!similarResult){
        return;
      }

      var res1 = searchResult.data;
      var res2 = similarResult.data;
      /* append results to array*/
      all_results.push([res1,res2]);
    }
  });
}

Body:
Javascript can be thought of as asynchronous, in that the execution of particular functions do not necessarily happen synchronously, however "describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms"

In order to accomplish your goal, though you may still get some ordering issues with the top array, you will need to wrap your .similar() call in another function that takes both arguments.  Your reference to the "item" on the top search is changing:

function searchNestedSimilar(item, topRes) {
    search.similar(item, function (err, similarResult) {

        if (err){
            return;
        }
        if (!topRes){
            return;
        }

        var res1 = topRes.data
        var res2 = similarResult.data

        // append results to array
        all_results.push([res1,res2])

    }
}

function searchLocate(item) {
   search.locate(item, function (err, searchResult) {

    if (err){
        console.log("Error");
        return;
    }
    if (!searchResult){
        console.log("Cannot find it");
        return;
    }
    searchNestedSimilar(item, searchResults);
}

I encapsulated both calls to keep it modular, but since "item" is in the closure, you really only need the searchLocate() function to wrap your capture your item reference during iteration.


问:
Split NSString from first whitespace
I have a name textfield in my app, where both the firstname maybe a middle and a lastname is written. Now I want to split these components by the first whitespace, the space between the firstname and the middlename/lastname, so I can put it into my model.

For example:

Textfield Text: John D. Sowers

String 1: John

String 2: D. Sowers.

I have tried using [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject]; &  [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lastObject];
But these only work if have a name without a middlename. Since it gets the first and the last object, and the middlename is ignored.
So how would I manage to accomplish what I want?

答:
I found this to be most robust:

```<code>NSString *fullNameString = @"\n  Barnaby Marmaduke \n \n Aloysius  ";
NSMutableArray *nameArray = [[fullNameString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
[nameArray removeObject:@""];
NSString *firstName = [nameArray firstObject];
if(nameArray.count)
{
    [nameArray removeObjectAtIndex:0];
}
NSString *nameRemainder = [nameArray componentsJoinedByString:@" "];
</code>```

Bob's your uncle.

Title: Split NSString from first whitespace

Body:
I found this to be most robust:

NSString *fullNameString = @"\n  Barnaby Marmaduke \n \n Aloysius  ";
NSMutableArray *nameArray = [[fullNameString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
[nameArray removeObject:@""];
NSString *firstName = [nameArray firstObject];
if(nameArray.count)
{
    [nameArray removeObjectAtIndex:0];
}
NSString *nameRemainder = [nameArray componentsJoinedByString:@" "];

Bob's your uncle.


问:
One Swift SpriteNode to approach another
I have 2 sprite nodes. one is the player (red) and there is also another object (green). additionally there is an invisible area which I use for collision detection.

My intention is, that the green objects approaches the red player as soon as the player is within the blue rectangle.

Until now I set up the collision handling in a way that a SKAction is triggered when the player collides with the blue area. The SKAction moves the green object to the position to the player. This approach works as long as I do not work with texture changes, which are handled with a SKActionForever.

Here is my code I have:

```<code>                    let distance: CGFloat = fabs(platformNode1.position.x - player.position.x);
                    let moveToPlayer = SKAction.move(to: CGPoint(x: player.position.x, y: platformNode1.position.y), duration: Double(distance/10))
                    let passengerAnimation = SKAction.group([moveToPlayer, animatePassengerAction])
                    animatePassengerAction = SKAction.repeatForever(SKAction.animate(with: passengerAnimation, timePerFrame: 0.1))
                    let removePassenger = SKAction.removeFromParent()
                    let setPassengerToOnBoard = SKAction.run({ () -> Void in
                        self.passengerOnBoard = true
                    })
                    let onBoardActionSequence = SKAction.sequence([passengerAnimation, removePassenger, setPassengerToOnBoard])
                    self.passenger.run(onBoardActionSequence, withKey: "isOnboarding")
</code>```

My problem no is, that the SKAction sequence does never complete, since the sequence is looping "passengerAnimation" until forever. But I need this animation forever since this represents the animation of the walking passenger/object, which should be looped as long as the object approaches the player.

Does anyone have an idea how to solve this problem? I am really stuck.

答:
Since you know the travel time or the passenger's movement, you should be able to compute the number of cycles needed and adjust the animation to that (and then you won't need to repeat forever)

For example:

```<code>let distance: CGFloat = fabs(platformNode1.position.x - player.position.x);
let moveToPlayer = SKAction.move(to: CGPoint(x: player.position.x, y: platformNode1.position.y), duration: Double(distance/10))

// distance/10 seconds * 0.1 second perFrame = distance number of frames.
// build a (repeating) array of the original animation frames with exactly the right number of frames for the distance.
let animationOnDistance = (0..<distance).map{passengerAnimation[$0 % passengerAnimation.count]}

let animatePassengerAction = SKAction.animate(with: animationOnDistance, timePerFrame: 0.1)

let passengerAnimation = SKAction.group([moveToPlayer, animatePassengerAction])
</code>```

Body:
I have 2 sprite nodes. one is the player (red) and there is also another object (green). additionally there is an invisible area which I use for collision detection.

My intention is, that the green objects approaches the red player as soon as the player is within the blue rectangle.

Until now I set up the collision handling in a way that a SKAction is triggered when the player collides with the blue area. The SKAction moves the green object to the position to the player. This approach works as long as I do not work with texture changes, which are handled with a SKActionForever.

Here is my code I have:

                    let distance: CGFloat = fabs(platformNode1.position.x - player.position.x);
                    let moveToPlayer = SKAction.move(to: CGPoint(x: player.position.x, y: platformNode1.position.y), duration: Double(distance/10))
                    let passengerAnimation = SKAction.group([moveToPlayer, animatePassengerAction])
                    animatePassengerAction = SKAction.repeatForever(SKAction.animate(with: passengerAnimation, timePerFrame: 0.1))
                    let removePassenger = SKAction.removeFromParent()
                    let setPassengerToOnBoard = SKAction.run({ () -> Void in
                        self.passengerOnBoard = true
                    })
                    let onBoardActionSequence = SKAction.sequence([passengerAnimation, removePassenger, setPassengerToOnBoard])
                    self.passenger.run(onBoardActionSequence, withKey: "isOnboarding")

My problem no is, that the SKAction sequence does never complete, since the sequence is looping "passengerAnimation" until forever. But I need this animation forever since this represents the animation of the walking passenger/object, which should be looped as long as the object approaches the player.

Does anyone have an idea how to solve this problem? I am really stuck.

Body:
Since you know the travel time or the passenger's movement, you should be able to compute the number of cycles needed and adjust the animation to that (and then you won't need to repeat forever)

For example:

let distance: CGFloat = fabs(platformNode1.position.x - player.position.x);
let moveToPlayer = SKAction.move(to: CGPoint(x: player.position.x, y: platformNode1.position.y), duration: Double(distance/10))

// distance/10 seconds * 0.1 second perFrame = distance number of frames.
// build a (repeating) array of the original animation frames with exactly the right number of frames for the distance.
let animationOnDistance = (0..<distance).map{passengerAnimation[$0 % passengerAnimation.count]}

let animatePassengerAction = SKAction.animate(with: animationOnDistance, timePerFrame: 0.1)

let passengerAnimation = SKAction.group([moveToPlayer, animatePassengerAction])


问:
Dynamically downsize an image
So I've got a large image 3000x2000 roughly and I want to span it across my website so it fills 100% width but stays the same proportions, but if I were to shrink the screen the image would resize automatically keeping the same proportions and no overflow scrolling.

```<code><div class="row anfield">
    <img src="../Images/Anfield.jpg" />
</div>

.row{
width:100%;
display:flex;
flex-wrap:wrap
}
</code>```

I have tried max-width / width 100% in the css anfield but neither worked.

```<code><img style="max-width:100%" src="../Images/Anfield.jpg" />
</code>```

This changes the width to 100% but doesn't resize the height accordingly.

Edit: I have tried adding this. Doesn't resize height at all

CSS

```<code>.fixed-ratio-resize { /* basic responsive img */
max-width: 20%;
height: auto;
width: auto\9; /* IE8 */
}
</code>```

HTML

```<code><img id="anfield" src="../Images/Anfield.jpg" class="fixed-ratio-resize" />
</code>```

答:
Check out this site.  It allows you to upload your image and generates not only smaller images but the code for you!
http://www.responsivebreakpoints.com/</p>

Title: Dynamically downsize an image

Body:
So I've got a large image 3000x2000 roughly and I want to span it across my website so it fills 100% width but stays the same proportions, but if I were to shrink the screen the image would resize automatically keeping the same proportions and no overflow scrolling.

.row{
width:100%;
display:flex;
flex-wrap:wrap
}

I have tried max-width / width 100% in the css anfield but neither worked.

This changes the width to 100% but doesn't resize the height accordingly.

Edit: I have tried adding this. Doesn't resize height at all

CSS

.fixed-ratio-resize { /* basic responsive img */
max-width: 20%;
height: auto;
width: auto\9; /* IE8 */
}

HTML


问:
Unable to execute simple cd command in Python (in Jupyter shell)
When I attempt to use the following command in Jupyter shell for Python "cd /Users/Donald/Documents/BUS6303/week 7/ocelma-python-recsys-48df9c4/ocelma-python-recsys-48df9c4/recsys/algorithm" I get a Invalid Syntax" error. What am I doing wrong?</p>

答: I encountered this issue when I added a comment in the same cell.  Create a new cell, without a comment, and try it again.</p>


答: You don't need flexbox for this, just apply width: 100% to the image (nothing else), height is auto by default, which keeps it in proportion.

Title: Dynamically downsize an image


问:
Scope of an object created in a function
I have created an object of a class inside a function. The created object is passed as a parameter to another class. I expect that when I exit the function in which the object is created, the object must be destroyed.

Also any references to this object must be invalid, but I find that the object referenced after exiting the function is still valid. Trying to understand the scope of the object. The code snipped is given below.

```<code>class TextWidget
{
    public:
        TextWidget()
        {
            cout <<  "Constructor TextWidget" << endl;
        }

        TextWidget(int id)
        {
            _ID = id;
            cout <<  "Constructor TextWidget" << endl;
        }

        ~TextWidget()
        {
            cout <<  "Destructor TextWidget" << endl;
        }

        void printWidgetInstance()
        {
            cout << this << endl;
        }
        int _ID;
};

class AnotherWidget
{
    public:
        AnotherWidget()
        {
            cout << "Constructor AnotherWidget" << endl;
        }

        ~AnotherWidget()
        {
            cout << "Destructor AnotherWidget" << endl;
        }

        TextWidget* getTextWidget()
        {
            return _textWidget;
        }

        void setTextWidget(TextWidget* t)
        {
            _textWidget = t;
        }

        int getTextID() { return _textWidget->_ID; }

    private:
        TextWidget* _textWidget;
};

ButtonWidget b;
AnotherWidget a;

void fun()
{
    TextWidget t(7);
    b.setTextWidget(&t);
    a.setTextWidget(&t);
    a.getTextWidget()->printWidgetInstance();
    b.getTextWidget()->printWidgetInstance();
}

int main()
{
    fun();
    cout << "TextWidget in AnotherWidget is ";
    a.getTextWidget()->printWidgetInstance();
    cout << "Text ID in a is " << a.getTextID() << endl;
    getchar();
    return 0;
}
</code>```

OUTPUT

```<code>Constructor AnotherWidget
Constructor TextWidget
Before deleting TextWidget in class ButtonWidget 0x73fdf0
Before deleting TextWidget in class AnotherWidget 0x73fdf0
0x73fdf0
0x73fdf0
Destructor TextWidget
TextWidget in AnotherWidget is 0x73fdf0
Text ID in a is 7
</code>```

答:
You need to understand what classes, objects, pointers and references are. Classes are code in memory, this code deals with the member variables. A class does not occupy any data memory. When you create a object you instantiate the class. This step will reserve some data memory for the local data of one object instance of the class. To access this instance you get a reference to the object (this). An object variable holds a pointer to the data memory of an instance of a class.

When an object gets destroyed the occupied memory block gets listed as free but not cleared. So if you still have a reference to that memory block you may access it. And as long as the system doesnt use this memory block for other purposes you still will find your bits and bytes there.

You may declare some variables:

```<code>long      long_array[10];
myclass   myobject;
</code>```

These variables are stored sequential in one memory block. When you now access the memory behind the long_array through that array:

long_array[10] = 12345;   // valid range is  from   long_array[0] to long_array[9]

Than you will overwrite the data of the object myobject.

Body:
I have created an object of a class inside a function. The created object is passed as a parameter to another class. I expect that when I exit the function in which the object is created, the object must be destroyed.

Also any references to this object must be invalid, but I find that the object referenced after exiting the function is still valid. Trying to understand the scope of the object. The code snipped is given below.

class TextWidget
{
    public:
        TextWidget()
        {
            cout <<  "Constructor TextWidget" << endl;
        }

        TextWidget(int id)
        {
            _ID = id;
            cout <<  "Constructor TextWidget" << endl;
        }

        ~TextWidget()
        {
            cout <<  "Destructor TextWidget" << endl;
        }

        void printWidgetInstance()
        {
            cout << this << endl;
        }
        int _ID;
};

class AnotherWidget
{
    public:
        AnotherWidget()
        {
            cout << "Constructor AnotherWidget" << endl;
        }

        ~AnotherWidget()
        {
            cout << "Destructor AnotherWidget" << endl;
        }

        TextWidget* getTextWidget()
        {
            return _textWidget;
        }

        void setTextWidget(TextWidget* t)
        {
            _textWidget = t;
        }

        int getTextID() { return _textWidget->_ID; }

    private:
        TextWidget* _textWidget;
};

ButtonWidget b;
AnotherWidget a;

void fun()
{
    TextWidget t(7);
    b.setTextWidget(&t);
    a.setTextWidget(&t);
    a.getTextWidget()->printWidgetInstance();
    b.getTextWidget()->printWidgetInstance();
}

int main()
{
    fun();
    cout << "TextWidget in AnotherWidget is ";
    a.getTextWidget()->printWidgetInstance();
    cout << "Text ID in a is " << a.getTextID() << endl;
    getchar();
    return 0;
}

OUTPUT

Constructor AnotherWidget
Constructor TextWidget
Before deleting TextWidget in class ButtonWidget 0x73fdf0
Before deleting TextWidget in class AnotherWidget 0x73fdf0
0x73fdf0
0x73fdf0
Destructor TextWidget
TextWidget in AnotherWidget is 0x73fdf0
Text ID in a is 7

Body:
You need to understand what classes, objects, pointers and references are. Classes are code in memory, this code deals with the member variables. A class does not occupy any data memory. When you create a object you instantiate the class. This step will reserve some data memory for the local data of one object instance of the class. To access this instance you get a reference to the object (this). An object variable holds a pointer to the data memory of an instance of a class.

When an object gets destroyed the occupied memory block gets listed as free but not cleared. So if you still have a reference to that memory block you may access it. And as long as the system doesnt use this memory block for other purposes you still will find your bits and bytes there.

You may declare some variables:

long      long_array[10];
myclass   myobject;

These variables are stored sequential in one memory block. When you now access the memory behind the long_array through that array:

long_array[10] = 12345;   // valid range is  from   long_array[0] to long_array[9]

Than you will overwrite the data of the object myobject.


问:
Matlab submatrix multiplication poor performance
Multiplications of submatricies in matlab seems to be materially slower than multiplication of the matrix they are drawn from.

```<code>>> m = rand(1e7, 40);
>> tic; m' * m; toc % (1)
Elapsed time is 0.245803 seconds.
>> tic; m(1:2.5e6, :)' * m(1:2.5e6, :); toc % (2)
Elapsed time is 1.810981 seconds.
>> tic; t = m(1:2.5e6, :); t' * t; toc % (3)
Elapsed time is 0.885764 seconds.
</code>```

I had hoped that there would be some fast builtin methods for this, since the data is already in memory, but it seems there's no way to prevent matlab from making intermediate copies. (3) is faster but garuntees that we make a copy.

Is there any technique in matlab to make operations (e.g. multiplcation, transpose) as quick on the subset of a matrix as they are the whole?

Is the only fast way to achieve this to with mex?

Edit: Using column major data speeds things up across the board (as expected), but is still much slower when multiplying the submatricies.

```<code>>> m = rand(40,1e7);
>> tic; m * m'; toc
Elapsed time is 0.251958 seconds.
>> tic; m(:, 1:2.5e6) * m(:, 1:2.5e6)'; toc
Elapsed time is 1.461321 seconds.
>> tic; s=m(:, 1:2.5e6); s * s'; toc
Elapsed time is 0.555667 seconds.
</code>```

Clearly matlab is taking copies when indexing, but is there any way to prevent this (it's clear such a multiplication algorithm can exist without copying the data, I just want to know if it's expressible in matlab).

答:
Here is more test results.

Five methods of performing matrix multiplication has been tested, 3 of which are involving submatrices. As @Cris has pointed out, there may be difference if using rand(1e7,40), so another whole set is tested.

A loop of 10 repeats and Profiler have been used to improve accuracy. Tested on a i7 with abundant RAM.

Test code

```<code>% clear;clc;close all

A = rand(1e7, 40);
for ii = 1:10
    m = A;
    m(end) = m(end-1);

    m' * m; % 1

    n = m';
    n * m; % 2

    m(1:2.5e6, :)' * m(1:2.5e6, :); % 3

    t = m(1:2.5e6, :);
    t' * t; % 4

    t2 = t';
    t2 * t; % 5

    clearvars -except A
end
clearvars A
B = rand(40, 1e7);
for ii = 1:10
    m = B;
    m(end) = m(end-1);

    m * m'; % 1

    n = m';
    m * n; % 2

    m(:,1:2.5e6) * m(:,1:2.5e6)'; % 3

    t = m(:,1:2.5e6);
    t * t'; % 4

    t2 = t';
    t * t2; % 5

    clearvars -except B
end
</code>```

Profiler result

Comments

Any time difference less than 10% is considered identical.

At the start of each loop, the matrix is forced to copy by a trivial assignment. The copy is pretty slow (11.5 sec).

For the complete matrix, no difference is found between MxN and NxM dimensions. However for the sub-matrix test, the 40x2.5e6 one is clearly faster.

Buffering the transpose slows down the entire process by 100%. I think it's because Matlab loses ability to optimize; probably if one types m'*m it identifies the pattern and skips the transpose operation.

Subsetting and then transposing is not optimized.

Buffering the subset does speed up the multiplication.

Body:
Multiplications of submatricies in matlab seems to be materially slower than multiplication of the matrix they are drawn from.

>> m = rand(1e7, 40);
>> tic; m' * m; toc % (1)
Elapsed time is 0.245803 seconds.
>> tic; m(1:2.5e6, :)' * m(1:2.5e6, :); toc % (2)
Elapsed time is 1.810981 seconds.
>> tic; t = m(1:2.5e6, :); t' * t; toc % (3)
Elapsed time is 0.885764 seconds.

I had hoped that there would be some fast builtin methods for this, since the data is already in memory, but it seems there's no way to prevent matlab from making intermediate copies. (3) is faster but garuntees that we make a copy.

Is there any technique in matlab to make operations (e.g. multiplcation, transpose) as quick on the subset of a matrix as they are the whole?

Is the only fast way to achieve this to with mex?

Edit: Using column major data speeds things up across the board (as expected), but is still much slower when multiplying the submatricies.

>> m = rand(40,1e7);
>> tic; m * m'; toc
Elapsed time is 0.251958 seconds.
>> tic; m(:, 1:2.5e6) * m(:, 1:2.5e6)'; toc
Elapsed time is 1.461321 seconds.
>> tic; s=m(:, 1:2.5e6); s * s'; toc
Elapsed time is 0.555667 seconds.

Clearly matlab is taking copies when indexing, but is there any way to prevent this (it's clear such a multiplication algorithm can exist without copying the data, I just want to know if it's expressible in matlab).

Body:
Here is more test results.

Five methods of performing matrix multiplication has been tested, 3 of which are involving submatrices. As @Cris has pointed out, there may be difference if using rand(1e7,40), so another whole set is tested.

A loop of 10 repeats and Profiler have been used to improve accuracy. Tested on a i7 with abundant RAM.

Test code

% clear;clc;close all

A = rand(1e7, 40);
for ii = 1:10
    m = A;
    m(end) = m(end-1);

    m' * m; % 1

    n = m';
    n * m; % 2

    m(1:2.5e6, :)' * m(1:2.5e6, :); % 3

    t = m(1:2.5e6, :);
    t' * t; % 4

    t2 = t';
    t2 * t; % 5

    clearvars -except A
end
clearvars A
B = rand(40, 1e7);
for ii = 1:10
    m = B;
    m(end) = m(end-1);

    m * m'; % 1

    n = m';
    m * n; % 2

    m(:,1:2.5e6) * m(:,1:2.5e6)'; % 3

    t = m(:,1:2.5e6);
    t * t'; % 4

    t2 = t';
    t * t2; % 5

    clearvars -except B
end

Profiler result

Comments

Any time difference less than 10% is considered identical.

At the start of each loop, the matrix is forced to copy by a trivial assignment. The copy is pretty slow (11.5 sec).

For the complete matrix, no difference is found between MxN and NxM dimensions. However for the sub-matrix test, the 40x2.5e6 one is clearly faster.

Buffering the transpose slows down the entire process by 100%. I think it's because Matlab loses ability to optimize; probably if one types m'*m it identifies the pattern and skips the transpose operation.

Subsetting and then transposing is not optimized.

Buffering the subset does speed up the multiplication.


问:
DynamoDB call history?
I have a DynamoDB application and it seems to be running well and using normal throughput generally.  However once in a while it seems to spike pretty high (latest kicked up over 300, normal is around 10-20 max).  I've looked through the code and I'm having a bit of trouble figuring out what it is that is causing these spikes.  Is there any type of history of the calls in DynamoDB that could tell me what exactly were the calls that caused the spiking?</p>

答:
You can enable the cloudtrail logs for the dynamoDB.It will deliver these log files to S3 bucket. Taken directly from the AWS Docs :-

DynamoDB is integrated with CloudTrail, a service that captures
  low-level API requests made by or on behalf of DynamoDB in your AWS
  account and delivers the log files to an Amazon S3 bucket that you
  specify. CloudTrail captures calls made from the DynamoDB console or
  from the DynamoDB low-level API. Using the information collected by
  CloudTrail, you can determine what request was made to DynamoDB, the
  source IP address from which the request was made, who made the
  request, when it was made, and so on. To learn more about CloudTrail,
  including how to configure and enable it, see the AWS CloudTrail User
  Guide.

Please follow the aws dynamoDB cloudtrail logging to enable it.

Title: DynamoDB call history?


问:
MinimumShouldMatch not appending to "Should" clause in a Bool query built using object initializer syntax in Nest ElasticSearch
I am using the NEST object initializer syntax to build my queries dynamically given user input. The query format I am using is like this:

```<code>"query": {
        "bool": {
            "should": [{
                "range": {
                    "field1": {
                        "lt": x
                    }
                }
            }, {
                "range": {
                    "field2": {
                        "lt": y
                    }
                }
            }],
            "filter": [{
                ...
            }]
        }
    }
</code>```

The above query doesn't work because the should is overridden by the filter unless the should clause has a "minimum_should_match" field attached to it, like so:

```<code>"query": {
        "bool": {
            "should": [{
                "range": {
                    "field1": {
                        "lt": x
                    }
                }
            }, {
                "range": {
                    "field2": {
                        "lt": y
                    }
                }
            }],
            "minimum_should_match" = "1",
            "filter": [{
                ...
            }]
        }
    }
</code>```

However, I can't seem to find a way to position the minimum_should_match clause correctly so that it sits in between the should and filter. The BoolQuery accepts a "MinimumShouldMatch" field, but that appends it after the filter and not before the should.

Is there a way to do this or I am going to have to use raw search input?

答: As per the comment by Russ Cam, the positioning of the "minimum_should_match" clause does not matter. I made a mistake in my testing that made my thinking the filter was being overridden, and I had wrongly assumed the positioning was the issue. I went and retested the query and it works correctly.</p>

Body:
I am using the NEST object initializer syntax to build my queries dynamically given user input. The query format I am using is like this:

"query": {
        "bool": {
            "should": [{
                "range": {
                    "field1": {
                        "lt": x
                    }
                }
            }, {
                "range": {
                    "field2": {
                        "lt": y
                    }
                }
            }],
            "filter": [{
                ...
            }]
        }
    }

The above query doesn't work because the should is overridden by the filter unless the should clause has a "minimum_should_match" field attached to it, like so:

"query": {
        "bool": {
            "should": [{
                "range": {
                    "field1": {
                        "lt": x
                    }
                }
            }, {
                "range": {
                    "field2": {
                        "lt": y
                    }
                }
            }],
            "minimum_should_match" = "1",
            "filter": [{
                ...
            }]
        }
    }

However, I can't seem to find a way to position the minimum_should_match clause correctly so that it sits in between the should and filter. The BoolQuery accepts a "MinimumShouldMatch" field, but that appends it after the filter and not before the should.

Is there a way to do this or I am going to have to use raw search input?


问:
How to set the tool tip on jqGrid mouse over?
How can you set the "tool tip" that appears when you hover your mouse over a jqGrid row/cell?

Currently the tool tip appears to just be the cell contents.

答: There is no jqGrid API for this. If you want to change the tooltip text you will have to write code to manually change the value of the cell's title element.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to set watchpoints on Swift properties?
In Objective-C, I would sometimes set watchpoints in LLDB to let me know when instance variables had changed. Can I do this with Swift properties too?

Right now, the only way I can achieve this is:

adding a didSet handler to the property and setting a breakpoint inside (but this requires stopping the program and recompiling, which kind of defeats the purpose)

adding a symbolic breakpoint on [setPropertyName:] but this only works if the class happens to support Objective-C bridging

Do I have any other options?

答:
On XCode (8.2 Swift 3.0) set breakpoint normally on the swift property then run your app. After the app has ran go to breakpoint panel you can expand the breakpoint into multiple breakpoints:

All are selected by default, you can then disable the ones you don't need.
NOTE: I found when you first add the breakpoint it will not expand until you run the app.

An alternative method you can try is to use lldb to add them. First add breakpoint somewhere inside your class instance eg viewDidLoad ext. p self and note the memory address of your instance.

Then add breakpoint like so where 0x0f0f0f0f0f0f is memory address of your object.

```<code>break set -F '-[MyClass setMyProperty:]' -c '$rdi == 0x0f0f0f0f0f0f'
</code>```

Body:
On XCode (8.2 Swift 3.0) set breakpoint normally on the swift property then run your app. After the app has ran go to breakpoint panel you can expand the breakpoint into multiple breakpoints:

All are selected by default, you can then disable the ones you don't need.
NOTE: I found when you first add the breakpoint it will not expand until you run the app.

An alternative method you can try is to use lldb to add them. First add breakpoint somewhere inside your class instance eg viewDidLoad ext. p self and note the memory address of your instance.

Then add breakpoint like so where 0x0f0f0f0f0f0f is memory address of your object.

break set -F '-[MyClass setMyProperty:]' -c '$rdi == 0x0f0f0f0f0f0f'

ContentLicense: CC BY-SA 4.0


问:
How to tell auto-format in VS Code not to insert spaces after opening and before closing curly braces?
Whenever I use the auto-format shortcut (Shift + Alt + k) in Visual Studio Code inside a file that contains this piece of code -

```<code>var keyframes = [
  {opacity: 0, transform: 'translate(0, 4em)'},
  {opacity: 1, transform: 'translate(0)'}
];
</code>```

I get this -

```<code>var keyframes = [
  { opacity: 0, transform: 'translate(0, 4em)' },
  { opacity: 1, transform: 'translate(0)' }
];
</code>```

I wonder if there's any way to tell the auto-format not to insert all the spaces?

答:
If anyone is looking for that option in react it is:

```<code>"typescript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": true
</code>```

Then it will format this

```<code><option key={org.id} value={org.id}>{org.displayName}</option>
</code>```

like this:

```<code><option key={ org.id } value={ org.id }>{ org.displayName }</option>
</code>```

Body:
Whenever I use the auto-format shortcut (Shift + Alt + k) in Visual Studio Code inside a file that contains this piece of code -

var keyframes = [
  {opacity: 0, transform: 'translate(0, 4em)'},
  {opacity: 1, transform: 'translate(0)'}
];

I get this -

var keyframes = [
  { opacity: 0, transform: 'translate(0, 4em)' },
  { opacity: 1, transform: 'translate(0)' }
];

I wonder if there's any way to tell the auto-format not to insert all the spaces?

Body:
If anyone is looking for that option in react it is:

"typescript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": true

Then it will format this

<option key={org.id} value={org.id}>{org.displayName}</option>

like this:

<option key={ org.id } value={ org.id }>{ org.displayName }</option>


问:
Angular: updating view with value passed from directive to controller
Budding web developer here struggling with updating the view from my controller.

I'm using highmaps and angular to build a neat selection tool for my web app. I've got a directive nested inside the scope of a controller. I would like this directive to update a value (selectedCountry) stored in the controller. Then, I'd like the controller to display the up to date selectedCountry value on the view.

I've checked that the directive is passing the correct selectedCountry value to the parent controller. However, the controller is not updating the view to match the updated value. I would greatly appreciate if someone could take a look at this.

Demo Here: http://jsfiddle.net/frauLLmr/5/

index.html

```<code><div ng-app="myApp">
  <div ng-controller="GraphController as graphCtrl">
    <div> {{graphCtrl.showSelectedCountry()}} </div>
    <div> {{graphCtrl.selectedCountry}} </div>
    <high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>
  </div>
</div>
</code>```

app.js

```<code>var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function() {
  var self = this;
  self.selectedCountry = 'unselected';
  var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
        + self.selectedCountry);
  };
  self.updateSelectedCountry = function(newCountry) {
    self.selectedCountry = newCountry;
    outsideScopeTest();
  };
  self.showSelectedCountry = function() {
    return self.selectedCountry;
  };
});

myApp.directive('highChartDirective', function () {
  return {
    restrict: 'E',
    scope: {
      updateSelectedCountry: '&'
    },
    link: function(scope, element) {
      Highcharts.mapChart(element[0], getMapOptions(mapClick));

      function mapClick(event) {
        scope.updateSelectedCountry({newCountry: event.point.name});
        alert('selectedCountry (from directive scope): '
        + event.point.name);
      }
    }
  };

  function getMapOptions(callback) {
    return {
      title: {
        text: ''
      },
      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },
      series: [{
        data: getTestCountries(),
        mapData: Highcharts.maps['custom/world-highres'],
        // TODO-chantelle: figure out how geoJSON joinBy works
        joinBy: 'hc-key',
        name: 'Emission per capita',
        states: {
          hover: {
            color: '#9370DB'
          }
        },
        dataLabels: {
          enabled: false,
          format: '{point.name}'
        }
      }],
      plotOptions: {
        series: {
          events: {
            click: function(event) {
              callback(event);
            }
          }
        }
      }
    };
  }

  function getTestCountries() {
    return [{
      "hc-key": "ca",
      "value": 0
    }, {
      "hc-key": "br",
      "value": 1
    }, {
      "hc-key": "ru",
      "value": 2
    }];
  }
});
</code>```

答:
Try this </p>

```<code><div ng-app="myApp">
  <div ng-controller="GraphController as graphCtrl">
    <div> {{graphCtrl.showSelectedCountry()}} </div>
    <div> {{graphCtrl.selectedCountry}} </div>
    <high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>
  </div>
</div>
</code>```

<p>the js </p>

```<code>var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function($scope) {
  var self = this;
  self.selectedCountry = 'unselected';
  var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
        + self.selectedCountry);
      $scope.$apply();
  };
  self.updateSelectedCountry = function(newCountry) {
    self.selectedCountry = newCountry;
    outsideScopeTest();
  };
  self.showSelectedCountry = function() {
    return self.selectedCountry;
  };
});

myApp.directive('highChartDirective', function () {
  return {
    restrict: 'E',
    scope: {
      updateSelectedCountry: '&'
    },
    link: function(scope, element) {
      Highcharts.mapChart(element[0], getMapOptions(mapClick));

      function mapClick(event) {
        scope.updateSelectedCountry({newCountry: event.point.name});
        alert('selectedCountry (from directive scope): '
        + event.point.name);
      }
    }
  };

  function getMapOptions(callback) {
    return {
      title: {
        text: ''
      },
      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },
      series: [{
        data: getTestCountries(),
        mapData: Highcharts.maps['custom/world-highres'],
        // TODO-chantelle: figure out how geoJSON joinBy works
        joinBy: 'hc-key',
        name: 'Emission per capita',
        states: {
          hover: {
            color: '#9370DB'
          }
        },
        dataLabels: {
          enabled: false,
          format: '{point.name}'
        }
      }],
      plotOptions: {
        series: {
          events: {
            click: function(event) {
              callback(event);
            }
          }
        }
      }
    };
  }

  function getTestCountries() {
    return [{
      "hc-key": "ca",
      "value": 0
    }, {
      "hc-key": "br",
      "value": 1
    }, {
      "hc-key": "ru",
      "value": 2
    }];
  }
});
</code>```

Body:
Budding web developer here struggling with updating the view from my controller.

I'm using highmaps and angular to build a neat selection tool for my web app. I've got a directive nested inside the scope of a controller. I would like this directive to update a value (selectedCountry) stored in the controller. Then, I'd like the controller to display the up to date selectedCountry value on the view.

I've checked that the directive is passing the correct selectedCountry value to the parent controller. However, the controller is not updating the view to match the updated value. I would greatly appreciate if someone could take a look at this.

Demo Here: http://jsfiddle.net/frauLLmr/5/

index.html

 {{graphCtrl.showSelectedCountry()}}

 {{graphCtrl.selectedCountry}}

    <high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>

app.js

var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function() {
  var self = this;
  self.selectedCountry = 'unselected';
  var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
        + self.selectedCountry);
  };
  self.updateSelectedCountry = function(newCountry) {
    self.selectedCountry = newCountry;
    outsideScopeTest();
  };
  self.showSelectedCountry = function() {
    return self.selectedCountry;
  };
});

myApp.directive('highChartDirective', function () {
  return {
    restrict: 'E',
    scope: {
      updateSelectedCountry: '&'
    },
    link: function(scope, element) {
      Highcharts.mapChart(element[0], getMapOptions(mapClick));

      function mapClick(event) {
        scope.updateSelectedCountry({newCountry: event.point.name});
        alert('selectedCountry (from directive scope): '
        + event.point.name);
      }
    }
  };

  function getMapOptions(callback) {
    return {
      title: {
        text: ''
      },
      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },
      series: [{
        data: getTestCountries(),
        mapData: Highcharts.maps['custom/world-highres'],
        // TODO-chantelle: figure out how geoJSON joinBy works
        joinBy: 'hc-key',
        name: 'Emission per capita',
        states: {
          hover: {
            color: '#9370DB'
          }
        },
        dataLabels: {
          enabled: false,
          format: '{point.name}'
        }
      }],
      plotOptions: {
        series: {
          events: {
            click: function(event) {
              callback(event);
            }
          }
        }
      }
    };
  }

  function getTestCountries() {
    return [{
      "hc-key": "ca",
      "value": 0
    }, {
      "hc-key": "br",
      "value": 1
    }, {
      "hc-key": "ru",
      "value": 2
    }];
  }
});

Body:
Try this

<div ng-app="myApp">
  <div ng-controller="GraphController as graphCtrl">
    <div> {{graphCtrl.showSelectedCountry()}} </div>
    <div> {{graphCtrl.selectedCountry}} </div>
    <high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>
  </div>
</div>

the js

var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function($scope) {
  var self = this;
  self.selectedCountry = 'unselected';
  var outsideScopeTest = function() {
    alert('selectedCountry (from controller scope): '
        + self.selectedCountry);
      $scope.$apply();
  };
  self.updateSelectedCountry = function(newCountry) {
    self.selectedCountry = newCountry;
    outsideScopeTest();
  };
  self.showSelectedCountry = function() {
    return self.selectedCountry;
  };
});

myApp.directive('highChartDirective', function () {
  return {
    restrict: 'E',
    scope: {
      updateSelectedCountry: '&'
    },
    link: function(scope, element) {
      Highcharts.mapChart(element[0], getMapOptions(mapClick));

      function mapClick(event) {
        scope.updateSelectedCountry({newCountry: event.point.name});
        alert('selectedCountry (from directive scope): '
        + event.point.name);
      }
    }
  };

  function getMapOptions(callback) {
    return {
      title: {
        text: ''
      },
      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },
      series: [{
        data: getTestCountries(),
        mapData: Highcharts.maps['custom/world-highres'],
        // TODO-chantelle: figure out how geoJSON joinBy works
        joinBy: 'hc-key',
        name: 'Emission per capita',
        states: {
          hover: {
            color: '#9370DB'
          }
        },
        dataLabels: {
          enabled: false,
          format: '{point.name}'
        }
      }],
      plotOptions: {
        series: {
          events: {
            click: function(event) {
              callback(event);
            }
          }
        }
      }
    };
  }

  function getTestCountries() {
    return [{
      "hc-key": "ca",
      "value": 0
    }, {
      "hc-key": "br",
      "value": 1
    }, {
      "hc-key": "ru",
      "value": 2
    }];
  }
});


问:
Keep d3-cloud consistent between refreshes with a seed value?
Is there a way to pass a seed value to d3-cloud or another javascript based tag cloud in order to keep it consistent between page loads?

Our client wants to use a tag cloud as a navigation/discovery aid but due to d3-cloud randomizing the placement each time it's usefulness is lowered.

Is there a way to pass a seed value or modify the cloud to keep it looking the same if the input is the same? I do not require rotation and the name and size will be (for most of the time) constant and predetermined.

I could save a representation of it to localstorage but when Jenny looks at it on her tablet or goes to help Jane it won't be consistent

Can anyone make any recommendations on how I could create a persistent state word cloud?

答:
We have found a fix :)

Set random to return 1 to not randomize the initial placement of the words

```<code>var layout = cloud()
    .size([1500, 475])
    .words(sitesList.map(function(d) {
      return {text: d, size: 10, test: "haha"};
    }))
    .padding(5)
    .rotate(function() { return ~~(Math.random() * 1) * 90; })
    .font("Impact")
    .fontSize(function(d) { return d.size; })
    .random(function(d) { return 1; })
    .on("end", draw);
</code>```

Edit: After further experimentation it looks better to return 0.5, this seems to group the words in the center. Higher numbers appear to push it off to the bottom right corner

Body:
We have found a fix :)

Set random to return 1 to not randomize the initial placement of the words

var layout = cloud()
    .size([1500, 475])
    .words(sitesList.map(function(d) {
      return {text: d, size: 10, test: "haha"};
    }))
    .padding(5)
    .rotate(function() { return ~~(Math.random() * 1) * 90; })
    .font("Impact")
    .fontSize(function(d) { return d.size; })
    .random(function(d) { return 1; })
    .on("end", draw);

Edit: After further experimentation it looks better to return 0.5, this seems to group the words in the center. Higher numbers appear to push it off to the bottom right corner


问:
Calling function of a subclass of Immutable.Map throws 'xxx is not a function' exception
I have created a new class this way:

```<code>import Immutable from 'immutable';

export default class Faq extends Immutable.Map {

  getState(faqNum) {
    return this.get(faqNum) || false;
  }

  setState(faqNum, open) {
    return this.set(faqNum, open);
  }
}
</code>```

But when I call getState on an instance of Faq, it throws an exception faqState.getState is not a function exception?

Why it does not work?

答: As it turns out Immutable-js does not support class inheritance. (https://github.com/facebook/immutable-js/issues/301)

Body:
I have created a new class this way:

import Immutable from 'immutable';

export default class Faq extends Immutable.Map {

  getState(faqNum) {
    return this.get(faqNum) || false;
  }

  setState(faqNum, open) {
    return this.set(faqNum, open);
  }
}

But when I call getState on an instance of Faq, it throws an exception faqState.getState is not a function exception?

Why it does not work?


问:
Mongoimport import json array as collection not as key in collection
I am attempting to seed a database with a json array of data with mongoimport, however when the data reaches the mongo collection, it imports as a key in the collection object like this:

"items" is my json file, it always shows up as "items", I want the parent array to be the array I'm trying to import itself, does this make sense?

Update

Please see this example, the first image is how mongoimport is importing this array of objects:

```<code>{ "_id" : ObjectId("58dc01ecec116d4c9039e47c"), "items" : [ { "id" : 1, "_id" : "item1", "type" : "alert", "title" : "hello.world", "email" : "something@something.com", "message" : "", "createdDate" : "date", "price" : "$9.00", "active" : true }, { "id" : 2, "_id" : "item2", "type" : "welcome.lol", "title" : "Item 2", "email" : "something@something.com", "message" : "lol", "createdDate" : "date", "price" : "$12.00", "active" : true }, { "id" : 3, "_id" : "item3", "type" : "message", "title" : "various.domain", "email" : "something@something.com", "message" : "lol", "createdDate" : "date", "price" : "$3.00", "active" : false }, { "id" : 4, "_id" : "item4", "type" : "message", "title" : "something.else", "message" : "", "createdDate" : "date", "price" : "$12.00", "active" : false }, { "id" : 5, "_id" : "item5", "type" : "update", "title" : "wow.lol", "email" : "something@something.com", "message" : "", "createdDate" : "date", "price" : "$12.00", "active" : false }, { "id" : 6, "_id" : "item6", "type" : "update", "title" : "domainname.net", "email" : "something@something.com", "message" : "cars", "createdDate" : "date", "price" : "$12.00", "active" : false }, { "id" : 7, "_id" : "item7", "type" : "update", "title" : "something.lol", "email" : "something@something.com", "message" : "", "createdDate" : "date", "price" : "$12.00", "active" : false } ] }
</code>```

Notice how its treats the entire array as an "item" object, with a key in the item "items" which is the array, I want the data to look like this:

```<code>{ "_id" : ObjectId("58dc027a2c74df002a957281"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:42.227Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957282"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.574Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957283"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.708Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957284"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.855Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957285"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.994Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027c2c74df002a957286"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:44.128Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027c2c74df002a957287"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:44.263Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027c2c74df002a957288"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:44.391Z"), "active" : true, "__v" : 0 }
</code>```

Where each item in the array is created as an "item" in mongo, each with its own ObjectID - otherwise it's useless for CRUD applications.

Docker MongoDB Log:

```<code>mongodb_1       | 2017-03-29T21:38:09.439+0000 I COMMAND  [conn1] command reach-engine.domains command: insert { insert: "domains", documents: [ { items: [ { id: 1, _id: "item1", type: "alert", title: "hello.world", email: "something@something.com", message: "", createdDate: "date", price: "$9.00", active: true }, { id: 2, _id: "item2", type: "welcome.lol", title: "Item 2", email: "something@something.com", message: "lol", createdDate: "date", price: "$12.00", active: true }, { id: 3, _id: "item3", type: "message", title: "various.domain", email: "something@something.com", message: "lol", createdDate: "date", price: "$3.00", active: false }, { id: 4, _id: "item4", type: "message", title: "something.else", message: "", createdDate: "date", price: "$12.00", active: false }, { id: 5, _id: "item5", type: "update", title: "wow.lol", email: "something@something.com", message: "", createdDate: "date", price: "$12.00", active: false }, { id: 6, _id: "item6", type: "update", title: "domainname.net", email: "something@something.com", message: "cars", createdDate: "date", price: "$12.00", active: false }, { id: 7, _id: "item7", type: "update", title: "something.lol", email: "something@something.com", message: "", createdDate: "date", price: "$12.00", active: false } ] } ], writeConcern: { getLastError: 1, w: 1 }, ordered: false } ninserted:1 keyUpdates:0 writeConflicts:0 numYields:0 reslen:40 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 1, W: 1 } }, Collection: { acquireCount: { W: 1 } } } protocol:op_query 250ms
</code>```

答:
It would be useful to know what command you are using to import, but I just created a database an imported the following JSON with this command:

mongoimport --db test --collection example --type json --file example.json --jsonArray

Make sure you are using the --jsonArray flag

example.json

```<code>[
    {
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    },
    {
        "color": "blue",
        "value": "#00f"
    },
    {
        "color": "cyan",
        "value": "#0ff"
    },
    {
        "color": "magenta",
        "value": "#f0f"
    },
    {
        "color": "yellow",
        "value": "#ff0"
    },
    {
        "color": "black",
        "value": "#000"
    }
]
</code>```

Body:
I am attempting to seed a database with a json array of data with mongoimport, however when the data reaches the mongo collection, it imports as a key in the collection object like this:

"items" is my json file, it always shows up as "items", I want the parent array to be the array I'm trying to import itself, does this make sense?

Update

Please see this example, the first image is how mongoimport is importing this array of objects:

{ "_id" : ObjectId("58dc01ecec116d4c9039e47c"), "items" : [ { "id" : 1, "_id" : "item1", "type" : "alert", "title" : "hello.world", "email" : "something@something.com", "message" : "", "createdDate" : "date", "price" : "$9.00", "active" : true }, { "id" : 2, "_id" : "item2", "type" : "welcome.lol", "title" : "Item 2", "email" : "something@something.com", "message" : "lol", "createdDate" : "date", "price" : "$12.00", "active" : true }, { "id" : 3, "_id" : "item3", "type" : "message", "title" : "various.domain", "email" : "something@something.com", "message" : "lol", "createdDate" : "date", "price" : "$3.00", "active" : false }, { "id" : 4, "_id" : "item4", "type" : "message", "title" : "something.else", "message" : "", "createdDate" : "date", "price" : "$12.00", "active" : false }, { "id" : 5, "_id" : "item5", "type" : "update", "title" : "wow.lol", "email" : "something@something.com", "message" : "", "createdDate" : "date", "price" : "$12.00", "active" : false }, { "id" : 6, "_id" : "item6", "type" : "update", "title" : "domainname.net", "email" : "something@something.com", "message" : "cars", "createdDate" : "date", "price" : "$12.00", "active" : false }, { "id" : 7, "_id" : "item7", "type" : "update", "title" : "something.lol", "email" : "something@something.com", "message" : "", "createdDate" : "date", "price" : "$12.00", "active" : false } ] }

Notice how its treats the entire array as an "item" object, with a key in the item "items" which is the array, I want the data to look like this:

{ "_id" : ObjectId("58dc027a2c74df002a957281"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:42.227Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957282"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.574Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957283"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.708Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957284"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.855Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027b2c74df002a957285"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:43.994Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027c2c74df002a957286"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:44.128Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027c2c74df002a957287"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:44.263Z"), "active" : true, "__v" : 0 }
{ "_id" : ObjectId("58dc027c2c74df002a957288"), "price" : "asdf", "message" : "asdf", "email" : "aasfd", "title" : "asdf", "dateCreated" : ISODate("2017-03-29T18:52:44.391Z"), "active" : true, "__v" : 0 }

Where each item in the array is created as an "item" in mongo, each with its own ObjectID - otherwise it's useless for CRUD applications.

Docker MongoDB Log:

mongodb_1       | 2017-03-29T21:38:09.439+0000 I COMMAND  [conn1] command reach-engine.domains command: insert { insert: "domains", documents: [ { items: [ { id: 1, _id: "item1", type: "alert", title: "hello.world", email: "something@something.com", message: "", createdDate: "date", price: "$9.00", active: true }, { id: 2, _id: "item2", type: "welcome.lol", title: "Item 2", email: "something@something.com", message: "lol", createdDate: "date", price: "$12.00", active: true }, { id: 3, _id: "item3", type: "message", title: "various.domain", email: "something@something.com", message: "lol", createdDate: "date", price: "$3.00", active: false }, { id: 4, _id: "item4", type: "message", title: "something.else", message: "", createdDate: "date", price: "$12.00", active: false }, { id: 5, _id: "item5", type: "update", title: "wow.lol", email: "something@something.com", message: "", createdDate: "date", price: "$12.00", active: false }, { id: 6, _id: "item6", type: "update", title: "domainname.net", email: "something@something.com", message: "cars", createdDate: "date", price: "$12.00", active: false }, { id: 7, _id: "item7", type: "update", title: "something.lol", email: "something@something.com", message: "", createdDate: "date", price: "$12.00", active: false } ] } ], writeConcern: { getLastError: 1, w: 1 }, ordered: false } ninserted:1 keyUpdates:0 writeConflicts:0 numYields:0 reslen:40 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 1, W: 1 } }, Collection: { acquireCount: { W: 1 } } } protocol:op_query 250ms

Body:
It would be useful to know what command you are using to import, but I just created a database an imported the following JSON with this command:

mongoimport --db test --collection example --type json --file example.json --jsonArray

Make sure you are using the --jsonArray flag

example.json

[
    {
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    },
    {
        "color": "blue",
        "value": "#00f"
    },
    {
        "color": "cyan",
        "value": "#0ff"
    },
    {
        "color": "magenta",
        "value": "#f0f"
    },
    {
        "color": "yellow",
        "value": "#ff0"
    },
    {
        "color": "black",
        "value": "#000"
    }
]


问:
ASP Menu auto-adds clear div
I want my header to look like this:

```<code>Link | Link | Link                                               Image
-----------------------------------------------------------------------
</code>```

What I have instead is:

```<code>Link | Link | Link
-----------------------------------------------------------------------
                                                                 Image
</code>```

ASP code:

```<code><div class="hideSkiplink">
     <asp:Menu ID="NavigationMenu" runat="server" EnableViewState="False" IncludeStyleBlock="true" Orientation="Horizontal" >
          <Items>
               <asp:MenuItem NavigateUrl="~/Default.aspx" ImageUrl="~/ICONS/About/home_Icon.png"/>
               <asp:MenuItem NavigateUrl="~/About.aspx" ImageUrl="~/ICONS/About/about_Icon.png"/>
               <asp:MenuItem NavigateUrl="~/RestrictedPages/AdminMenu.aspx" ImageUrl="~/ICONS/About/admin_Icon.png"></asp:MenuItem>
          </Items>
     </asp:Menu>
     <div class="logo">
          <asp:Image ID="Image1" runat="server" ImageUrl="~/ICONS/About/logo.png" />
     </div>
</div>
</code>```

CSS:

```<code>div.hideSkiplink {
    background-color: #3a4f63;
    width: 100%;
}

div.logo {
   float: right;
}
</code>```

Inspecting the element in Firebug shows:

```<code><div class="hideSkiplink">
  <a href="#NavigationMenu_SkipLink">
    <div id="NavigationMenu" style="float: left;">
      <div style="clear: left;"></div>
</code>```

I think the div with clear: left is being created automatically and that is what is causing the issue.

What can be done to prevent this element from being created or is there a workaround to compensate for its inclusion?

答:
The correct, and complete, answer is:

1) add, as "musium" commented, the following to your CSS

```<code>#IDOfYourMenuControl + div {
clear: none !important;
}
</code>```

This will stop the unexpected

```<code><div style="clear: left";></div>
</code>```

2) add the following to your asp.menu tag

```<code>SkipLinkText=""
</code>```

This will stop the unexpected

```<code><a id="yourmenuID_SkipLink">
</code>```

tag from being  created.

You're welcome. :-)

Title: ASP Menu auto-adds clear div

Body:
I want my header to look like this:

Link | Link | Link                                               Image
-----------------------------------------------------------------------

What I have instead is:

Link | Link | Link
-----------------------------------------------------------------------
                                                                 Image

ASP code:

     <asp:Menu ID="NavigationMenu" runat="server" EnableViewState="False" IncludeStyleBlock="true" Orientation="Horizontal" >
          <Items>
               <asp:MenuItem NavigateUrl="~/Default.aspx" ImageUrl="~/ICONS/About/home_Icon.png"/>
               <asp:MenuItem NavigateUrl="~/About.aspx" ImageUrl="~/ICONS/About/about_Icon.png"/>
               <asp:MenuItem NavigateUrl="~/RestrictedPages/AdminMenu.aspx" ImageUrl="~/ICONS/About/admin_Icon.png"></asp:MenuItem>
          </Items>
     </asp:Menu>

          <asp:Image ID="Image1" runat="server" ImageUrl="~/ICONS/About/logo.png" />

CSS:

div.hideSkiplink {
    background-color: #3a4f63;
    width: 100%;
}

div.logo {
   float: right;
}

Inspecting the element in Firebug shows:

I think the div with clear: left is being created automatically and that is what is causing the issue.

What can be done to prevent this element from being created or is there a workaround to compensate for its inclusion?

Body:
The correct, and complete, answer is:

1) add, as "musium" commented, the following to your CSS

#IDOfYourMenuControl + div {
clear: none !important;
}

This will stop the unexpected

<div style="clear: left";></div>

2) add the following to your asp.menu tag

SkipLinkText=""

This will stop the unexpected

<a id="yourmenuID_SkipLink">

tag from being  created.

You're welcome. :-)


问:
I am trying to join two table but getting the error as Invalid object name
I want to Write a SQL script, which would return all the Employees in EmployeeMaster table with the columns LastName, City, State and Country.

This is what I tried to execute but it shows error.

```<code>SELECT dbo.EmployeeMaster.LastName, dbo.EmployeeDetails.City, State, Country
From dbo.EmployeeMaster
LEFT JOIN EmployeeDetails
ON dbo.EmployeeMaster.ID=dbo.EmployeeDetails.EmployeeID
ORDER BY dbo.EmployeeMaster.LastName
</code>```

答:
I think you are missing dbo prefixe on your left join no ? Since you are sing it on the ON, ORDER  and SELECT

```<code>SELECT dbo.EmployeeMaster.LastName, dbo.EmployeeDetails.City, State, Country
From dbo.EmployeeMaster
LEFT JOIN dbo.EmployeeDetails ON dbo.EmployeeMaster.ID=dbo.EmployeeDetails.EmployeeID
ORDER BY dbo.EmployeeMaster.LastName
</code>```

Not sure which table State & ountry are from, hoping they are not in both table else you need to add their table alias.

Body:
I want to Write a SQL script, which would return all the Employees in EmployeeMaster table with the columns LastName, City, State and Country.

This is what I tried to execute but it shows error.

SELECT dbo.EmployeeMaster.LastName, dbo.EmployeeDetails.City, State, Country
From dbo.EmployeeMaster
LEFT JOIN EmployeeDetails
ON dbo.EmployeeMaster.ID=dbo.EmployeeDetails.EmployeeID
ORDER BY dbo.EmployeeMaster.LastName

Body:
I think you are missing dbo prefixe on your left join no ? Since you are sing it on the ON, ORDER  and SELECT

SELECT dbo.EmployeeMaster.LastName, dbo.EmployeeDetails.City, State, Country
From dbo.EmployeeMaster
LEFT JOIN dbo.EmployeeDetails ON dbo.EmployeeMaster.ID=dbo.EmployeeDetails.EmployeeID
ORDER BY dbo.EmployeeMaster.LastName

Not sure which table State & ountry are from, hoping they are not in both table else you need to add their table alias.