问:
How to convert BMP image to 8-bit greyscale
I have to make a program that reads a 24 bit BMP image(without ImageIO or any external library) and make it a 8 bit greyscale BMP image... I read that I must change the header of the image to make it a 8 bit, Source 1 and Source 2. So I read here that the BitCount bytes are at 29 and 30 of the Header and try to change them...

First I read my file and generate the byte vector like this

```<code>FileInputStream image= new FileInputStream(path);
byte[] bytesImage = new byte[image.available()];
image.read(bytesImage);
image.close();
</code>```

Then I get the image header and copy it to a new vector

```<code>int width = byteToInt(bytesImage[18], bytesImage[19], bytesImage[20], bytesImage[21]);
int height = byteToInt(bytesImage[22], bytesImage[23], bytesImage[24], bytesImage[25]);
int header = byteToInt(bytesImage[14], bytesImage[15], bytesImage[16], bytesImage[17]) + 14; // Add 14 for the header
vecGrey = Arrays.copyOf(bytesImage, bytesImage.length);
</code>```

Then I change the header info bytes to make it an 8 bit BMP like this:

```<code>byte[] values = intToByte(8);
vecGrey[28] = values[0];    // This is the index for the BitCount byte 1
vecGrey[29] = values[1];    // and this one is the index for the second one.
</code>```

Okay now comes the problem, for some reason I can't write a file with the header in vecGrey if i try to write vecGrey with a diferent header as show here:

```<code>FileOutputStream aGrey = new FileOutputStream(name+ "-gray.bmp");
aGrey.write(vecGrey);
aGrey.close();
// This is a method that displays the resulting image in a frame...
makeInterface(name + "-gray.bmp");
</code>```

I know that I must change values in the vecGrey, but this should work showing incorrect output(probably a non greyscale image or not an image at all). But when I try to read the file that I generate in the makeInterface() method I get a

javax.imageio.iioexception unable to read the image header

So I asume that the program is unable to read correctly the header, but I don't know why! If I change the BitCount value to 16 it still works, but to 1, 4 or 8 it doesn't work with the same error... I didn't upload my hole code because it's in spanish, but if needed I can translate it and edit here.

Thanks!

EDIT1: I'm only using 640x480 24-bit BMP images, so I don't need to check padding.

答:
you should first see the hex format of both 24-bit BMP as well as gray scale BMP, then you should go step wise,
-read 24-bit bmp header
-read data after offset.
-write header of 8-bit gray scale image
-write the data into 8-bit gray scale image.
note: you have to convert rgb bits into 8-bit gray scale by adding rgb bits and divide them by 3.</p>

Body:
I have to make a program that reads a 24 bit BMP image(without ImageIO or any external library) and make it a 8 bit greyscale BMP image... I read that I must change the header of the image to make it a 8 bit, Source 1 and Source 2. So I read here that the BitCount bytes are at 29 and 30 of the Header and try to change them...

First I read my file and generate the byte vector like this

FileInputStream image= new FileInputStream(path);
byte[] bytesImage = new byte[image.available()];
image.read(bytesImage);
image.close();

Then I get the image header and copy it to a new vector

int width = byteToInt(bytesImage[18], bytesImage[19], bytesImage[20], bytesImage[21]);
int height = byteToInt(bytesImage[22], bytesImage[23], bytesImage[24], bytesImage[25]);
int header = byteToInt(bytesImage[14], bytesImage[15], bytesImage[16], bytesImage[17]) + 14; // Add 14 for the header
vecGrey = Arrays.copyOf(bytesImage, bytesImage.length);

Then I change the header info bytes to make it an 8 bit BMP like this:

byte[] values = intToByte(8);
vecGrey[28] = values[0];    // This is the index for the BitCount byte 1
vecGrey[29] = values[1];    // and this one is the index for the second one.

Okay now comes the problem, for some reason I can't write a file with the header in vecGrey if i try to write vecGrey with a diferent header as show here:

FileOutputStream aGrey = new FileOutputStream(name+ "-gray.bmp");
aGrey.write(vecGrey);
aGrey.close();
// This is a method that displays the resulting image in a frame...
makeInterface(name + "-gray.bmp");

I know that I must change values in the vecGrey, but this should work showing incorrect output(probably a non greyscale image or not an image at all). But when I try to read the file that I generate in the makeInterface() method I get a

javax.imageio.iioexception unable to read the image header

So I asume that the program is unable to read correctly the header, but I don't know why! If I change the BitCount value to 16 it still works, but to 1, 4 or 8 it doesn't work with the same error... I didn't upload my hole code because it's in spanish, but if needed I can translate it and edit here.

Thanks!

EDIT1: I'm only using 640x480 24-bit BMP images, so I don't need to check padding.


来源: stackexchange

问:
update missing values in Python Pandas dataframe with matching conditions
I have a dataframe df1 with 3 columns (A,B,C), NaN represents missing value here

```<code>A     B      C
1     2    NaN
2     1    2.3
2     3    2.5
</code>```

I have a dataframe df2 with 3 columns (A,B,D)

```<code>A     B     D
1     2     2
2     1     2
2     3     4
</code>```

The expected output would be

```<code>A     B      C
1     2      2
2     1      2.3
2     3      2.5
</code>```

I want to have values in column C in df1 intact if not missing, replaced by corresponding value in D with other two columns value equal, i.e, df1.A==df2.A and df1.B==df2.B

any good solution?

答:
One way would be to use the columns A and B as the index. If you use fillna then, pandas will align the indices and give you the correct result:</p>

```<code>df1.set_index(['A', 'B'])['C'].fillna(df2.set_index(['A', 'B'])['D']).reset_index()
Out:
   A  B    C
0  1  2  2.0
1  2  1  2.3
2  2  3  2.5
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe df1 with 3 columns (A,B,C), NaN represents missing value here

A     B      C
1     2    NaN
2     1    2.3
2     3    2.5

I have a dataframe df2 with 3 columns (A,B,D)

A     B     D
1     2     2
2     1     2
2     3     4

The expected output would be

A     B      C
1     2      2
2     1      2.3
2     3      2.5

I want to have values in column C in df1 intact if not missing, replaced by corresponding value in D with other two columns value equal, i.e, df1.A==df2.A and df1.B==df2.B

any good solution?

Body:
One way would be to use the columns A and B as the index. If you use fillna then, pandas will align the indices and give you the correct result:

df1.set_index(['A', 'B'])['C'].fillna(df2.set_index(['A', 'B'])['D']).reset_index()
Out:
   A  B    C
0  1  2  2.0
1  2  1  2.3
2  2  3  2.5


问:
Getting multiple strings as inputs
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.

Sample Input:

```<code>@ON SNOW
ARYA STARK
HODOR
@
</code>```

Output:

```<code>NO
</code>```

My code:

```<code>#include <stdio.h>
#include <ctype.h>
int main(){
    char s1[100],s2[100],s3[100];
    char ch[1];
    scanf("%[^\n]s",s1);
    scanf("%[^\n]s",s2);
    scanf("%[^\n]s",s3);
    scanf("%s",ch);
    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");
}
</code>```

As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.

```<code>John Player
NO
</code>```

What is the way to store multiple strings in a char array without using loops and only using branching??

答:
Try fgets.</p>

```<code>fgets(s1,100,stdin);
fgets(s2,100,stdin);
fgets(s3,100,stdin);
</code>```

Title: Getting multiple strings as inputs

Body:
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.

Sample Input:

@ON SNOW
ARYA STARK
HODOR
@

Output:

NO

My code:

#include <stdio.h>
#include <ctype.h>
int main(){
    char s1[100],s2[100],s3[100];
    char ch[1];
    scanf("%[^\n]s",s1);
    scanf("%[^\n]s",s2);
    scanf("%[^\n]s",s3);
    scanf("%s",ch);
    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");
}

As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.

John Player
NO

What is the way to store multiple strings in a char array without using loops and only using branching??

Body:
Try fgets.

fgets(s1,100,stdin);
fgets(s2,100,stdin);
fgets(s3,100,stdin);


问:
Appending to query string with everything intact
I tried the below. That doesn't seem to work.

If the referrer has the string google.com, I want the rewrite rule to trigger, and preserve the existing query string and just append the referrer to the end of the query string

```<code>RewriteEngine On
RewriteCond %{HTTP_REFERER} .*google.com.*$
RewriteRule ^(.*)$ ^(.*)$referrer=%{HTTP_REFERER} [QSA]
</code>```

I'm sure something in my rewriterule is wrong. Can someone point me in the right direction?

答:
This worked

```<code>RewriteEngine On
RewriteCond %{HTTP_REFERER} google\.com
RewriteCond %{QUERY_STRING}    !^referrer=(.*)$    [NC]
RewriteRule ^(.*)$ $1?referrer=%{HTTP_REFERER} [L,R,QSA]
</code>```

I needed to add a condition that if there is already a referrer query string parameter, don't append it. Else I was getting an infinite loop.

And I needed a external Redirect flag. Else it was not redirecting.

Body:
I tried the below. That doesn't seem to work.

If the referrer has the string google.com, I want the rewrite rule to trigger, and preserve the existing query string and just append the referrer to the end of the query string

RewriteEngine On
RewriteCond %{HTTP_REFERER} .*google.com.*$
RewriteRule ^(.*)$ ^(.*)$referrer=%{HTTP_REFERER} [QSA]

I'm sure something in my rewriterule is wrong. Can someone point me in the right direction?

Body:
This worked

RewriteEngine On
RewriteCond %{HTTP_REFERER} google\.com
RewriteCond %{QUERY_STRING}    !^referrer=(.*)$    [NC]
RewriteRule ^(.*)$ $1?referrer=%{HTTP_REFERER} [L,R,QSA]

I needed to add a condition that if there is already a referrer query string parameter, don't append it. Else I was getting an infinite loop.

And I needed a external Redirect flag. Else it was not redirecting.


问:
Getting and removing a part of a string by first and last occurance of character
I have a string like this:

```<code>{something:something}Some data will be here
</code>```

Heres how its setup:

```<code>{username:password}data
</code>```

How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.

Preferably I would like to get the username:password without the {} so I can just split by :

答:
You can first use substring and index of to remove the unwanted characters.

```<code>string input = {username:password}data
input = input.Substring(input.IndexOf("}") +1);   //data
</code>```

This will give you the data part assuming } occurs only once.

Body:
I have a string like this:

{something:something}Some data will be here

Heres how its setup:

{username:password}data

How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.

Preferably I would like to get the username:password without the {} so I can just split by :

Body:
You can first use substring and index of to remove the unwanted characters.

string input = {username:password}data
input = input.Substring(input.IndexOf("}") +1);   //data

This will give you the data part assuming } occurs only once.


问:
Is python is a good choice as language used to implementing my first 3D model?
I am C/C  /Java programmer, but lately I have started learn Python.

Moreover I have 3D Graphics on my studies. I have to create 3D model of my apartment, with dynamic camera. I am wondering if this is a good idea to merge this two issues, by writing this 3D model in python.

However as I said, I am a python beginner, so I don't know possibilities, which python can give me in this area. Which libraries/engine will be the best for a start?

答:
IMHO C++ is a better option for 3D graphics, and you have experience in it.
Though you can have a look at PyOpenGL, python bindings for OpenGl.

http://pyopengl.sourceforge.net/

ContentLicense: CC BY-SA 2.5


问:
How to get Linkedin profile information (as Name, Bio, etc) using API, if i only have an Email?
How to get Linkedin profile information (as Name, Bio, etc) using API, if i only have an Email? </p>

<p>So there is a thing: i have a bunch of emails, and i want to get information about them. How can i do this, using Linkedin API? </p>

答:
It doesn't seem to be possible. Check Opal's answer:

LinkedIn has closed its API some time ago. See a detailed announcement here.

Body:
How to get Linkedin profile information (as Name, Bio, etc) using API, if i only have an Email?

So there is a thing: i have a bunch of emails, and i want to get information about them. How can i do this, using Linkedin API?


问:
Use transactions with mariadb and node.js
Is there a better way to use transactions with the mariasql library than adding BEGIN to the start of the query, and finalizing with either a commit or a rollback?

Currently, if I want to wrap a series of queries in a transaction I have to do something like this:

```<code>const MariaClient = require('mariasql');
let client = new MariaClient();

client.connect({
    host: "127.0.0.1",
    user: "user",
    password: "pass",
    db: "some_db",
    multiStatements: true
});

client.query('BEGIN; INSERT INTO some_table VALUES ("a0","b0"), ("a1","b1"), ("a2","b2");', function (err) {
    if (err) {
        client.query('ROLLBACK;');
    }
    client.query('COMMIT;');
});
</code>```

This seems clunky and potentially error prone.  We are using the generic-pool to manage the mariadb client, so it seems like there could be some unintended consequences handling transactions this way.

答:
Plan A:  If autocommit is set to 1, then each statement is its own transaction.  No BEGIN/COMMIT needed.

Plan B:  Suck it up and use separate calls to the API for each statement here:

```<code>BEGIN;
some SQL statement;
some SQL statement;
some SQL statement;
COMMIT;
</code>```

If the API has special calls for BEGIN and COMMIT, use them instead of performing the corresponding SQL; there may be something important hiding in the call.

In both cases you must check for errors at all steps.  Deadlocks can happen when you least expect them.

Body:
Is there a better way to use transactions with the mariasql library than adding BEGIN to the start of the query, and finalizing with either a commit or a rollback?

Currently, if I want to wrap a series of queries in a transaction I have to do something like this:

const MariaClient = require('mariasql');
let client = new MariaClient();

client.connect({
    host: "127.0.0.1",
    user: "user",
    password: "pass",
    db: "some_db",
    multiStatements: true
});

client.query('BEGIN; INSERT INTO some_table VALUES ("a0","b0"), ("a1","b1"), ("a2","b2");', function (err) {
    if (err) {
        client.query('ROLLBACK;');
    }
    client.query('COMMIT;');
});

This seems clunky and potentially error prone.  We are using the generic-pool to manage the mariadb client, so it seems like there could be some unintended consequences handling transactions this way.

Body:
Plan A:  If autocommit is set to 1, then each statement is its own transaction.  No BEGIN/COMMIT needed.

Plan B:  Suck it up and use separate calls to the API for each statement here:

BEGIN;
some SQL statement;
some SQL statement;
some SQL statement;
COMMIT;

If the API has special calls for BEGIN and COMMIT, use them instead of performing the corresponding SQL; there may be something important hiding in the call.

In both cases you must check for errors at all steps.  Deadlocks can happen when you least expect them.


问:
The best way to set the timeout on built-in HTTP request
What is the best way to setup a timeout on built-in http NewRequest? Currently, I'm using http.Client.Timeout which is cover the entire exchange, but is there something better for example context.WithDeadline or context.WithTimeout. If yes how is it working, how can I setup a context.WithDeadline solution for the http.NewRequest?

There is my current solution:

```<code>func (c *Client) post(resource string, data url.Values, timeout time.Duration) ([]byte, error) {
    url := c.getURL(resource)
    client := &http.Client{
        Timeout: timeout * time.Millisecond,
    }
    req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
    if err != nil {
        return nil, err
    }
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    return ioutil.ReadAll(resp.Body)
}
</code>```

答:
Get new context from context.WithDeadline. See documentation.
WithTimeout just returns WithDeadline(parent, time.Now().Add(timeout)).

```<code>package main

import (
    "context"
    "io"
    "log"
    "net/http"
    "os"
    "time"
)

func getContent(ctx context.Context) {
    req, err := http.NewRequest("GET", "http://example.com", nil)
    if err != nil {
        log.Fatal(err)
    }
    ctx, cancel := context.WithDeadline(ctx, time.Now().Add(3 * time.Second))
    defer cancel()

    req.WithContext(ctx)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    io.Copy(os.Stdout, resp.Body)
}

func main() {
    ctx := context.Background()
    getContent(ctx)
}
</code>```

If you want to make cancel trigger on main:

```<code>func main() {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)

    sc := make(chan os.Signal, 1)
    signal.Notify(sc, os.Interrupt)
    go func(){
        <-sc
        cancel()
    }()

    getContent(ctx)
}
</code>```

Body:
What is the best way to setup a timeout on built-in http NewRequest? Currently, I'm using http.Client.Timeout which is cover the entire exchange, but is there something better for example context.WithDeadline or context.WithTimeout. If yes how is it working, how can I setup a context.WithDeadline solution for the http.NewRequest?

There is my current solution:

func (c *Client) post(resource string, data url.Values, timeout time.Duration) ([]byte, error) {
    url := c.getURL(resource)
    client := &http.Client{
        Timeout: timeout * time.Millisecond,
    }
    req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
    if err != nil {
        return nil, err
    }
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    return ioutil.ReadAll(resp.Body)
}

Body:
Get new context from context.WithDeadline. See documentation.
WithTimeout just returns WithDeadline(parent, time.Now().Add(timeout)).

package main

import (
    "context"
    "io"
    "log"
    "net/http"
    "os"
    "time"
)

func getContent(ctx context.Context) {
    req, err := http.NewRequest("GET", "http://example.com", nil)
    if err != nil {
        log.Fatal(err)
    }
    ctx, cancel := context.WithDeadline(ctx, time.Now().Add(3 * time.Second))
    defer cancel()

    req.WithContext(ctx)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    io.Copy(os.Stdout, resp.Body)
}

func main() {
    ctx := context.Background()
    getContent(ctx)
}

If you want to make cancel trigger on main:

func main() {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)

    sc := make(chan os.Signal, 1)
    signal.Notify(sc, os.Interrupt)
    go func(){
        <-sc
        cancel()
    }()

    getContent(ctx)
}


问:
change resize icon of an element with resize style applied
How do you change resize icon of an element with resize style applied?

for example:

```<code>.resize{
  background-color:red;
  width:300px;
  height:220px;
  resize:horizontal;
  overflow: auto;
}
</code>```

https://codepen.io/anon/pen/WOyQVq

See those 2 black lines at the bottom right? How do you change that icon?

答:
I don't think it is possible to change that controller symbol. In your case, I can suggest this solution. Add background color red and it will disappear</p>

```<code>.resize::-webkit-resizer {
background-color: red;
}
</code>```

Body:
How do you change resize icon of an element with resize style applied?

for example:

.resize{
  background-color:red;
  width:300px;
  height:220px;
  resize:horizontal;
  overflow: auto;
}

https://codepen.io/anon/pen/WOyQVq

See those 2 black lines at the bottom right? How do you change that icon?

Body:
I don't think it is possible to change that controller symbol. In your case, I can suggest this solution. Add background color red and it will disappear

.resize::-webkit-resizer {
background-color: red;
}


问:
Check failed: error == cudaSuccess (77 vs. 0) an illegal memory access was encountered
I'm debugging some lengthy code which involves some cuda operations.
I' currently getting the above mentioned error during a call to cudaMemcpy(...,...,cudaMemcpyHostToDevice) but I'm not sure it is speficially related to that.

Here is a code snippet:

```<code>    int num_elements = 8294400; // --> I also tried it with "1" here which didn't work either!
    float *checkArray = new float[num_elements];
    float *checkArray_GPU;
    CUDA_CHECK(cudaMalloc(&checkArray_GPU, num_elements * sizeof(float)));
    CUDA_CHECK(cudaMemcpy(checkArray_GPU, checkArray, num_elements * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(checkArray, checkArray_GPU, num_elements * sizeof(float), cudaMemcpyDeviceToHost));
</code>```

where CUDA_CHECK is simply a macro for printing any cuda error (this was part of the existing code and works fine for all other cudaMemcpy oder cudaMalloc calls so it is not part of the problem). Strangely this code snippet executed separately in a toy *.cu example works fine.

So my assumption is that due to previous cuda operations in the program, there have been some errors which have not been reported that cause the bug in the code snippet above. Could that be?
Is there a way to check if there is some unreported error involving cuda?

My other estimate is that it might come from the specific graphic card I'm using. I have a Nvidia Titan X Pascal, Cuda 8.0 and cudnn v5.1. I also tried to compile my code using some special compiler flags like

```<code>-arch=sm_30 \
 -gencode=arch=compute_20,code=sm_20 \
 -gencode=arch=compute_30,code=sm_30 \
 -gencode=arch=compute_50,code=sm_50 \
 -gencode=arch=compute_52,code=sm_52 \
 -gencode=arch=compute_52,code=compute_52 \
 -gencode=arch=compute_60,code=sm_60 \
 -gencode=arch=compute_61,code=sm_61 \
 -gencode=arch=compute_62,code=sm_62 \
</code>```

but it didn't help so far. Here is my current simplified Makefile for completeness:

```<code>NVCC = nvcc
CUDA_INC = -I/usr/local/cuda/include
CUDA_LIB = -L/usr/local/cuda/lib64
TARGET = myProgramm
OPTS = -std=c++11
$(TARGET).so: $(TARGET).o
    $(NVCC) $(OPTS) -shared $(TARGET).o $(CUDA_LIB) -o $(TARGET).so
$(TARGET).o: $(TARGET).cu headers/some_header.hpp
    $(NVCC) $(OPTS) $(CUDA_INC) -Xcompiler -fPIC -c $(TARGET).cu
</code>```

Has anyone an idea how I could get to the bottom of this?

Edit:

cuda-memcheck was a good idea, so the error apparantly happens earlier during a call of Kernel_set_value:

```<code>========= Invalid __global__ write of size 4
=========     at 0x00000298 in void Kernel_set_value<float>(unsigned long, unsigned long, float*, float)
=========     by thread (480,0,0) in block (30,0,0)
=========     Address 0x0005cd00 is out of bounds
=========     Saved host backtrace up to driver entry point at kernel launch time
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 (cuLaunchKernel + 0x2c5) [0x209035]
[...]
=========     Host Frame:/media/.../myProgramm.so (_ZN5boost6python6detail6invokeIiPFvRKSsENS0_15arg_from_pythonIS4_EEEEP7_objectNS1_11invoke_tag_ILb1ELb0EEERKT_RT0_RT1_ + 0x2d) [0x3e5eb]
[...]
=========
========= Program hit cudaErrorLaunchFailure (error 4) due to "unspecified launch failure" on CUDA API call to cudaMemcpy.
=========     Saved host backtrace up to driver entry point at error
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 [0x2f4e33]
=========     Host Frame:/media/.../myProgramm.so [0x7489f]
F0703 16:23:54.840698 26207 myProgramm.cu:411] Check failed: error == cudaSuccess (4 vs. 0)  unspecified launch failure
[...]
=========     Host Frame:python (Py_Main + 0xb5e) [0x66d92]
=========     Host Frame:/lib/x86_64-linux-gnu/libc.so.6 (__libc_start_main + 0xf5) [0x21f45]
=========     Host Frame:python [0x177c2e]
=========
*** Check failure stack trace: ***
========= Error: process didn't terminate successfully
========= Internal error (20)
========= No CUDA-MEMCHECK results found
</code>```

but also the function Kernel_set_value works fine in a toy example. Is there anything special to consider when using Kernel_set_value. This is it's source code and it's respective helper functions.

```<code>#define CUDA_NUM_THREADS 512
#define MAX_NUM_BLOCKS 2880

inline int CUDA_GET_BLOCKS(const size_t N) {
  return min(MAX_NUM_BLOCKS, int((N + size_t(CUDA_NUM_THREADS) - 1) / CUDA_NUM_THREADS));
}

inline size_t CUDA_GET_LOOPS(const size_t N) {
  size_t total_threads = CUDA_GET_BLOCKS(N)*CUDA_NUM_THREADS;
  return (N + total_threads -1)/ total_threads;
}

template <typename Dtype>
__global__ void Kernel_set_value(size_t CUDA_NUM_LOOPS, size_t N, Dtype* GPUdst, Dtype value){
  const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
  if (idxBase >= N) return;
  for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
    GPUdst[idx] = value;
  }
}
</code>```

答: So the final solution was to compile the code without any -gencode=arch=compute_XX,code=sm_XX-style flags. Took me forever to find this out. The actual error codes were very missleading (error == cudaSuccess (77 vs. 0) an illegal memory access, (4 vs. 0) unspecified launch failure or (8 vs. 0) invalid device function

Body:
I'm debugging some lengthy code which involves some cuda operations.
I' currently getting the above mentioned error during a call to cudaMemcpy(...,...,cudaMemcpyHostToDevice) but I'm not sure it is speficially related to that.

Here is a code snippet:

    int num_elements = 8294400; // --> I also tried it with "1" here which didn't work either!
    float *checkArray = new float[num_elements];
    float *checkArray_GPU;
    CUDA_CHECK(cudaMalloc(&checkArray_GPU, num_elements * sizeof(float)));
    CUDA_CHECK(cudaMemcpy(checkArray_GPU, checkArray, num_elements * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(checkArray, checkArray_GPU, num_elements * sizeof(float), cudaMemcpyDeviceToHost));

where CUDA_CHECK is simply a macro for printing any cuda error (this was part of the existing code and works fine for all other cudaMemcpy oder cudaMalloc calls so it is not part of the problem). Strangely this code snippet executed separately in a toy *.cu example works fine.

So my assumption is that due to previous cuda operations in the program, there have been some errors which have not been reported that cause the bug in the code snippet above. Could that be?
Is there a way to check if there is some unreported error involving cuda?

My other estimate is that it might come from the specific graphic card I'm using. I have a Nvidia Titan X Pascal, Cuda 8.0 and cudnn v5.1. I also tried to compile my code using some special compiler flags like

-arch=sm_30 \
 -gencode=arch=compute_20,code=sm_20 \
 -gencode=arch=compute_30,code=sm_30 \
 -gencode=arch=compute_50,code=sm_50 \
 -gencode=arch=compute_52,code=sm_52 \
 -gencode=arch=compute_52,code=compute_52 \
 -gencode=arch=compute_60,code=sm_60 \
 -gencode=arch=compute_61,code=sm_61 \
 -gencode=arch=compute_62,code=sm_62 \

but it didn't help so far. Here is my current simplified Makefile for completeness:

NVCC = nvcc
CUDA_INC = -I/usr/local/cuda/include
CUDA_LIB = -L/usr/local/cuda/lib64
TARGET = myProgramm
OPTS = -std=c++11
$(TARGET).so: $(TARGET).o
    $(NVCC) $(OPTS) -shared $(TARGET).o $(CUDA_LIB) -o $(TARGET).so
$(TARGET).o: $(TARGET).cu headers/some_header.hpp
    $(NVCC) $(OPTS) $(CUDA_INC) -Xcompiler -fPIC -c $(TARGET).cu

Has anyone an idea how I could get to the bottom of this?

Edit:

cuda-memcheck was a good idea, so the error apparantly happens earlier during a call of Kernel_set_value:

========= Invalid __global__ write of size 4
=========     at 0x00000298 in void Kernel_set_value<float>(unsigned long, unsigned long, float*, float)
=========     by thread (480,0,0) in block (30,0,0)
=========     Address 0x0005cd00 is out of bounds
=========     Saved host backtrace up to driver entry point at kernel launch time
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 (cuLaunchKernel + 0x2c5) [0x209035]
[...]
=========     Host Frame:/media/.../myProgramm.so (_ZN5boost6python6detail6invokeIiPFvRKSsENS0_15arg_from_pythonIS4_EEEEP7_objectNS1_11invoke_tag_ILb1ELb0EEERKT_RT0_RT1_ + 0x2d) [0x3e5eb]
[...]
=========
========= Program hit cudaErrorLaunchFailure (error 4) due to "unspecified launch failure" on CUDA API call to cudaMemcpy.
=========     Saved host backtrace up to driver entry point at error
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 [0x2f4e33]
=========     Host Frame:/media/.../myProgramm.so [0x7489f]
F0703 16:23:54.840698 26207 myProgramm.cu:411] Check failed: error == cudaSuccess (4 vs. 0)  unspecified launch failure
[...]
=========     Host Frame:python (Py_Main + 0xb5e) [0x66d92]
=========     Host Frame:/lib/x86_64-linux-gnu/libc.so.6 (__libc_start_main + 0xf5) [0x21f45]
=========     Host Frame:python [0x177c2e]
=========
*** Check failure stack trace: ***
========= Error: process didn't terminate successfully
========= Internal error (20)
========= No CUDA-MEMCHECK results found

but also the function Kernel_set_value works fine in a toy example. Is there anything special to consider when using Kernel_set_value. This is it's source code and it's respective helper functions.

#define CUDA_NUM_THREADS 512
#define MAX_NUM_BLOCKS 2880

inline int CUDA_GET_BLOCKS(const size_t N) {
  return min(MAX_NUM_BLOCKS, int((N + size_t(CUDA_NUM_THREADS) - 1) / CUDA_NUM_THREADS));
}

inline size_t CUDA_GET_LOOPS(const size_t N) {
  size_t total_threads = CUDA_GET_BLOCKS(N)*CUDA_NUM_THREADS;
  return (N + total_threads -1)/ total_threads;
}

template <typename Dtype>
__global__ void Kernel_set_value(size_t CUDA_NUM_LOOPS, size_t N, Dtype* GPUdst, Dtype value){
  const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
  if (idxBase >= N) return;
  for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
    GPUdst[idx] = value;
  }
}


问:
Availability of BridgeConnect in Magento
One of our clients is thinking of buying an Enterprise Edition, due to his requirement of using the Exact CRM Services with Magento. But today, to my utter astonishment, I’m not finding any inclusion of ”BridgeConnect” module in either the ”Enterprise” or the ”Professional” Editions.

Can anybody from the SO please highlight, whether Magento still provides this ”BridgeConnect” module with the ”Enterprise” or the ”Professional” Editions?

If this module is not being provided, then when will Magento provide this module?
Or, is Magento planning to provide any better solution module, instead of the ”BridgeConnect” module?

This is very much urgent for us, and will be very very grateful for some quick responses.
Any help is really appreciated.

答: I believe it's actually in your support section near the download for EE itself.</p>


问:
Modify object property from variable
I'm trying to do something like this:

```<code>var obj={o:"a string"};
var o=obj.o
console.log(o)
o='modified'
console.log(o)
console.log(obj.o)
</code>```

The result is:

```<code>a string
modified
a string
</code>```

But I expect it to be:

```<code>a string
modified
modified
</code>```

I tried destructuring too without success: it seems that the property and the variable are not linked.

Is there a way to link o to obj.o ? I don't want to use obj.o to modify obj property, but o instead.

Thank you in advance for your help.

答:
No, you can't "link" variables and object properties.

If the o property was a reference to an object, it would work:

```<code>var obj = { o: { foo: 'bar' } };
var o = obj.o;
o.foo = 'baz';
console.log(obj.o.foo); // 'baz'
</code>```

Primitives however are copied, you can't get a reference to a string. When you read the value of the property o of the obj, the value is copied, because it's a string, and you get a new string which is not related to the old string in the object.

When you assign the new string to the variable, the old string value is lost (at least for the variable o).

Title: Modify object property from variable

Body:
I'm trying to do something like this:

var obj={o:"a string"};
var o=obj.o
console.log(o)
o='modified'
console.log(o)
console.log(obj.o)

The result is:

a string
modified
a string

But I expect it to be:

a string
modified
modified

I tried destructuring too without success: it seems that the property and the variable are not linked.

Is there a way to link o to obj.o ? I don't want to use obj.o to modify obj property, but o instead.

Thank you in advance for your help.

Body:
No, you can't "link" variables and object properties.

If the o property was a reference to an object, it would work:

var obj = { o: { foo: 'bar' } };
var o = obj.o;
o.foo = 'baz';
console.log(obj.o.foo); // 'baz'

Primitives however are copied, you can't get a reference to a string. When you read the value of the property o of the obj, the value is copied, because it's a string, and you get a new string which is not related to the old string in the object.

When you assign the new string to the variable, the old string value is lost (at least for the variable o).


问:
HTML5 Canvas lags
I recently added a canvas element,random dots on sphere,in my page.It works great on PC but on mobile phones and tablets rendering is very slow.
How can I speed up the sphere and reduce lags?
Any help would be much appreciated.GitHub example</p>

答:
There is so much room for improvements.

In the render loop you have

```<code>    for (var p of points) {
        p = rotation.multiplyVector(p);
        ctx.beginPath();
        ctx.arc(p.x + c.width / 2, p.y + c.height / 2, 2, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.fill();
    }
</code>```

The beginPath is not needed if you are rendering the same style over and over

```<code>    ctx.beginPath();
    for (var p of points) {
        p = rotation.multiplyVector(p);
        const x = p.x + c.width / 2;
        const y = p.y + c.height / 2;
        ctx.moveTo(x + 2, y)
        ctx.arc(x, y, 2, 0, 2 * Math.PI);
    }
    ctx.fill();
</code>```

Then the matrix vector multiply has needless vetting and needless memory assignment and object instantiations

You had

```<code>Matrix3.prototype.multiplyVector = function (vec) {
    if (vec instanceof Vector3) {
        var x = this.data[0 + 0 * 3] * vec.x + this.data[0 + 1 * 3] * vec.y + this.data[0 + 2 * 3] * vec.z;
        var y = this.data[1 + 0 * 3] * vec.x + this.data[1 + 1 * 3] * vec.y + this.data[1 + 2 * 3] * vec.z;
        var z = this.data[2 + 0 * 3] * vec.x + this.data[2 + 1 * 3] * vec.y + this.data[2 + 2 * 3] * vec.z;

        return new Vector3(x, y, z);
    }
}
</code>```

Will this ever not happen if (vec instanceof Vector3) { ??? not in your code so why waste the CPU time doing it.

Then this.data[2 + 0 * 3] The optimiser may get this for you, but mobiles do not optimise as well as desktops and I am not sure if this will be picked up on. Also some browsers are slower when using indirect references  this.data[?] is slower than data[?]

And creating a new vector with for each circle to immediately discard it is not at all memory friendly. You only need one object so pass it to the function to set.

Improved

```<code>Matrix3.prototype.multiplyVector = function (vec, retVec = new Vector3(0,0,0)) {
    const d = this.data;
    retVec.x = d[0] * vec.x + d[3] * vec.y + d[6] * vec.z;
    retVec.y = d[1] * vec.x + d[4] * vec.y + d[7] * vec.z;
    retVec.z = d[2] * vec.x + d[5] * vec.y + d[8] * vec.z;
    return retVec;
};
</code>```

Then in the loop

```<code>const rp = new Vector3(0,0,0);
ctx.beginPath();
for (var p of points) {
    rotation.multiplyVector(p,rp);
    const x = rp.x + c.width / 2;
    const y = rp.y + c.height / 2;
    ctx.moveTo(x + 2, y)
    ctx.arc(x, y, 2, 0, 2 * Math.PI);
}
ctx.fill();
</code>```

Both the Vector3 and Matrix3 objects are very memory wasteful which means CPU cycles you have no control over being used just to assign and delete when you should be reusing memory as shown above.

You have the Matrix rotate function to build the rotation that creates a new matrix to create a rotation matrix which then needs a new matrix to multiply. You create 6 full matrix objects just to get one matrix.

The rotate function is called with 2 of x,y,z as 0 meaning that many of the multiplications and additions are just getting zero or you end up adding omc + cos which equals 1 or you multiply by 1 making no change.

You have

```<code>Matrix3.rotate = function (angle, x, y, z) {
    var result = new Matrix3();
    result.setIdentity();

    var cos = Math.cos(angle);
    var sin = Math.sin(angle);
    var omc = 1 - cos;

    result.data[0 + 0 * 3] = x * omc + cos;
    result.data[1 + 0 * 3] = y * x * omc + z * sin;
    result.data[2 + 0 * 3] = x * z * omc - y * sin;

    result.data[0 + 1 * 3] = x * y * omc - z * sin;
    result.data[1 + 1 * 3] = y * omc + cos;
    result.data[2 + 1 * 3] = y * z * omc + x * sin;

    result.data[0 + 2 * 3] = x * z * omc + y * sin;
    result.data[1 + 2 * 3] = y * z * omc - x * sin;
    result.data[2 + 2 * 3] = z * omc + cos;

    return result;
}
</code>```

Create a rotation matrix by directly multiplying a matrix, you will need one for each axis.

```<code>Matrix3.prototype.rotateX = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle));
    const ns = -s;
    r[0] = d[0]
    r[1] = d[1] * c + d[2] * ns;
    r[2] = d[1] * s + d[2] * c;
    r[3] = d[3];
    r[4] = d[4] * c + d[5] * ns;
    r[5] = d[4] * s + d[5] * c;
    r[6] = d[6];
    r[7] = d[7] * c + d[8] * ns;
    r[8] = d[7] * s + d[8] * c;
    return result;
},
</code>```

Do same for rotateY,rotateZ (each is different than above)

Instance matrix directly setting the identity rather than needing a second call.

```<code>function Matrix3() { this.data = [1,0,0,0,1,0,0,0,1] }
</code>```

Set identity with

```<code>Matrix3.prototype.setIdentity = function () {
    const d = this.data;
    d.fill(0);
    d[8] = d[4] = d[0] = 1;
}
</code>```

Then in your loop function have access to two matrix objects.

```<code>const mat1 = new Matrix3();
const mat2 = new Matrix3();
const rp = new Vector3(0,0,0);
const MPI2 = 2 * Math.PI;
function loop(){
    mat1.setIdentity();
    mat1.rotateX(angle.x,mat2);
    mat2.rotateY(angle.y,mat1);
    mat1.rotateZ(angle.z,mat2);
    // your text rendering in here
    const cw = c.width / 2;
    const ch = c.height / 2;
    ctx.beginPath();
    for (var p of points) {
        mat2.multiplyVector(p,rp);
        const x = rp.x + cw;
        const y = rp.y + ch;
        ctx.moveTo(x + 2, y)
        ctx.arc(x, y, 2, 0, MPI2);
    }
    ctx.fill();
}
</code>```

That will give you a little extra speed. Any other improvements will be browser / device specific.

UPDATE as requested in the comments the following snippet contains the shortened rotation matrix multiplication of rotation around the X,Y, andZ axis

// How I find the optimum matrix multiplication via
// eleminating a[?] * 0 = 0
// reducing  a[?] * 1 = a[?]
//
// The following are the rotations for X,Y,Z as matrix
//-------------------
// rotate X
//  1       0     0
//  0  cos(r) sin(r)
//  0 -sin(r) cos(r)
//-------------------
// rotate Y
//  cos(r) 0 sin(r)
//  0      1      0
// -sin(r) 0 cos(r)
//-------------------
// rotate Z
//  cos(r) sin(r) 0
// -sin(r) cos(r) 0
//       0      0 1
// The matrix indexes
// [0][1][2]
// [3][4][5]
// [6][7][8]
// Using the indexs and multiply is c = a * b
// c[0] = a[0] * b[0] + a[1] * b[3] + a[2] * b[6]
// c[1] = a[0] * b[1] + a[1] * b[4] + a[2] * b[7]
// c[2] = a[0] * b[2] + a[1] * b[5] + a[2] * b[8]
// c[3] = a[3] * b[0] + a[4] * b[3] + a[5] * b[6]
// c[4] = a[3] * b[1] + a[4] * b[4] + a[5] * b[7]
// c[5] = a[3] * b[2] + a[4] * b[5] + a[5] * b[8]
// c[6] = a[6] * b[0] + a[7] * b[3] + a[8] * b[6]
// c[7] = a[6] * b[1] + a[7] * b[4] + a[8] * b[7]
// c[8] = a[6] * b[2] + a[7] * b[5] + a[8] * b[8]
// Then use the rotations matrix to find the zeros and ones
// EG rotate X b[1],b[2],b[3],b[6] are zero and b[0] is one
// c[0] = a[0] * 1    + a[1] * 0    + a[2] * 0
// c[1] = a[0] * 0    + a[1] * b[4] + a[2] * b[7]
// c[2] = a[0] * 0    + a[1] * b[5] + a[2] * b[8]
// c[3] = a[3] * 1    + a[4] * 0    + a[5] * 0
// c[4] = a[3] * 0    + a[4] * b[4] + a[5] * b[7]
// c[5] = a[3] * 0    + a[4] * b[5] + a[5] * b[8]
// c[6] = a[6] * 1    + a[7] * 0    + a[8] * 0
// c[7] = a[6] * 0    + a[7] * b[4] + a[8] * b[7]
// c[8] = a[6] * 0    + a[7] * b[5] + a[8] * b[8]
// then eliminate all the zero terms a[?] * 0 == 0 and
// remove the 1 from 1 * a[?] = a[?]
// c[0] = a[0]
// c[1] = a[1] * b[4] + a[2] * b[7]
// c[2] = a[1] * b[5] + a[2] * b[8]
// c[3] = a[3]
// c[4] = a[4] * b[4] + a[5] * b[7]
// c[5] = a[4] * b[5] + a[5] * b[8]
// c[6] = a[6]
// c[7] = a[7] * b[4] + a[8] * b[7]
// c[8] = a[7] * b[5] + a[8] * b[8]
// And you are left with the minimum calculations required to apply a particular rotation Or any other transform.

Matrix3.prototype.rotateX = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const ns = -s;
    r[0] = d[0];
    r[1] = d[1] * c + d[2] * ns;
    r[2] = d[1] * s + d[2] * c;
    r[3] = d[3];
    r[4] = d[4] * c + d[5] * ns;
    r[5] = d[4] * s + d[5] * c;
    r[6] = d[6];
    r[7] = d[7] * c + d[8] * ns;
    r[8] = d[7] * s + d[8] * c;
    return result;
}
Matrix3.prototype.rotateY = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const ns = -s;
    r[0] = d[0] * c + d[2] * ns;
    r[1] = d[1];
    r[2] = d[0] * s + d[2] * c;

    r[3] = d[3] * c + d[5] * ns;
    r[4] = d[4];
    r[5] = d[3] * s + d[5] * c;

    r[6] = d[6] * c + d[8] * ns;
    r[7] = d[7];
    r[8] = d[6] * s + d[8] * c;
    return result;
}
Matrix3.prototype.rotateZ = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const ns = -s;
    r[0] = d[0] * c + d[1] * ns;
    r[1] = d[0] * s + d[1] * c;
    r[2] = d[2];

    r[3] = d[3] * c + d[4] * ns;
    r[4] = d[3] * s + d[4] * c;
    r[5] = d[5];

    r[6] = d[6] * c + d[7] * ns;
    r[7] = d[6] * s + d[7] * c;
    r[8] = d[8];
    return result;
}```

Title: HTML5 Canvas lags

Body:
There is so much room for improvements.

In the render loop you have

    for (var p of points) {
        p = rotation.multiplyVector(p);
        ctx.beginPath();
        ctx.arc(p.x + c.width / 2, p.y + c.height / 2, 2, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.fill();
    }

The beginPath is not needed if you are rendering the same style over and over

    ctx.beginPath();
    for (var p of points) {
        p = rotation.multiplyVector(p);
        const x = p.x + c.width / 2;
        const y = p.y + c.height / 2;
        ctx.moveTo(x + 2, y)
        ctx.arc(x, y, 2, 0, 2 * Math.PI);
    }
    ctx.fill();

Then the matrix vector multiply has needless vetting and needless memory assignment and object instantiations

You had

Matrix3.prototype.multiplyVector = function (vec) {
    if (vec instanceof Vector3) {
        var x = this.data[0 + 0 * 3] * vec.x + this.data[0 + 1 * 3] * vec.y + this.data[0 + 2 * 3] * vec.z;
        var y = this.data[1 + 0 * 3] * vec.x + this.data[1 + 1 * 3] * vec.y + this.data[1 + 2 * 3] * vec.z;
        var z = this.data[2 + 0 * 3] * vec.x + this.data[2 + 1 * 3] * vec.y + this.data[2 + 2 * 3] * vec.z;

        return new Vector3(x, y, z);
    }
}

Will this ever not happen if (vec instanceof Vector3) { ??? not in your code so why waste the CPU time doing it.

Then this.data[2 + 0 * 3] The optimiser may get this for you, but mobiles do not optimise as well as desktops and I am not sure if this will be picked up on. Also some browsers are slower when using indirect references  this.data[?] is slower than data[?]

And creating a new vector with for each circle to immediately discard it is not at all memory friendly. You only need one object so pass it to the function to set.

Improved

Matrix3.prototype.multiplyVector = function (vec, retVec = new Vector3(0,0,0)) {
    const d = this.data;
    retVec.x = d[0] * vec.x + d[3] * vec.y + d[6] * vec.z;
    retVec.y = d[1] * vec.x + d[4] * vec.y + d[7] * vec.z;
    retVec.z = d[2] * vec.x + d[5] * vec.y + d[8] * vec.z;
    return retVec;
};

Then in the loop

const rp = new Vector3(0,0,0);
ctx.beginPath();
for (var p of points) {
    rotation.multiplyVector(p,rp);
    const x = rp.x + c.width / 2;
    const y = rp.y + c.height / 2;
    ctx.moveTo(x + 2, y)
    ctx.arc(x, y, 2, 0, 2 * Math.PI);
}
ctx.fill();

Both the Vector3 and Matrix3 objects are very memory wasteful which means CPU cycles you have no control over being used just to assign and delete when you should be reusing memory as shown above.

You have the Matrix rotate function to build the rotation that creates a new matrix to create a rotation matrix which then needs a new matrix to multiply. You create 6 full matrix objects just to get one matrix.

The rotate function is called with 2 of x,y,z as 0 meaning that many of the multiplications and additions are just getting zero or you end up adding omc + cos which equals 1 or you multiply by 1 making no change.

You have

Matrix3.rotate = function (angle, x, y, z) {
    var result = new Matrix3();
    result.setIdentity();

    var cos = Math.cos(angle);
    var sin = Math.sin(angle);
    var omc = 1 - cos;

    result.data[0 + 0 * 3] = x * omc + cos;
    result.data[1 + 0 * 3] = y * x * omc + z * sin;
    result.data[2 + 0 * 3] = x * z * omc - y * sin;

    result.data[0 + 1 * 3] = x * y * omc - z * sin;
    result.data[1 + 1 * 3] = y * omc + cos;
    result.data[2 + 1 * 3] = y * z * omc + x * sin;

    result.data[0 + 2 * 3] = x * z * omc + y * sin;
    result.data[1 + 2 * 3] = y * z * omc - x * sin;
    result.data[2 + 2 * 3] = z * omc + cos;

    return result;
}

Create a rotation matrix by directly multiplying a matrix, you will need one for each axis.

Matrix3.prototype.rotateX = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle));
    const ns = -s;
    r[0] = d[0]
    r[1] = d[1] * c + d[2] * ns;
    r[2] = d[1] * s + d[2] * c;
    r[3] = d[3];
    r[4] = d[4] * c + d[5] * ns;
    r[5] = d[4] * s + d[5] * c;
    r[6] = d[6];
    r[7] = d[7] * c + d[8] * ns;
    r[8] = d[7] * s + d[8] * c;
    return result;
},

Do same for rotateY,rotateZ (each is different than above)

Instance matrix directly setting the identity rather than needing a second call.

function Matrix3() { this.data = [1,0,0,0,1,0,0,0,1] }

Set identity with

Matrix3.prototype.setIdentity = function () {
    const d = this.data;
    d.fill(0);
    d[8] = d[4] = d[0] = 1;
}

Then in your loop function have access to two matrix objects.

const mat1 = new Matrix3();
const mat2 = new Matrix3();
const rp = new Vector3(0,0,0);
const MPI2 = 2 * Math.PI;
function loop(){
    mat1.setIdentity();
    mat1.rotateX(angle.x,mat2);
    mat2.rotateY(angle.y,mat1);
    mat1.rotateZ(angle.z,mat2);
    // your text rendering in here
    const cw = c.width / 2;
    const ch = c.height / 2;
    ctx.beginPath();
    for (var p of points) {
        mat2.multiplyVector(p,rp);
        const x = rp.x + cw;
        const y = rp.y + ch;
        ctx.moveTo(x + 2, y)
        ctx.arc(x, y, 2, 0, MPI2);
    }
    ctx.fill();
}

That will give you a little extra speed. Any other improvements will be browser / device specific.

UPDATE as requested in the comments the following snippet contains the shortened rotation matrix multiplication of rotation around the X,Y, andZ axis

// How I find the optimum matrix multiplication via
// eleminating a[?] * 0 = 0
// reducing  a[?] * 1 = a[?]
//
// The following are the rotations for X,Y,Z as matrix
//-------------------
// rotate X
//  1       0     0
//  0  cos(r) sin(r)
//  0 -sin(r) cos(r)
//-------------------
// rotate Y
//  cos(r) 0 sin(r)
//  0      1      0
// -sin(r) 0 cos(r)
//-------------------
// rotate Z
//  cos(r) sin(r) 0
// -sin(r) cos(r) 0
//       0      0 1
// The matrix indexes
// [0][1][2]
// [3][4][5]
// [6][7][8]
// Using the indexs and multiply is c = a * b
// c[0] = a[0] * b[0] + a[1] * b[3] + a[2] * b[6]
// c[1] = a[0] * b[1] + a[1] * b[4] + a[2] * b[7]
// c[2] = a[0] * b[2] + a[1] * b[5] + a[2] * b[8]
// c[3] = a[3] * b[0] + a[4] * b[3] + a[5] * b[6]
// c[4] = a[3] * b[1] + a[4] * b[4] + a[5] * b[7]
// c[5] = a[3] * b[2] + a[4] * b[5] + a[5] * b[8]
// c[6] = a[6] * b[0] + a[7] * b[3] + a[8] * b[6]
// c[7] = a[6] * b[1] + a[7] * b[4] + a[8] * b[7]
// c[8] = a[6] * b[2] + a[7] * b[5] + a[8] * b[8]
// Then use the rotations matrix to find the zeros and ones
// EG rotate X b[1],b[2],b[3],b[6] are zero and b[0] is one
// c[0] = a[0] * 1    + a[1] * 0    + a[2] * 0
// c[1] = a[0] * 0    + a[1] * b[4] + a[2] * b[7]
// c[2] = a[0] * 0    + a[1] * b[5] + a[2] * b[8]
// c[3] = a[3] * 1    + a[4] * 0    + a[5] * 0
// c[4] = a[3] * 0    + a[4] * b[4] + a[5] * b[7]
// c[5] = a[3] * 0    + a[4] * b[5] + a[5] * b[8]
// c[6] = a[6] * 1    + a[7] * 0    + a[8] * 0
// c[7] = a[6] * 0    + a[7] * b[4] + a[8] * b[7]
// c[8] = a[6] * 0    + a[7] * b[5] + a[8] * b[8]
// then eliminate all the zero terms a[?] * 0 == 0 and
// remove the 1 from 1 * a[?] = a[?]
// c[0] = a[0]
// c[1] = a[1] * b[4] + a[2] * b[7]
// c[2] = a[1] * b[5] + a[2] * b[8]
// c[3] = a[3]
// c[4] = a[4] * b[4] + a[5] * b[7]
// c[5] = a[4] * b[5] + a[5] * b[8]
// c[6] = a[6]
// c[7] = a[7] * b[4] + a[8] * b[7]
// c[8] = a[7] * b[5] + a[8] * b[8]
// And you are left with the minimum calculations required to apply a particular rotation Or any other transform.

Matrix3.prototype.rotateX = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const ns = -s;
    r[0] = d[0];
    r[1] = d[1] * c + d[2] * ns;
    r[2] = d[1] * s + d[2] * c;
    r[3] = d[3];
    r[4] = d[4] * c + d[5] * ns;
    r[5] = d[4] * s + d[5] * c;
    r[6] = d[6];
    r[7] = d[7] * c + d[8] * ns;
    r[8] = d[7] * s + d[8] * c;
    return result;
}
Matrix3.prototype.rotateY = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const ns = -s;
    r[0] = d[0] * c + d[2] * ns;
    r[1] = d[1];
    r[2] = d[0] * s + d[2] * c;

    r[3] = d[3] * c + d[5] * ns;
    r[4] = d[4];
    r[5] = d[3] * s + d[5] * c;

    r[6] = d[6] * c + d[8] * ns;
    r[7] = d[7];
    r[8] = d[6] * s + d[8] * c;
    return result;
}
Matrix3.prototype.rotateZ = function(angle, result = new Matrix3()) {
    const r = result.data;
    const d = this.data;
    const c = Math.cos(angle);
    const s = Math.sin(angle);
    const ns = -s;
    r[0] = d[0] * c + d[1] * ns;
    r[1] = d[0] * s + d[1] * c;
    r[2] = d[2];

    r[3] = d[3] * c + d[4] * ns;
    r[4] = d[3] * s + d[4] * c;
    r[5] = d[5];

    r[6] = d[6] * c + d[7] * ns;
    r[7] = d[6] * s + d[7] * c;
    r[8] = d[8];
    return result;
}


问:
Azure function, flexible test and production queue names
How can I design my Azure Function hosting for flexible test/production queue isolation?

I am planning to write 6 precompiled Azure Functions in C# packaged as single DLL and have yet to to decide if I will use WebJobSdk function annotation or multiple .json config files. My 6 Azure functions will only have input bindings and all will be triggered via storage queues.

I dislike the idea of hardcoding queue names in source code as method attribute strings but I understand that INameResolver provides for naming indirection.

Is this the standard solution for test/production storage queue binding isolation or can some other form of higher level Azure environment declaration achieve the same with zero code?

答:
The approach you've mentioned, where you rely on the INameResolver functionality to set those queue names based on the environment would definitely work and give you a more flexibility than if you had those queue names defined as literals in your pre-compiled assemblies. This is particularly important if the teams maintaining the environment and writing the code are different.

It's worth noting that, although the approach above alone would work, our recommendation, for better isolation, and to avoid other potential issues, would be to use completely different storage accounts when developing/testing and when running your production workloads.
You can still leverage the INameResolver behavior for added flexibility in this case.


问:
ggplot2: Create second y-axis on the right side for one variable
I have a dataframe with 3 different variables for the same time horizon. The first two variables have the same scaling (stock indice values) and can be illustrated with the y-axis. The third variable is an interest rate and ranges only from 0 to 7%, so that I focused on creating an additional y-axis on the right hand side of the plot to illustrate it. But after now 2 days trying and failing, I look for advice in your community. I first tried to separate my dataset and used to par(new=T) "overwrite" my first plot, but that led to more difficulties than before. I already found cases where people looked for a similar problem, but their questions were to special to replicate with my few skills.

```<code>library(reshape2)
library (scales)
library (ggplot2)

df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates")

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+
      scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
      labs(x="Date", y="MSCI Value" )+
      theme_classic()+
      theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
      scale_color_manual(values=c("grey0", "orangered2", "royalblue2"))
</code>```

Here some data (the first 30 observations) to replicate my plot and to illustrate what I mean.

```<code>Dates <- structure(c(8766, 8797, 8825, 8856, 8886, 8917, 8947, 8978, 9009,
9039, 9070, 9100, 9131, 9162, 9190, 9221, 9251, 9282, 9312, 9343,
9374, 9404, 9435, 9465, 9496, 9527, 9556, 9587, 9617, 9648), class = "Date")

Variables <- structure(c(1405.713, 1498.661, 1479.508, 1415.972, 1459.993,
1464.001, 1460.193, 1488.212, 1533.288, 1493.268, 1536.017, 1469.67,
1484.177, 1462.17, 1483.771, 1555.59, 1610.111, 1624.192, 1624.007,
1705.582, 1667.891, 1716.796, 1690.085, 1749.089, 1800.553, 1833.446,
1844.949, 1875.988, 1920.44, 1922.445, 3.05, 3.25, 3.34, 3.56,
4.01, 4.25, 4.26, 4.47, 4.73, 4.76, 5.29, 5.45, 5.53, 5.92, 5.98,
6.05, 6.01, 6, 5.85, 5.74, 5.8, 5.76, 5.8, 5.6, 5.56, 5.22, 5.31,
5.22, 5.24, 5.27, 1226.99191666667, 1240.457375, 1253.96166666667,
1267.07825, 1281.38133333333, 1293.99208333333, 1308.05641666667,
1323.16016666667, 1338.992625, 1353.58925, 1371.2485, 1385.3055,
1399.57704166667, 1412.76375, 1425.710875, 1438.80775, 1451.77004166667,
1464.062625, 1476.80325, 1491.8025, 1502.652, 1516.61345833333,
1527.86608333333, 1544.914875, 1561.36654166667, 1575.31591666667,
1590.542625, 1609.70995833333, 1628.89525, 1647.99708333333), .Dim = c(30L,
3L), .Dimnames = list(NULL, c("MSCI.WORLD", "Funds.Target.Rate",
"Mean.Rolling")))
</code>```

The variable "Funds.Target.Rate" should be presented in a more convenient way. Is it possible to create a second y-axis on the right side of the plot that refers to the interest rates of this variable? Thank you for your time and help.

答:
As far as I know, this is not possible in ggplot2, for good reasons. see this discussion. The only thing possible is to add a second axis which is a re-calculation of the first axis, e.g. Celsius -> Fahrenheit or local differences:

```<code>ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  scale_y_continuous(
    "mpg (US)",
    sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)")
  )
</code>```

Having said that, you can use that hack for your purposes. First scale the interest rate, so that all variables have the same dimension (1000 - 2000 in your case) - I multiply Interest.Rate by 400. Then add the second axis and make sure the annotations show the unscaled (i.e. divided) values (* 300 and / 300 in your case):

```<code>Variables[, 2] <- Variables[, 2] * 300
df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates")

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+
    scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
    labs(x="Date", y="MSCI Value" )+
    theme_classic()+
    theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
    scale_color_manual(values=c("grey0", "orangered2", "royalblue2")) +

    # NEW CODE:
    scale_y_continuous("MSCI Value", sec.axis = sec_axis(~ . /300, name = "Interest Rate")
)
</code>```

Body:
I have a dataframe with 3 different variables for the same time horizon. The first two variables have the same scaling (stock indice values) and can be illustrated with the y-axis. The third variable is an interest rate and ranges only from 0 to 7%, so that I focused on creating an additional y-axis on the right hand side of the plot to illustrate it. But after now 2 days trying and failing, I look for advice in your community. I first tried to separate my dataset and used to par(new=T) "overwrite" my first plot, but that led to more difficulties than before. I already found cases where people looked for a similar problem, but their questions were to special to replicate with my few skills.

library(reshape2)
library (scales)
library (ggplot2)

df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates")

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+
      scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
      labs(x="Date", y="MSCI Value" )+
      theme_classic()+
      theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
      scale_color_manual(values=c("grey0", "orangered2", "royalblue2"))

Here some data (the first 30 observations) to replicate my plot and to illustrate what I mean.

Dates <- structure(c(8766, 8797, 8825, 8856, 8886, 8917, 8947, 8978, 9009,
9039, 9070, 9100, 9131, 9162, 9190, 9221, 9251, 9282, 9312, 9343,
9374, 9404, 9435, 9465, 9496, 9527, 9556, 9587, 9617, 9648), class = "Date")

Variables <- structure(c(1405.713, 1498.661, 1479.508, 1415.972, 1459.993,
1464.001, 1460.193, 1488.212, 1533.288, 1493.268, 1536.017, 1469.67,
1484.177, 1462.17, 1483.771, 1555.59, 1610.111, 1624.192, 1624.007,
1705.582, 1667.891, 1716.796, 1690.085, 1749.089, 1800.553, 1833.446,
1844.949, 1875.988, 1920.44, 1922.445, 3.05, 3.25, 3.34, 3.56,
4.01, 4.25, 4.26, 4.47, 4.73, 4.76, 5.29, 5.45, 5.53, 5.92, 5.98,
6.05, 6.01, 6, 5.85, 5.74, 5.8, 5.76, 5.8, 5.6, 5.56, 5.22, 5.31,
5.22, 5.24, 5.27, 1226.99191666667, 1240.457375, 1253.96166666667,
1267.07825, 1281.38133333333, 1293.99208333333, 1308.05641666667,
1323.16016666667, 1338.992625, 1353.58925, 1371.2485, 1385.3055,
1399.57704166667, 1412.76375, 1425.710875, 1438.80775, 1451.77004166667,
1464.062625, 1476.80325, 1491.8025, 1502.652, 1516.61345833333,
1527.86608333333, 1544.914875, 1561.36654166667, 1575.31591666667,
1590.542625, 1609.70995833333, 1628.89525, 1647.99708333333), .Dim = c(30L,
3L), .Dimnames = list(NULL, c("MSCI.WORLD", "Funds.Target.Rate",
"Mean.Rolling")))

The variable "Funds.Target.Rate" should be presented in a more convenient way. Is it possible to create a second y-axis on the right side of the plot that refers to the interest rates of this variable? Thank you for your time and help.

Body:
As far as I know, this is not possible in ggplot2, for good reasons. see this discussion. The only thing possible is to add a second axis which is a re-calculation of the first axis, e.g. Celsius -> Fahrenheit or local differences:

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  scale_y_continuous(
    "mpg (US)",
    sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)")
  )

Having said that, you can use that hack for your purposes. First scale the interest rate, so that all variables have the same dimension (1000 - 2000 in your case) - I multiply Interest.Rate by 400. Then add the second axis and make sure the annotations show the unscaled (i.e. divided) values (* 300 and / 300 in your case):

Variables[, 2] <- Variables[, 2] * 300
df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates")

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+
    scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
    labs(x="Date", y="MSCI Value" )+
    theme_classic()+
    theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
    scale_color_manual(values=c("grey0", "orangered2", "royalblue2")) +

    # NEW CODE:
    scale_y_continuous("MSCI Value", sec.axis = sec_axis(~ . /300, name = "Interest Rate")
)


问:
Why is cancelCellEditing() not called when pressing escape while editing a JTable cell?
I have an editable JTable and have set a DefaultCellEditor like so:

```<code>    colModel.getColumn( 1 ).setCellEditor( new DefaultCellEditor( txtEditBox ) {
        // ...
        @Override
        public void cancelCellEditing() {
            super.cancelCellEditing();
            // handling the event
        }
        // ...
    }
</code>```

However, when pressing escape while editing a cell in this column, though the editing mode is finished, this method is not called. Any ideas why? Am I doing something wrong? Is there a way to handle this (other than manually adding a KeyListener that is)?

答:
The official way: You can register a CellEditorListener: AbstractCellEditor.addCellEditorListener(...). If the editing is canceled, editingCanceled(ChangeEvent e) should be called. Due to a SUN bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6788481, editingCanceled is not called :(

As workaround you can register your own action for the ESCAPE key and handle it yourself. But it will not work for resize events.

Another solution (quick and dirty;-)): Overwrite the methode JTable.removeEditor() and insert your code after the super call.

Body:
I have an editable JTable and have set a DefaultCellEditor like so:

    colModel.getColumn( 1 ).setCellEditor( new DefaultCellEditor( txtEditBox ) {
        // ...
        @Override
        public void cancelCellEditing() {
            super.cancelCellEditing();
            // handling the event
        }
        // ...
    }

However, when pressing escape while editing a cell in this column, though the editing mode is finished, this method is not called. Any ideas why? Am I doing something wrong? Is there a way to handle this (other than manually adding a KeyListener that is)?


问:
i want to select multiple images from phone write now i am using intent
I want to select multiple images from phone but I am only getting 1 image, now I am using an intent

```<code>Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
</code>```

but still it only selects one image at time .so how can I set a limit on image selection more than 1 and how I can handle it in onActivityResult.

答:
Firstly,
Which action you need to perform with multiple image,that is important

Secondly you can use Array list for same,array list of bitmap and pass that list further and you can access all that images from that list..Pls try and revert..

Body:
I want to select multiple images from phone but I am only getting 1 image, now I am using an intent

Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);

but still it only selects one image at time .so how can I set a limit on image selection more than 1 and how I can handle it in onActivityResult.


问:
How can I parse a line of potentially quoted search terms, and how can I use these terms to match input lines that each contain all of them?
I'm using Bash on Mac OS X El Capitan.

My main goal:

Allow a user to input any number of search terms, including ones containing quotes.

Iterate through a text file and show the user every line that contains matches for all search terms input.

I have a text file that is essentially an index of files on various servers. E.g.,

```<code>/Volumes/Server1/Resources/Images/this.jpg
/Volumes/Server2/Inventory/docs/that.doc
/Volumes/Server6/Projects/Project 32/the other.pdf
/Volumes/Server6/Projects/Project 32/audio video training.doc
</code>```

I'm using

```<code>read -r sSearchTerms
</code>```

to let a user input search criteria. I basically just want to parse whatever she enters so I can allow her to search based on multiple terms. I also want to allow the use of quotes to search for terms containing spaces.

For example, a user might enter "Project 32" "audio video" doc

In this case, I want to compare 3 terms to each line of my index text file: Project 32, audio video, and doc, building a results.txt file that I can then easily show the user.

The two main things I need to figure out:

How to parse the input line properly into separate strings to use for comparison purposes (making sure that anything inside quotes is treated as a single search term (and removing the quotes before comparing)). I'm imagining using an array?

stringCompare[0]="Project 32"

stringCompare[1]="audio video"

stringCompare[2]="doc"

How to properly test each line of the text file to see if it contains matches for all search terms input.

Below is my working code for comparing the whole input line as a single search term.

```<code>#!/bin/bash

SEARCH_FILE="/Users/User/Desktop/SEARCH_TEST_2.txt"
RESULTS_FILE="results.txt"
# -i ignores case
GREP_OPTS="-i"

echo "PLEASE ENTER YOUR SEARCH:"

# -r treats backslash as a backslash, instead of an escape character.
read -r sSearchTerms

echo " Searching..."

grep $GREP_OPTS "$sSearchTerms" "$SEARCH_FILE">>"$RESULTS_FILE"

echo " All Done! "

# -t = open with default text editor
open -t "$RESULTS_FILE"

osascript -e 'tell application "Terminal" to quit' &
exit
</code>```

I'm imagining replacing everything after the

```<code>read -r sSearchTerms
</code>```

with this:

```<code>strQuotes='"'
numberOfQuotes=$(grep -o "$strQuotes" <<< "$sSearchTerms" | wc -l)

if [ "$(($numberOfQuotes%2))" != "0" ]
then
    echo "ODD number of quotes"
    # Can't properly parse an odd number of quotes, so Abort!
else
    echo "EVEN number of quotes"
    # We're good to go on quotes, so go ahead and process

    # Create or overwrite the results file
    echo "">"$RESULTS_FILE"

    # CODE HERE to parse input

    # CODE HERE to compare terms to index and build results file
fi

echo " All Done! "
open -t "$RESULTS_FILE"

osascript -e 'tell application "Terminal" to quit' &
exit
</code>```

For safety and ease of coding, I already test to make sure that the user inputs an even number of quotes (0, 2, 4, ...). If not, I'll just throw a message and make the user try again.

答:
Look at the code below that reads a file line by line and runs a regex expression against each line.

```<code> #!/bin/bash
 searchline()
 {
 # The following uses the first argument as a regex
 # pattern to test against the second argument.  You
 # can use more complex regex patterns to test for
 # multiple substrings
 if [[ "$2" =~ "$1" ]]
    then
       echo "     String found"
    else
       echo "     String not found"
    fi
 }
 # At this point your read and list the arguments
 args=$#
 echo $args arguments
 echo "list of arguments preceded by script name"
 for i in `seq 0  $args`
    do
       echo "     $i   ${!i}"
    done
 echo "end of arguments"
 # Move the argumnts into the variables
 if [ "$args" -gt 0 ]
    then
       search="$1"
    else
       search="abc"
       echo "Using default search string of abc"
   fi
 if [ "$args" -gt 1 ]
    then
       file="$2";
    else
       file="stdin"
    fi
 # Read from the file or standard input, runing the
 # function above against each line
 if [ $file = "stdin" ]
    then
       echo "Read from stdin"
       end_of_file=0
       while [[ $end_of_file == 0 ]]
       do
          read -r line
          end_of_file=$?
          echo $line
          searchline $search $line
       done
    else
       echo "Read from $file"
       IFSold=$IFS
       IFS=$'\n'
       for line in `cat $file`
          do
             echo $line
             searchline $search $line
          done
       IFS=$IFSold
    fi
</code>```

The following was the test file.  It was stored in testiness.txt.  So I ran the
program with the following sets of arguments.

"the" testfiles.txt

"The" testfiles.txt

```<code> This is the first line
 Second line
 Now if the time for all good men to come to the aid of their country
 Ignorance of the law is no excuse
 The quick brown fox jumped over the lazy dog
</code>```

Body:
I'm using Bash on Mac OS X El Capitan.

My main goal:

Allow a user to input any number of search terms, including ones containing quotes.

Iterate through a text file and show the user every line that contains matches for all search terms input.

I have a text file that is essentially an index of files on various servers. E.g.,

/Volumes/Server1/Resources/Images/this.jpg
/Volumes/Server2/Inventory/docs/that.doc
/Volumes/Server6/Projects/Project 32/the other.pdf
/Volumes/Server6/Projects/Project 32/audio video training.doc

I'm using

read -r sSearchTerms

to let a user input search criteria. I basically just want to parse whatever she enters so I can allow her to search based on multiple terms. I also want to allow the use of quotes to search for terms containing spaces.

For example, a user might enter "Project 32" "audio video" doc

In this case, I want to compare 3 terms to each line of my index text file: Project 32, audio video, and doc, building a results.txt file that I can then easily show the user.

The two main things I need to figure out:

How to parse the input line properly into separate strings to use for comparison purposes (making sure that anything inside quotes is treated as a single search term (and removing the quotes before comparing)). I'm imagining using an array?

stringCompare[0]="Project 32"

stringCompare[1]="audio video"

stringCompare[2]="doc"

How to properly test each line of the text file to see if it contains matches for all search terms input.

Below is my working code for comparing the whole input line as a single search term.

#!/bin/bash

SEARCH_FILE="/Users/User/Desktop/SEARCH_TEST_2.txt"
RESULTS_FILE="results.txt"
# -i ignores case
GREP_OPTS="-i"

echo "PLEASE ENTER YOUR SEARCH:"

# -r treats backslash as a backslash, instead of an escape character.
read -r sSearchTerms

echo " Searching..."

grep $GREP_OPTS "$sSearchTerms" "$SEARCH_FILE">>"$RESULTS_FILE"

echo " All Done! "

# -t = open with default text editor
open -t "$RESULTS_FILE"

osascript -e 'tell application "Terminal" to quit' &
exit

I'm imagining replacing everything after the

read -r sSearchTerms

with this:

strQuotes='"'
numberOfQuotes=$(grep -o "$strQuotes" <<< "$sSearchTerms" | wc -l)

if [ "$(($numberOfQuotes%2))" != "0" ]
then
    echo "ODD number of quotes"
    # Can't properly parse an odd number of quotes, so Abort!
else
    echo "EVEN number of quotes"
    # We're good to go on quotes, so go ahead and process

    # Create or overwrite the results file
    echo "">"$RESULTS_FILE"

    # CODE HERE to parse input

    # CODE HERE to compare terms to index and build results file
fi

echo " All Done! "
open -t "$RESULTS_FILE"

osascript -e 'tell application "Terminal" to quit' &
exit

For safety and ease of coding, I already test to make sure that the user inputs an even number of quotes (0, 2, 4, ...). If not, I'll just throw a message and make the user try again.

Body:
Look at the code below that reads a file line by line and runs a regex expression against each line.

 #!/bin/bash
 searchline()
 {
 # The following uses the first argument as a regex
 # pattern to test against the second argument.  You
 # can use more complex regex patterns to test for
 # multiple substrings
 if [[ "$2" =~ "$1" ]]
    then
       echo "     String found"
    else
       echo "     String not found"
    fi
 }
 # At this point your read and list the arguments
 args=$#
 echo $args arguments
 echo "list of arguments preceded by script name"
 for i in `seq 0  $args`
    do
       echo "     $i   ${!i}"
    done
 echo "end of arguments"
 # Move the argumnts into the variables
 if [ "$args" -gt 0 ]
    then
       search="$1"
    else
       search="abc"
       echo "Using default search string of abc"
   fi
 if [ "$args" -gt 1 ]
    then
       file="$2";
    else
       file="stdin"
    fi
 # Read from the file or standard input, runing the
 # function above against each line
 if [ $file = "stdin" ]
    then
       echo "Read from stdin"
       end_of_file=0
       while [[ $end_of_file == 0 ]]
       do
          read -r line
          end_of_file=$?
          echo $line
          searchline $search $line
       done
    else
       echo "Read from $file"
       IFSold=$IFS
       IFS=$'\n'
       for line in `cat $file`
          do
             echo $line
             searchline $search $line
          done
       IFS=$IFSold
    fi

The following was the test file.  It was stored in testiness.txt.  So I ran the
program with the following sets of arguments.

"the" testfiles.txt

"The" testfiles.txt

 This is the first line
 Second line
 Now if the time for all good men to come to the aid of their country
 Ignorance of the law is no excuse
 The quick brown fox jumped over the lazy dog


问:
timestamp from year and day of year?
I have to deduce the timestamp number from a list of items in Python 2.7.

For each item I have the year and the days of the year when it was created, for example:

```<code>year = 2015
days = 154
</code>```

I don't have any data about hours, minutes, seconds and milliseconds, so I assume that they are all equal to 0.

Can someone help me to deduce a timestamp?

答:
Giving a year and a day of the year, you can have a date with day, month and year. But to get a timestamp, you still need the hours, minutes, seconds, milliseconds and a timezone.

In the example below, I'm setting the time fields (hour/minute/seconds/millisecond) to zero and timezone to UTC:

```<code>from datetime import datetime
from pytz import timezone

year = 2017
day_of_year = 154
# strptime sets the hours/minutes/secs to zero
d = datetime.strptime("%s %s" % (year, day_of_year), "%Y %j").replace(tzinfo = pytz.utc)
print(d.timestamp())
print(d)
</code>```

The date d will be 2017-06-03 00:00:00+00:00 and the respective timestamp will be 1496448000 - the number of seconds from unix epoch (1970-01-01T00:00:00Z). If you want the timestamp in milliseconds, just multiply this value by 1000.

Although I used UTC, you can change it to use the timezone that suits best for your case.

Title: timestamp from year and day of year?

Body:
I have to deduce the timestamp number from a list of items in Python 2.7.

For each item I have the year and the days of the year when it was created, for example:

year = 2015
days = 154

I don't have any data about hours, minutes, seconds and milliseconds, so I assume that they are all equal to 0.

Can someone help me to deduce a timestamp?

Body:
Giving a year and a day of the year, you can have a date with day, month and year. But to get a timestamp, you still need the hours, minutes, seconds, milliseconds and a timezone.

In the example below, I'm setting the time fields (hour/minute/seconds/millisecond) to zero and timezone to UTC:

from datetime import datetime
from pytz import timezone

year = 2017
day_of_year = 154
# strptime sets the hours/minutes/secs to zero
d = datetime.strptime("%s %s" % (year, day_of_year), "%Y %j").replace(tzinfo = pytz.utc)
print(d.timestamp())
print(d)

The date d will be 2017-06-03 00:00:00+00:00 and the respective timestamp will be 1496448000 - the number of seconds from unix epoch (1970-01-01T00:00:00Z). If you want the timestamp in milliseconds, just multiply this value by 1000.

Although I used UTC, you can change it to use the timezone that suits best for your case.


问:
Python: Nested List Indexing Error
```<code>result = []
for big in aisle:
  for small in big:
    if len(small) >= 0:
        result.append(small[1])
print(np.result)
</code>```

I've been getting this error: "string index out of range"

I added in the if statement to make sure each list within the lists under aisle have at least 2 items but still am getting this error. aisle is a list containing lists. the goal is to create a new list only containing the second item in each list within aisle. Of course it would be easier to do using numpy and arrays but want to learn...

答: len(small) >= 0 is always true - nothing can have less than 0 elements. To have an element with index 1, small must be at least 2 elements long (small[0] and small[1]), so you should test for len(small) > 1

Title: Python: Nested List Indexing Error

Body:
result = []
for big in aisle:
  for small in big:
    if len(small) >= 0:
        result.append(small[1])
print(np.result)

I've been getting this error: "string index out of range"

I added in the if statement to make sure each list within the lists under aisle have at least 2 items but still am getting this error. aisle is a list containing lists. the goal is to create a new list only containing the second item in each list within aisle. Of course it would be easier to do using numpy and arrays but want to learn...


问:
Java swing BoxLayout center doesn't work
I have a JFrame that has JPanel inside. Inside JPanel there are 2 buttons. JPanel has a BoxLayout. I need buttons to be displayed horizontally in the center of the window. Here is my code:

I just create two buttons, set their alignment to the center (tried all the ways I knew) and add them to the panel horizontally.

```<code>public class UserInterface extends JFrame  {
   public UserInterface()  {
                setup();
   }
   private void setup()  {
         ...
         panel=new UserInterfacePanel();
         add(panel);
   }
}

class UserInterfacePanel extends JPanel {
         private JToggleButton startButton;
         private JToggleButton stopButton;

         public UserInterfacePanel()  {
             setup();
         }

         private void setup()  {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

            setupButtons();
            setupButtonsActions();
            add(startButton);
            add(stopButton);
        }

        private void setupButtons()  {
            ...
            startButton.setHorizontalAlignment(JButton.CENTER);
            stopButton.setHorizontalAlignment(JButton.CENTER);
            startButton.setAlignmentX(CENTER_ALIGNMENT);
            stopButton.setAlignmentX(CENTER_ALIGNMENT);
        }
}
</code>```

And yet it doesn't work. Why doesn't it and how to fix it?

答:
You're setting the x alignment of the buttons but you're box layout lays out along the x axis -- doesn't make sense. Either set the y alignment and use the x axis for the box layout direction, or set the x alignment and use the y axis for the box layout direction.

e.g.,

```<code>private void setup() {
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));  // **** change ****

    setupButtons();
    // setupButtonsActions();
    add(startButton);
    add(stopButton);
}

private void setupButtons() {
    // ...
    startButton.setHorizontalAlignment(JButton.CENTER);
    stopButton.setHorizontalAlignment(JButton.CENTER);
    startButton.setAlignmentX(CENTER_ALIGNMENT);
    stopButton.setAlignmentX(CENTER_ALIGNMENT);
}
</code>```

or

```<code>private void setup() {
    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

    setupButtons();
    // setupButtonsActions();
    add(startButton);
    add(stopButton);
}

private void setupButtons() {
    // ...
    startButton.setHorizontalAlignment(JButton.CENTER);
    stopButton.setHorizontalAlignment(JButton.CENTER);
    startButton.setAlignmentY(CENTER_ALIGNMENT);  // **** change ****
    stopButton.setAlignmentY(CENTER_ALIGNMENT);  // **** change ****
}
</code>```

To center all, use a different layout, such as a GridBagLayout:

```<code>import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;

@SuppressWarnings("serial")
public class UserInterfacePanel extends JPanel {
    private static final Insets INSETS = new Insets(3, 3, 3, 3);
    private static final int PREF_W = 800;
    private static final int PREF_H = 650;
    private JToggleButton startButton = new JToggleButton("Start");
    private JToggleButton stopButton = new JToggleButton("Long Texted Title");

    public UserInterfacePanel() {
        setup();
    }

    private void setup() {
        setLayout(new GridBagLayout());  // **** change

        add(startButton, createGbc(0, 0));
        add(stopButton, createGbc(1, 0));
    }

    private GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.insets = INSETS;
        return gbc;
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        UserInterfacePanel mainPanel = new UserInterfacePanel();

        JFrame frame = new JFrame("UserInterfacePanel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
</code>```

Body:
I have a JFrame that has JPanel inside. Inside JPanel there are 2 buttons. JPanel has a BoxLayout. I need buttons to be displayed horizontally in the center of the window. Here is my code:

I just create two buttons, set their alignment to the center (tried all the ways I knew) and add them to the panel horizontally.

public class UserInterface extends JFrame  {
   public UserInterface()  {
                setup();
   }
   private void setup()  {
         ...
         panel=new UserInterfacePanel();
         add(panel);
   }
}

class UserInterfacePanel extends JPanel {
         private JToggleButton startButton;
         private JToggleButton stopButton;

         public UserInterfacePanel()  {
             setup();
         }

         private void setup()  {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

            setupButtons();
            setupButtonsActions();
            add(startButton);
            add(stopButton);
        }

        private void setupButtons()  {
            ...
            startButton.setHorizontalAlignment(JButton.CENTER);
            stopButton.setHorizontalAlignment(JButton.CENTER);
            startButton.setAlignmentX(CENTER_ALIGNMENT);
            stopButton.setAlignmentX(CENTER_ALIGNMENT);
        }
}

And yet it doesn't work. Why doesn't it and how to fix it?

Body:
You're setting the x alignment of the buttons but you're box layout lays out along the x axis -- doesn't make sense. Either set the y alignment and use the x axis for the box layout direction, or set the x alignment and use the y axis for the box layout direction.

e.g.,

private void setup() {
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));  // **** change ****

    setupButtons();
    // setupButtonsActions();
    add(startButton);
    add(stopButton);
}

private void setupButtons() {
    // ...
    startButton.setHorizontalAlignment(JButton.CENTER);
    stopButton.setHorizontalAlignment(JButton.CENTER);
    startButton.setAlignmentX(CENTER_ALIGNMENT);
    stopButton.setAlignmentX(CENTER_ALIGNMENT);
}

or

private void setup() {
    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

    setupButtons();
    // setupButtonsActions();
    add(startButton);
    add(stopButton);
}

private void setupButtons() {
    // ...
    startButton.setHorizontalAlignment(JButton.CENTER);
    stopButton.setHorizontalAlignment(JButton.CENTER);
    startButton.setAlignmentY(CENTER_ALIGNMENT);  // **** change ****
    stopButton.setAlignmentY(CENTER_ALIGNMENT);  // **** change ****
}

To center all, use a different layout, such as a GridBagLayout:

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;

@SuppressWarnings("serial")
public class UserInterfacePanel extends JPanel {
    private static final Insets INSETS = new Insets(3, 3, 3, 3);
    private static final int PREF_W = 800;
    private static final int PREF_H = 650;
    private JToggleButton startButton = new JToggleButton("Start");
    private JToggleButton stopButton = new JToggleButton("Long Texted Title");

    public UserInterfacePanel() {
        setup();
    }

    private void setup() {
        setLayout(new GridBagLayout());  // **** change

        add(startButton, createGbc(0, 0));
        add(stopButton, createGbc(1, 0));
    }

    private GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.insets = INSETS;
        return gbc;
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        UserInterfacePanel mainPanel = new UserInterfacePanel();

        JFrame frame = new JFrame("UserInterfacePanel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}


答:
Python list indexing is 0 based, my guess is that small might have only one item.</p>

```<code>result = []
for big in aisle:
  for small in big:
    if len(small) > 0: # >= 0 is always true
        result.append(small[0]) # Here if len(small) === 1 the item is at small[0]
print(result)
</code>```

Title: Python: Nested List Indexing Error

Body:
Python list indexing is 0 based, my guess is that small might have only one item.

result = []
for big in aisle:
  for small in big:
    if len(small) > 0: # >= 0 is always true
        result.append(small[0]) # Here if len(small) === 1 the item is at small[0]
print(result)


问:
Flying through starfield. LibGDX
What is the best way to implement something like this using LibGDX ? I have searched in the internet about this but didn't find anything helpful.</p>

答:
While, you still need to think this through, I'll point you in the right direction, I would recommend you create an object with values such as a vector2 for the spawn point and a vector2 for the direction, as well as an integer for the time counter, I would update these variables in a render function within the object. Then create an array of this specific object and update each value in the game render function using a for loop, and in that loop render a line with a shape renderer of a length depending on the time passed, and in the direction of the vector.
Also, if you liked this answer but would like further detail, check this as an answer and I'll edit in an example</p>

Title: Flying through starfield. LibGDX


问:
Angular 2 + Auth0 (Could not find a declaration file for module 'auth0-js'. )
Could not find a declaration file for module 'auth0-js'. 'C:/sandbox/loginauth0/node_modules/auth0-js/src/index.js' implicitly has an 'any' type.

I wanted to use the auth0 login. But after following the instructions and building my own Angular 2 service.

import * as auth0 from 'auth0-js';

gives an error like above. but I put it in with "npm install --save auth0-js" and its in my node_modules

答:
Auth0.js doesn't yet provide TypeScript type definition file. You can try using:

```<code>const auth0 = require('auth0-js');
</code>```

or the more brute-force method of turning the noImplicitAny flag to false in your tsconfig.json file, but that turns off warnings/errors for the whole project. See more info here.

Body:
Auth0.js doesn't yet provide TypeScript type definition file. You can try using:

const auth0 = require('auth0-js');

or the more brute-force method of turning the noImplicitAny flag to false in your tsconfig.json file, but that turns off warnings/errors for the whole project. See more info here.


问:
is this regular grammar- S -> 0S0/00?
Let L denotes the language generated by the grammar S -> 0S0/00. Which of the following is true?
(A) L = 0+
(B) L is regular but not 0+
(C) L is context free but not regular
(D) L is not context free

HI can anyone explain me how the language represented by the grammar S -> 0S0/00 is regular? I know very well the grammar is context free but not sure how can that be regular?

答:
We know that a language is regular if there exists a DFA (deterministic finite automata) that recogognizes it, or a RE (Regular expression). Either way we can see here that your grammar generates word like : 00, 0000, 000000, 00000000.. etc so it's words that starts and ends with '0' and with an even number of zeroes greater or equal than length two.

Here's a DFA for this grammar

Also here is a RE (Regular expression) that recognizes the language :

(0)(00)*(0)

Therefore you know this language recognized by this grammar is regular.

(Sorry if terms aren't 100% accurate, i took this class in french so terms might differ a bit) let me know if you have any other questions!

Title: is this regular grammar- S -> 0S0/00?