问:
starting with react example, in constructors this.method = this.method.bind(this) , why?
I'm starting with react and the first thing I did is to go to the main page where I see some examples, e.g.:

```<code>class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Type some *markdown* here!' };
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    const md = new Remarkable();
    return { __html: md.render(this.state.value) };
  }

  render() {
    return (
      <div className="MarkdownEditor">
        <h3>Input</h3>
        <textarea
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />
        <h3>Output</h3>
        <div
          className="content"
          dangerouslySetInnerHTML={this.getRawMarkup()}
        />
      </div>
    );
  }
}

ReactDOM.render(<MarkdownEditor />, mountNode);
</code>```

...
I see that in the constructor is done:

```<code>this.handleChange = this.handleChange.bind(this);
</code>```

What is the reason behind that? Talking with colleagues they think some possible reasons like something special behind the render() method, or something related with non supported feature of ES6.

Do someone have a specific explainment to that?

In a first look, it seems unnecessary for me as shown in this simple example:

```<code>class A {
  constructor(){
      this.a = 1;
  }
  do(){
      console.log('A', this.a);
 }
}

class B extends A {
  constructor(){
    super();
    this.a = 2;
  }

 do(){
      console.log('B', this.a);
  }
}
console.log ((new B()).do())
</code>```

答:
Inside React render method you need to bind the function..

import React from 'react';

export default class App React.component {

   constructor(){
     super();

  //simple binding
  this.handleSomthing2 = this.handleSomthing2.bind(this);

   //binding somthing with different name
  this.handleSomthing4 = this.handle.bind(this);

   }
handleSomthing() {
 //code here
}

handleSomthing2(){
 //code here
}

//using arrow function
handleSomthing3=()=>{// code here}

handleSomthing4(){
 //code here
}

 render() {

 return (

   {handleSomthing()} //cannot be access without binding.
   {this. handleSomthing()} //cannot be access without binding.

   {this.handleSomthing2} //bind with the function above and can be access.

   {this.handleSomthing3} //using arrow function bind the above function.

   {this.handle} // this bind the function handleSomthing4

 );

 }

 }```

Body:
I'm starting with react and the first thing I did is to go to the main page where I see some examples, e.g.:

class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Type some *markdown* here!' };
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    const md = new Remarkable();
    return { __html: md.render(this.state.value) };
  }

  render() {
    return (

Input

        <textarea
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />

Output

    );
  }
}

ReactDOM.render(<MarkdownEditor />, mountNode);

...
I see that in the constructor is done:

this.handleChange = this.handleChange.bind(this);

What is the reason behind that? Talking with colleagues they think some possible reasons like something special behind the render() method, or something related with non supported feature of ES6.

Do someone have a specific explainment to that?

In a first look, it seems unnecessary for me as shown in this simple example:

class A {
  constructor(){
      this.a = 1;
  }
  do(){
      console.log('A', this.a);
 }
}

class B extends A {
  constructor(){
    super();
    this.a = 2;
  }

 do(){
      console.log('B', this.a);
  }
}
console.log ((new B()).do())

Body:
Inside React render method you need to bind the function..

import React from 'react';

export default class App React.component {

   constructor(){
     super();

  //simple binding
  this.handleSomthing2 = this.handleSomthing2.bind(this);

   //binding somthing with different name
  this.handleSomthing4 = this.handle.bind(this);

   }
handleSomthing() {
 //code here
}

handleSomthing2(){
 //code here
}

//using arrow function
handleSomthing3=()=>{// code here}

handleSomthing4(){
 //code here
}

 render() {

 return (
  <div>
   {handleSomthing()} //cannot be access without binding.
   {this. handleSomthing()} //cannot be access without binding.

   {this.handleSomthing2} //bind with the function above and can be access.

   {this.handleSomthing3} //using arrow function bind the above function.

   {this.handle} // this bind the function handleSomthing4

  </div>

 );

 }

 }


来源: stackexchange

问:
Append new Data to JSON Data
I am somewhat new to JSON and I wanted to write a simple method that would append a data to my JSON instead of creating new JSON Object.

Here is my JSON Code:

```<code>public static JSONObject jsonObj = new JSONObject();
public static String toJSON(params) {

    try {

        jsonObj.put("Timestamp", timestamp);
        jsonObj.put("Package Name", packageName);
        jsonObj.put("Package Label", packageLabel);
        jsonObj.put("Permissions Requested at Once", permissionReqOnce);
        jsonObj.put("Permission Group", permGroup);
        jsonObj.put("Accept or Deny", acceptDeny);

        return jsonObj.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }
    return null;
}
</code>```

However, when I call it like this,

```<code>toJSON("data0", "data", "data", "data", "data", "data");
toJSON("data1", "data1", "data1", "data1", "data1", "data1");
Log.d("JSON", FileHandle.jsonObj.toString());
</code>```

it only returns me the last passed data:

```<code>{"Timestamp":"data1","Package Name":"data1","Package Label":"data1","Permissions Requested at Once":"data1","Permission Group":"data1","Accept or Deny":"data1"}
</code>```

What I want is:

```<code>[
 {
   "Timestamp": "data0",
   "Package Name": "data",
   "Package Label": "data",
   "Permissions Requested at Once": "data",
   "Permission Group": "data",
   "Accept or Deny": "data",
 },
 {
   "Timestamp": "data1",
   "Package Name": "data1",
   "Package Label": "data1",
   "Permissions Requested at Once": "data1",
   "Permission Group": "data1",
   "Accept or Deny": "data1",
 }
]
</code>```

How can this be achieved? Thanks.

答:
Use JSONArray as root container instead of JSONObject

During every call, Create new JSONObject and put it inside root JSONArray

Then use

```<code>// our root JSONArray to store JSONObject
JSONArray jsonArr = new JSONArray();

public static String toJSON(params) {
    // inner JSONObject
    JSONObject jsonObj1 = new JSONObject();
    try {
        // Here we convert Java Object to JSON
        jsonObj1.put("Timestamp", timestamp); // Set the first name/pair
        jsonObj1.put("Package Name", packageName);
        jsonObj1.put("Package Label", packageLabel);
        jsonObj1.put("Permissions Requested at Once", permissionReqOnce);
        jsonObj1.put("Permission Group", permGroup);
        jsonObj1.put("Accept or Deny", acceptDeny);
        jsonArr.put(jsonObj1);
        // return string form of collected data so far as jsonarray
        return jsonArr.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }
    return null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Append new Data to JSON Data

Body:
I am somewhat new to JSON and I wanted to write a simple method that would append a data to my JSON instead of creating new JSON Object.

Here is my JSON Code:

public static JSONObject jsonObj = new JSONObject();
public static String toJSON(params) {

    try {

        jsonObj.put("Timestamp", timestamp);
        jsonObj.put("Package Name", packageName);
        jsonObj.put("Package Label", packageLabel);
        jsonObj.put("Permissions Requested at Once", permissionReqOnce);
        jsonObj.put("Permission Group", permGroup);
        jsonObj.put("Accept or Deny", acceptDeny);

        return jsonObj.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }
    return null;
}

However, when I call it like this,

toJSON("data0", "data", "data", "data", "data", "data");
toJSON("data1", "data1", "data1", "data1", "data1", "data1");
Log.d("JSON", FileHandle.jsonObj.toString());

it only returns me the last passed data:

{"Timestamp":"data1","Package Name":"data1","Package Label":"data1","Permissions Requested at Once":"data1","Permission Group":"data1","Accept or Deny":"data1"}

What I want is:

[
 {
   "Timestamp": "data0",
   "Package Name": "data",
   "Package Label": "data",
   "Permissions Requested at Once": "data",
   "Permission Group": "data",
   "Accept or Deny": "data",
 },
 {
   "Timestamp": "data1",
   "Package Name": "data1",
   "Package Label": "data1",
   "Permissions Requested at Once": "data1",
   "Permission Group": "data1",
   "Accept or Deny": "data1",
 }
]

How can this be achieved? Thanks.

Body:
Use JSONArray as root container instead of JSONObject

During every call, Create new JSONObject and put it inside root JSONArray

Then use

// our root JSONArray to store JSONObject
JSONArray jsonArr = new JSONArray();

public static String toJSON(params) {
    // inner JSONObject
    JSONObject jsonObj1 = new JSONObject();
    try {
        // Here we convert Java Object to JSON
        jsonObj1.put("Timestamp", timestamp); // Set the first name/pair
        jsonObj1.put("Package Name", packageName);
        jsonObj1.put("Package Label", packageLabel);
        jsonObj1.put("Permissions Requested at Once", permissionReqOnce);
        jsonObj1.put("Permission Group", permGroup);
        jsonObj1.put("Accept or Deny", acceptDeny);
        jsonArr.put(jsonObj1);
        // return string form of collected data so far as jsonarray
        return jsonArr.toString();

    }
    catch(JSONException ex) {
        ex.printStackTrace();
    }
    return null;
}


问:
How do I attach VisualVM to a simple Java process running in a Docker container
Actually I wanted a solution working for JEE containers, specifically for Glassfish, but after I tried many combinations of settings and did not succeed, I reduced the setup to the simplest possible case.

Here is my Hello World daemon started in a Docker container. I want to attach jconsole or VisulaVM to it. Everything is on the same machine.

public class Main {
  public static void main(String[] args) {
    while (true) {
      try {
        Thread.sleep(3000);
        System.out.println("Hello, World");
      } catch (InterruptedException e) {
        break;
      }
    }
  }
}
```

<p>Dockerfile</p>

```FROM java:8
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
CMD ["java", "Main"]
```

<p>Building: <code>docker build -t hello-world-daemon .</code></p>

<p>Running: <code>docker run -it --rm --name hwd hello-world-daemon</code></p>

<p>Questions:</p>

<ul>
<li>what JVM parameters should be added to <code>CMD</code> command line?</li>
<li>what ports should be exposed and published?</li>
<li>what network mode should Docker container be using?</li>
</ul>

<p>I do not show my failed attempts here so that correct answers will not be biased. This should be a pretty common problem, yet I could not find a working solution.</p>

<p><strong>Update. Worked solution</strong></p>

<p>This Dockerfile works</p>

```FROM java:8
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
CMD ["java", \
"-Dcom.sun.management.jmxremote", \
"-Dcom.sun.management.jmxremote.port=9010", \
"-Dcom.sun.management.jmxremote.local.only=false", \
"-Dcom.sun.management.jmxremote.authenticate=false", \
"-Dcom.sun.management.jmxremote.ssl=false", "Main"]
EXPOSE 9010
```

<p>in combination with the docker run command</p>

```docker run -it --rm --name hwd -p 9010:9010 hello-world-daemon
```

VisualVM connects via right click Local->Add JMX Connection, and then entering localhost:9010, or through adding a remote host.

JConsole connects via selecting a Remote process with localhost:9010.

When defining the connection as remote, any interface listed by ifconfig can be used. For instance, docker0 interface with address 172.17.0.1 works. The container's address 172.17.0.2 works too.

答:
As answered by Anthony.
I had to use the -Djava.rmi.server.hostname java option on my Windows machine.

Just be sure not to use the CMD in JSON format in your Dockerfile as this doesn't support shell expansion.

Dockerfile example:

```<code>FROM java:8
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
#Do not use CMD in JSON format here because shell expansion doesn't work in JSON format
#Shell expansion is needed for the ${HOST} variable.
CMD java -Dcom.sun.management.jmxremote=true \
-Dcom.sun.management.jmxremote.rmi.port=9010 \
-Dcom.sun.management.jmxremote.port=9010 \
-Dcom.sun.management.jmxremote.ssl=false \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.local.only=false \
-Djava.rmi.server.hostname=${HOST} \
Main
</code>```

Body:
Actually I wanted a solution working for JEE containers, specifically for Glassfish, but after I tried many combinations of settings and did not succeed, I reduced the setup to the simplest possible case.

Here is my Hello World daemon started in a Docker container. I want to attach jconsole or VisulaVM to it. Everything is on the same machine.

public class Main {
  public static void main(String[] args) {
    while (true) {
      try {
        Thread.sleep(3000);
        System.out.println("Hello, World");
      } catch (InterruptedException e) {
        break;
      }
    }
  }
}

Dockerfile

FROM java:8
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
CMD ["java", "Main"]

Building: docker build -t hello-world-daemon .

Running: docker run -it --rm --name hwd hello-world-daemon

Questions:

what JVM parameters should be added to CMD command line?

what ports should be exposed and published?

what network mode should Docker container be using?

I do not show my failed attempts here so that correct answers will not be biased. This should be a pretty common problem, yet I could not find a working solution.

Update. Worked solution

This Dockerfile works

FROM java:8
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
CMD ["java", \
"-Dcom.sun.management.jmxremote", \
"-Dcom.sun.management.jmxremote.port=9010", \
"-Dcom.sun.management.jmxremote.local.only=false", \
"-Dcom.sun.management.jmxremote.authenticate=false", \
"-Dcom.sun.management.jmxremote.ssl=false", "Main"]
EXPOSE 9010

in combination with the docker run command

docker run -it --rm --name hwd -p 9010:9010 hello-world-daemon

VisualVM connects via right click Local->Add JMX Connection, and then entering localhost:9010, or through adding a remote host.

JConsole connects via selecting a Remote process with localhost:9010.

When defining the connection as remote, any interface listed by ifconfig can be used. For instance, docker0 interface with address 172.17.0.1 works. The container's address 172.17.0.2 works too.

Body:
As answered by Anthony.
I had to use the -Djava.rmi.server.hostname java option on my Windows machine.

Just be sure not to use the CMD in JSON format in your Dockerfile as this doesn't support shell expansion.

Dockerfile example:

FROM java:8
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
RUN javac Main.java
#Do not use CMD in JSON format here because shell expansion doesn't work in JSON format
#Shell expansion is needed for the ${HOST} variable.
CMD java -Dcom.sun.management.jmxremote=true \
-Dcom.sun.management.jmxremote.rmi.port=9010 \
-Dcom.sun.management.jmxremote.port=9010 \
-Dcom.sun.management.jmxremote.ssl=false \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.local.only=false \
-Djava.rmi.server.hostname=${HOST} \
Main


问:
Use same domain for two different subdomains?
I have a website called example.com.

I want www.example.com to point to my blog (on WordPress), but I want app.example.com to point to my app (on Heroku).

I am registered with Godaddy (could be any service though).

Is it possible to have one domain go to two completely different places?

答:
Yes that is, just create two dns records for example:

www.example.com CNAME hosting.example.com

app.example.com A 109.23.23.45

cheers


问:
Changing orientation of all children of LinearLayout programatically
I have a LinearLayout (child) inside another (parent) LinearLayout. I want to change the orientation of the parent from horizontal to vertical and vice versa and do the same for all children. How can i propagate this orientation change from parent to its children with adding any additional interface.

Btw, this has nothing to with orientation change of the device. I want the  orientation to change as per event encountered.

I can have multiple LinearLayout as its children and i don't want to set the orientation of all of these in a for loop since i am adding children programmatically

答:
```<code>ll1 = (LinearLayout) findViewById(R.id.llayout);
ll2 = (LinearLayout) findViewById(R.id.llayout2);
</code>```

Use setOrientation to change the orientation.

```<code>ll1.setOrientation(LinearLayout.VERTICAL);
ll2.setOrientation(LinearLayout.HORIZONTAL);
</code>```

Body:
ll1 = (LinearLayout) findViewById(R.id.llayout);
ll2 = (LinearLayout) findViewById(R.id.llayout2);

Use setOrientation to change the orientation.

ll1.setOrientation(LinearLayout.VERTICAL);
ll2.setOrientation(LinearLayout.HORIZONTAL);

ContentLicense: CC BY-SA 4.0


问:
Trouble using genericra to integrate activemq and glassfish when using failover protocol
I'm attempting to use activemq in glassfish using the genericra resource adapter provided with glassfish 2.1. I have found a few pages with helpful information including http://activemq.apache.org/sjsas-with-genericjmsra.html.

I have actually had success and been able to get MDBs to use activemq as their JMS provider, but I'm running into an issue as I'm trying to do some more complicated configuration. I want to set up a master-slave configuration, which would require my clients to use a brokerURL of failover:(tcp://broker1:61616,tcp://broker2:61616). In order to do this, I set the following property when calling asadmin create-resource-adapter-config (I have to escape '=' and ':'):

```<code>ConnectionFactoryProperties=brokerURL\=failover\:(tcp\://127.0.0.1\:61616,tcp\://127.0.0.1\:61617)
</code>```

However, I am now getting a StringIndexOutOfBoundsException when my application starts up. I suspect the comma in between the two URLs is the culprit, since this works fine:

```<code>brokerURL\=failover\:(tcp\://127.0.0.1\:61616)
</code>```

Just wondering if anyone has dealt with this issue before. Also wondering if there is a better way to integrate with glassfish than using the generic resource adapter.

EDIT: I forgot to escape the colon after the second tcp, but unfortunately that didn't fix the issue I'm seeing.

答:
I ended up switching to use the resource adapter provided by activemq that comes in the lib/optional directory.

In case anyone is interested, here are the steps I followed to get it working

```<code>asadmin create-resource-adapter-config --property ServerUrl=failover\:(tcp\://localhost\:61616,tcp\://localhost\:61617) activemqra

asadmin deploy --name activemqra <path to activemq-rar-5.4.2.rar>
</code>```

Then to create resources:

```<code>asadmin create-connector-connection-pool --raname --connectiondefinition javax.jms.ConnectionFactory --transactionsupport XATransaction jms/MyQueueFactoryPool

asadmin create-connector-resource --poolname jms/MyQueueFactoryPool jms/MyQueueQFactory

asadmin create-admin-object --raname activemqra --restype javax.jms.Queue --property PhysicalName=MyQueue jms/MyQueue
</code>```

To get an mdb hooked up, I had to add this in the sun-ejb-jar.xml

```<code><mdb-resource-adapter>
                <resource-adapter-mid>activemqra</resource-adapter-mid>
                <activation-config>
                    <activation-config-property>
                        <activation-config-property-name>DestinationType
                        </activation-config-property-name>
                        <activation-config-property-value>javax.jms.Queue
                        </activation-config-property-value>
                    </activation-config-property>
                    <activation-config-property>
                        <activation-config-property-name>destination
                        </activation-config-property-name>
                        <activation-config-property-value>MyQueue
                        </activation-config-property-value>
                    </activation-config-property>
                </activation-config>
            </mdb-resource-adapter>
</code>```

To hook this up to a spring JMSTemplate:

```<code><bean id="ConFac" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>jms/MyQueueQQFactory</value>
        </property>
        <property name="resourceRef">
            <value>true</value>
        </property>
    </bean>
    <bean id="myqueue" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>jms/MyQueue</value>
        </property>
        <property name="resourceRef">
            <value>true</value>
        </property>
    </bean>
    <bean id="mdbTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="conFac" />
        <property name="defaultDestination" ref="myqueue" />
    </bean>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm attempting to use activemq in glassfish using the genericra resource adapter provided with glassfish 2.1. I have found a few pages with helpful information including http://activemq.apache.org/sjsas-with-genericjmsra.html.

I have actually had success and been able to get MDBs to use activemq as their JMS provider, but I'm running into an issue as I'm trying to do some more complicated configuration. I want to set up a master-slave configuration, which would require my clients to use a brokerURL of failover:(tcp://broker1:61616,tcp://broker2:61616). In order to do this, I set the following property when calling asadmin create-resource-adapter-config (I have to escape '=' and ':'):

ConnectionFactoryProperties=brokerURL\=failover\:(tcp\://127.0.0.1\:61616,tcp\://127.0.0.1\:61617)

However, I am now getting a StringIndexOutOfBoundsException when my application starts up. I suspect the comma in between the two URLs is the culprit, since this works fine:

brokerURL\=failover\:(tcp\://127.0.0.1\:61616)

Just wondering if anyone has dealt with this issue before. Also wondering if there is a better way to integrate with glassfish than using the generic resource adapter.

EDIT: I forgot to escape the colon after the second tcp, but unfortunately that didn't fix the issue I'm seeing.

Body:
I ended up switching to use the resource adapter provided by activemq that comes in the lib/optional directory.

In case anyone is interested, here are the steps I followed to get it working

asadmin create-resource-adapter-config --property ServerUrl=failover\:(tcp\://localhost\:61616,tcp\://localhost\:61617) activemqra

asadmin deploy --name activemqra <path to activemq-rar-5.4.2.rar>

Then to create resources:

asadmin create-connector-connection-pool --raname --connectiondefinition javax.jms.ConnectionFactory --transactionsupport XATransaction jms/MyQueueFactoryPool

asadmin create-connector-resource --poolname jms/MyQueueFactoryPool jms/MyQueueQFactory

asadmin create-admin-object --raname activemqra --restype javax.jms.Queue --property PhysicalName=MyQueue jms/MyQueue

To get an mdb hooked up, I had to add this in the sun-ejb-jar.xml

<mdb-resource-adapter>
                <resource-adapter-mid>activemqra</resource-adapter-mid>
                <activation-config>
                    <activation-config-property>
                        <activation-config-property-name>DestinationType
                        </activation-config-property-name>
                        <activation-config-property-value>javax.jms.Queue
                        </activation-config-property-value>
                    </activation-config-property>
                    <activation-config-property>
                        <activation-config-property-name>destination
                        </activation-config-property-name>
                        <activation-config-property-value>MyQueue
                        </activation-config-property-value>
                    </activation-config-property>
                </activation-config>
            </mdb-resource-adapter>

To hook this up to a spring JMSTemplate:

<bean id="ConFac" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>jms/MyQueueQQFactory</value>
        </property>
        <property name="resourceRef">
            <value>true</value>
        </property>
    </bean>
    <bean id="myqueue" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>jms/MyQueue</value>
        </property>
        <property name="resourceRef">
            <value>true</value>
        </property>
    </bean>
    <bean id="mdbTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="conFac" />
        <property name="defaultDestination" ref="myqueue" />
    </bean>


问:
Why doesn’t a colon in function body not throw an error in JavaScript?
I wanted to return an object from an arrow function, but the code below was returning undefined. I realized that the curly braces were being interpreted as beginning/ending the function body. What intrigues me is why a: 1 didn’t throw an error.

```<code>const foo = () => {a: 1};
foo();
// > undefined
</code>```

答:
The issue is that the parser sees a label called 'a' which belongs to the expression statement '1'. Since there's no return statement at all, the returned value is always undefined.

If you wrap the body inside '()' you'll see your object being returned, see below.

```<code>const foo = () => ({a: 1});
console.log(foo());
</code>```

Edit: By adding the parentheses you are forcing the parser to treat the object literal as an expression so that it's not treated as a block statement.

Body:
I wanted to return an object from an arrow function, but the code below was returning undefined. I realized that the curly braces were being interpreted as beginning/ending the function body. What intrigues me is why a: 1 didn’t throw an error.

const foo = () => {a: 1};
foo();
// > undefined

Body:
The issue is that the parser sees a label called 'a' which belongs to the expression statement '1'. Since there's no return statement at all, the returned value is always undefined.

If you wrap the body inside '()' you'll see your object being returned, see below.

const foo = () => ({a: 1});
console.log(foo());

Edit: By adding the parentheses you are forcing the parser to treat the object literal as an expression so that it's not treated as a block statement.


问:
How do I select this check box using Selenium/Java
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

```<code><td class="normal">
    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer
</td>
</code>```

答:
As this checkbox has name, you can use it.

```<code>driver.findElement(By.name("1.48.1.3.2.6.1.1.57.3")).click();
</code>```

If name is not unique and you want find element by following text, you can use

```<code>driver.findElement(By.xpath("//*[contains(., 'Answer Flow Designer')]//preceding-sibling::input")).click();
</code>```

Body:
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer

Body:
As this checkbox has name, you can use it.

driver.findElement(By.name("1.48.1.3.2.6.1.1.57.3")).click();

If name is not unique and you want find element by following text, you can use

driver.findElement(By.xpath("//*[contains(., 'Answer Flow Designer')]//preceding-sibling::input")).click();


问:
how to only allow letters to be used python statment
I'm making a Morse code program:

```<code>def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    for key in phrase:
        print("your word or sentence translated to morse code is : ")
        print(morse_code[key], end = " ")
    if phrase == int or float:
        print("try the input")

    retry()
def retry ():
    main()
retry()
main()
</code>```

How do I print an error if someone enters a number?

答:
how to only allow letters

How do I print an error if someone enters a number?

The second case is covered easily by checking .isdigit on each character as others mentioned. But I will cover the first case.

Start by defining a string of valid characters. Assuming your valid character set is lowercase a-z, this would be the same as string.ascii_lowercase

```<code>import string
valid_characters = string.ascii_lowercase  # a-z

def char_valid(c):
    '''Check if a character is valid, returns True/False'''
    return c in valid_characters

def phrase_valid(phrase):
    '''Check if the phrase is valid, returns True/False'''
    return all(char_valid(char) for char in phrase)

while True:
    user_phrase = input('Enter some characters')
    if phrase_valid(user_phrase):
        # If the phrase is valid, end the loop
        break
    else:
        print('That was not a valid phrase')
        # the loop continues and will ask for input again
</code>```

This pattern works any time you want to keep asking for input until it is valid.

Body:
I'm making a Morse code program:

def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    for key in phrase:
        print("your word or sentence translated to morse code is : ")
        print(morse_code[key], end = " ")
    if phrase == int or float:
        print("try the input")

    retry()
def retry ():
    main()
retry()
main()

How do I print an error if someone enters a number?

Body:
how to only allow letters

How do I print an error if someone enters a number?

The second case is covered easily by checking .isdigit on each character as others mentioned. But I will cover the first case.

Start by defining a string of valid characters. Assuming your valid character set is lowercase a-z, this would be the same as string.ascii_lowercase

import string
valid_characters = string.ascii_lowercase  # a-z

def char_valid(c):
    '''Check if a character is valid, returns True/False'''
    return c in valid_characters

def phrase_valid(phrase):
    '''Check if the phrase is valid, returns True/False'''
    return all(char_valid(char) for char in phrase)

while True:
    user_phrase = input('Enter some characters')
    if phrase_valid(user_phrase):
        # If the phrase is valid, end the loop
        break
    else:
        print('That was not a valid phrase')
        # the loop continues and will ask for input again

This pattern works any time you want to keep asking for input until it is valid.


问:
Composer hangs on exit
The execution of composer (install, update, create-project...) hangs after composer has finished with an blinking cursor and idle cpu - but the batch script won't exit. It is possible to end the process with ctrl+c.

The problem occurs for most of my Laravel and Symfony Projects and seems not to depended on a certain composer.json / .lock

Window 10

XAMPP PHP 7.0.18

Un/reinstalled composer several times.

Examples:

```<code>composer create-project --prefer-dist laravel/laravel testapp
cd testapp
composer install
</code>```

both won't exit

using --profile shows the following result:

```<code>C:\dev\killme>composer install --profile
[7.2MB/0.01s] Loading composer repositories with package information
[7.5MB/0.01s] Installing dependencies (including require-dev) from lock file
[8.5MB/0.04s] Nothing to install or update
[7.7MB/0.05s] Generating optimized autoload files
[9.6MB/7.26s] > Illuminate\Foundation\ComposerScripts::postAutoloadDump
[11.0MB/7.28s] > @php artisan package:discover
[11.1MB/7.69s] Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Package manifest generated successfully.
[10.0MB/7.71s] Memory usage: 9.99MB (peak: 11.53MB), time: 7.71s
- (blinking cursor - batch won't end)
^C cancel batch process (Y/N)? ^C
</code>```

答:
The following change worked for me:

Updating from PHP 7.0.18 to 7.1.11 (XAMPP)

Title: Composer hangs on exit

Body:
The execution of composer (install, update, create-project...) hangs after composer has finished with an blinking cursor and idle cpu - but the batch script won't exit. It is possible to end the process with ctrl+c.

The problem occurs for most of my Laravel and Symfony Projects and seems not to depended on a certain composer.json / .lock

Window 10

XAMPP PHP 7.0.18

Un/reinstalled composer several times.

Examples:

composer create-project --prefer-dist laravel/laravel testapp
cd testapp
composer install

both won't exit

using --profile shows the following result:

C:\dev\killme>composer install --profile
[7.2MB/0.01s] Loading composer repositories with package information
[7.5MB/0.01s] Installing dependencies (including require-dev) from lock file
[8.5MB/0.04s] Nothing to install or update
[7.7MB/0.05s] Generating optimized autoload files
[9.6MB/7.26s] > Illuminate\Foundation\ComposerScripts::postAutoloadDump
[11.0MB/7.28s] > @php artisan package:discover
[11.1MB/7.69s] Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Package manifest generated successfully.
[10.0MB/7.71s] Memory usage: 9.99MB (peak: 11.53MB), time: 7.71s
- (blinking cursor - batch won't end)
^C cancel batch process (Y/N)? ^C


问:
Is it possible to target multiple apps with firebase, but only one will display the notification
I am new with FCM and I am still discovering its possibilities.
I wonder if it is the right tools to do what I want:

I would like to send a notification to all my users, to inform them about new informations for example.
The difficulty is that I want to target all the users of different apps (like 10 apps), and some of them may have more than one of my app installed.

So I do not want a user to have the same notification displayed multiple times (if he installed more than one of my app).

Is it something possible with Firebase?

Thank you

答:
Yes you can! To achieve this, i recomand you using Google Cloud Messaging not FCM. which it's an earlier version. Here is a tutorial on how you can migrate from FCM to GCM.

To achieve this, all your 10 apps must use Firebase and all your users must be Firebase registered users. To send a notification to all devices, would mean then to select all the registration ids from that database, add them in an array and pass them further to GCM.

Note also, that strating with GCM 3.0 it's now possible to send a notification to all devices thanks to topics support. The app must suscribe to one or more topics and the server can send notifications to that topic without specifying individual devices. You can see here Topic Messaging.

Unfortunately, there is no way in which, with a single line of code, to send a notification to all of your users from all your apps. You can only send a notification to all your users that belong only to a single app. If you want that all of yours to get the same message, then you need to consider sending that particular message again, to all users that belong to each app. In this case, if a users is using more then one of your apps, will receieve that message for each app separately.


问:
Onclick function triggered with page load instead of clicks
I have been searching about this issue with onclick triggers that actually trigger with page/window load, but could find a solution for the following.

I need to the id of the latest clicked button, so I did this:

```<code> var lastButtonId = [];//to get the latest Id
// then the onclick statements:
 document.getElementById('traffBut').onclick = sendButtonId('traffButton');
 document.getElementById('convBut').onclick = sendButtonId('convBut');
 document.getElementById('revBut').onclick = sendButtonId('revBut');
 document.getElementById('tranBut').onclick = sendButtonId('tranBut');
//Below the funstion to get the last Id:
 function sendButtonId (clikedButton)
       {
        lastButtonId.splice (0,1,clikedButton);
         console.log(lastButtonId);
       }
</code>```

But the console shows the following on Page Load:
Click here to see console logs

I have tried different ways of doing this but can't get mu head around it,

I hope someone can give me a hint :)

Many thanks
J.

答:
It's because you must pass a function to the onclick attribute, and not a function call. I mean, you must not call the function you want to be called on click, but instead pass a reference to the function.

So, if you want to call sendButtonId, just write:

```<code>document.getElementById('traffBut').onclick = sendButtonId;
</code>```

Though, as you want to add arguments to the function call, you must create a new function that will automatically apply this argument when called. It can be done using .bind, which returns a new function with the given parameters:

```<code>document.getElementById('traffBut').onclick = sendButtonId.bind(this, 'traffButton');
</code>```

Body:
I have been searching about this issue with onclick triggers that actually trigger with page/window load, but could find a solution for the following.

I need to the id of the latest clicked button, so I did this:

 var lastButtonId = [];//to get the latest Id
// then the onclick statements:
 document.getElementById('traffBut').onclick = sendButtonId('traffButton');
 document.getElementById('convBut').onclick = sendButtonId('convBut');
 document.getElementById('revBut').onclick = sendButtonId('revBut');
 document.getElementById('tranBut').onclick = sendButtonId('tranBut');
//Below the funstion to get the last Id:
 function sendButtonId (clikedButton)
       {
        lastButtonId.splice (0,1,clikedButton);
         console.log(lastButtonId);
       }

But the console shows the following on Page Load:
Click here to see console logs

I have tried different ways of doing this but can't get mu head around it,

I hope someone can give me a hint :)

Many thanks
J.

Body:
It's because you must pass a function to the onclick attribute, and not a function call. I mean, you must not call the function you want to be called on click, but instead pass a reference to the function.

So, if you want to call sendButtonId, just write:

document.getElementById('traffBut').onclick = sendButtonId;

Though, as you want to add arguments to the function call, you must create a new function that will automatically apply this argument when called. It can be done using .bind, which returns a new function with the given parameters:

document.getElementById('traffBut').onclick = sendButtonId.bind(this, 'traffButton');


问:
I would like to get rid of dynamic casting. What is the best alternative?
I send data to and from my server.

I create a message, set the type (enum) and the objects that need to be transferred.

The message is sent as a compressed JSON string.
When I receive it I parse the message, instantiate the object and start to fill it. When I need to instantiate the data transferred I use a map that contains the name of the class as a key and a pointer to the constructor as the value.

All this works fine but now I need to consume the message and do what needs to be done with it (send an answer, write to the DB, etc).
What is the best way to do that ? For now, I check the type of the message and get each of the transferred object. But I don't know what class they are (not explicitly).

Should I dynamic cast everything (cost a lot for not much) ? Should I treat the data with the hope it will always be in the same order. Or should I store the objects as a map (with the name or a enum as the key) and cast it correctly then ?

I know that dynamic casting should not be done if possible. But here I am wondering, is it worth it to have a switch from the beginning and create the correct object and feed it the JSON ? For now the entire message is reconstructed dynamically without any problem and my message manager will handle the treatment, should I change that ?

答:
I agree with Peter.

I'd probably use a "sniffer" function that returned an enum class JType mapping the JSON to the associated type of the message.

Then use that JType enum in a switch/case block to call the appropriate factory function which would return a std::unique_ptr.

Failure to parse would throw an exception, rather than return a unique_ptr with a nullptr.

You'd have one factory for each associated class type.

You'd have a sniffer function that would determine what type the JSON represented, returning an enum.

The happy path would be JType e = sniff(message);, and if (e == JType::Foo) std::unique_ptr<Foo_t> foo = FooFactory(message);

Throwing an exception from the factory would only occur in the exceptional case of the message and the factory disagreeing as to what should be in the message.

No list of base_class objects, but the enum class JType would have a 1:1 mapping to the classes.

Think of the JSON as being the state information "dehydrated", and the factory functions "rehydrate" the state data into new objects.  The factory functions could be static class functions as part of the class, or could be freestanding functions.

Hierarchies are for polymorphism, and this isn't that situation.


问:
Why does Canvas::drawArc method draw incorrect angles?
I'm trying to draw a 180° arc within an android view.
In the onDraw method I'm using Canvas::drawArc like this:

```<code>canvas.drawArc(arcRect, 180.0f, 180.0f, false, arcBackgroundPaint);
</code>```

The Paint that is being used has a strokeCap of type BUTT. As you can see in the image below, the ends of the arc do not look quite right. The ends are angled up slightly from the inner diameter to the outer diameter.

Does anyone know why this is happening? Is there a way to fix it other than changing the values passed to drawArc so that it actually draws more than 180 degrees? That seems like a nasty hack that I'd rather avoid.

UPDATE:
As requested, I added code to draw a straight line at the bottom of the arc. I draw the line before I draw the arc so the line is behind. I also made the arc black to get better contrast with the line. Here is the outcome:

Yuck.

Here's one with anti-aliasing turned off for the line and arc...

答:
For anyone else who comes across this I did find a workaround. Instead of using Canvas::drawArc, create a Path, add an arc to it and then draw the path on the canvas. Like this:

```<code>Path arcPath = new Path();
Rect arcRect = ... // Some rect that will contain the arc
path.addArc(arcRect, 180, 180);
canvas.drawPath(arcPath, backgroundArcPaint);
</code>```

Then the rendering problem highlighted no longer occurs.

Since my question was not "how do I fix the problem" but rather "why is this a problem" I am not marking this as the correct answer.

Body:
I'm trying to draw a 180° arc within an android view.
In the onDraw method I'm using Canvas::drawArc like this:

canvas.drawArc(arcRect, 180.0f, 180.0f, false, arcBackgroundPaint);

The Paint that is being used has a strokeCap of type BUTT. As you can see in the image below, the ends of the arc do not look quite right. The ends are angled up slightly from the inner diameter to the outer diameter.

Does anyone know why this is happening? Is there a way to fix it other than changing the values passed to drawArc so that it actually draws more than 180 degrees? That seems like a nasty hack that I'd rather avoid.

UPDATE:
As requested, I added code to draw a straight line at the bottom of the arc. I draw the line before I draw the arc so the line is behind. I also made the arc black to get better contrast with the line. Here is the outcome:

Yuck.

Here's one with anti-aliasing turned off for the line and arc...

Body:
For anyone else who comes across this I did find a workaround. Instead of using Canvas::drawArc, create a Path, add an arc to it and then draw the path on the canvas. Like this:

Path arcPath = new Path();
Rect arcRect = ... // Some rect that will contain the arc
path.addArc(arcRect, 180, 180);
canvas.drawPath(arcPath, backgroundArcPaint);

Then the rendering problem highlighted no longer occurs.

Since my question was not "how do I fix the problem" but rather "why is this a problem" I am not marking this as the correct answer.


问:
SQL search in the same order as requested and showing not found items
I want to do a special query for SQL but I'm not able to get the wanted result.

My basic query is:

```<code>select * from TABLE_NAME where COLUMN_NAME_1 in ('ABC1', 'ABC98', 'ABC97', 'ABC2', 'ABC3')
</code>```

Imagine that the item 'ABC1' is not in the table. I would like my query to show it. In addition I would like that my query shows the items in the same order I asked (ABC1, ABC98, ABC97, and so on).

I attach an image where you'll understand better what I want.

Thanks in advance

答:
First of all you need a table of the values to show along with their desired position. You can create this on the fly in the FROM clause. Then outer join your table:

```<code>select keys.name, t.column_name_2, t.column_name_3, t.column_name_4
from
(
  select 'ABC1' as name, 1 as sortkey
  union all
  select 'ABC98' as name, 2 as sortkey
  union all
  select 'ABC97' as name, 3 as sortkey
  union all
  select 'ABC2' as name, 4 as sortkey
  union all
  select 'ABC3' as name, 5 as sortkey
) as keys
left join table_name t on t.column_name_1 = keys.name
order by keys.sortkey;
</code>```

Body:
I want to do a special query for SQL but I'm not able to get the wanted result.

My basic query is:

select * from TABLE_NAME where COLUMN_NAME_1 in ('ABC1', 'ABC98', 'ABC97', 'ABC2', 'ABC3')

Imagine that the item 'ABC1' is not in the table. I would like my query to show it. In addition I would like that my query shows the items in the same order I asked (ABC1, ABC98, ABC97, and so on).

I attach an image where you'll understand better what I want.

Thanks in advance

Body:
First of all you need a table of the values to show along with their desired position. You can create this on the fly in the FROM clause. Then outer join your table:

select keys.name, t.column_name_2, t.column_name_3, t.column_name_4
from
(
  select 'ABC1' as name, 1 as sortkey
  union all
  select 'ABC98' as name, 2 as sortkey
  union all
  select 'ABC97' as name, 3 as sortkey
  union all
  select 'ABC2' as name, 4 as sortkey
  union all
  select 'ABC3' as name, 5 as sortkey
) as keys
left join table_name t on t.column_name_1 = keys.name
order by keys.sortkey;


问:
Storing Java Classes in Database and then Casting to them
Use-Case: Accept User Input for numerous data types and validate the user input on the back-end with Java.

Database:

```<code>Table 1 - Attribute Declarations

Id | Attribute Name  | Attribute Data Type
-----------------------------------------
1  | My Numeric Type | Long.class
2  | My String Type  | String.class
3  | Favorite Letter | Character.class

Table 2 - Attribute Assignments

Id | Fk | Attribute Value [Varchar2]
--------------------------
66 |  1 | 1234
67 |  2 | Some Word
68 |  3 | A
</code>```

Problem: How do I take a value like "1234" and cast that into Long.class without knowing that it's a Long.class. I don't want to hard-code a bunch of if-else blocks because then if I need to add a new class to my DB I will need to do a code change to support it.

Pseduo:

```<code>public static void validate(final Class<?> dbClass, String attrValue){
    try {
        dbClass.cast(attrValue);

    } catch(Exception e){
      LOGGER.error("ERROR: This Attribute Value is not an "
                 + "instance of Class: {} | {}", dbClass.getSimpleName(), e);
      throw e;
    }
}
</code>```

Current Issue: is java.lang.String cannot be cast to a Long. I know that I can do this using Long.parseLong(string), but is there a generic way I can do it for ANY class defined in my DB?

答:
You could use Class.forName(<Attribute Data Type>);
and then call the string version of the constructor of that class to create a new instance of the object.  This will only work if the classes you are using have a String constructor (which Long and String does - but Character doesn't).

Do you need to store the Attribute value as a varchar in the DB?  Could you not store the serialised Java object?  Then you can just de-serialise it straight from the DB and you have the correct object already created.

Body:
Use-Case: Accept User Input for numerous data types and validate the user input on the back-end with Java.

Database:

Table 1 - Attribute Declarations

Id | Attribute Name  | Attribute Data Type
-----------------------------------------
1  | My Numeric Type | Long.class
2  | My String Type  | String.class
3  | Favorite Letter | Character.class

Table 2 - Attribute Assignments

Id | Fk | Attribute Value [Varchar2]
--------------------------
66 |  1 | 1234
67 |  2 | Some Word
68 |  3 | A

Problem: How do I take a value like "1234" and cast that into Long.class without knowing that it's a Long.class. I don't want to hard-code a bunch of if-else blocks because then if I need to add a new class to my DB I will need to do a code change to support it.

Pseduo:

public static void validate(final Class<?> dbClass, String attrValue){
    try {
        dbClass.cast(attrValue);

    } catch(Exception e){
      LOGGER.error("ERROR: This Attribute Value is not an "
                 + "instance of Class: {} | {}", dbClass.getSimpleName(), e);
      throw e;
    }
}

Current Issue: is java.lang.String cannot be cast to a Long. I know that I can do this using Long.parseLong(string), but is there a generic way I can do it for ANY class defined in my DB?


问:
Symbol MC30xx Barcode reader device - How to transfer data to PC
I'm developing application for Symbol MC3000 device. It's running Windows CE 4.2 Professional. Application is simple data driven app, which stores information about products in store.

My client wants to communicate with the device through serial and USB interface and read data stored in application. And here is where i'm stucked.

He wan't to send commands to device like over console:

RES:GET:DATA?
 - to receive all data from device in spec.format

RES:GET:VN?
 - to get version of software.

and so on.

Serial line is not a big deal. But how would you implement this via the USB port. (with no active sync, or network sockets)

(the device might be connected to USB on linux or windows machine, and those terminal commands should work)

Od do you have any ideas how to design this problem?

can you please guys recommend me some literature, or materials to read?

Thank you very much.

Alef

答:
It would be difficult to build a USB serial link between the device and a PC. For a Windows Platform you could use RAPI as a work around. The device would connect to a PC through ActiveSync. Then using RAPI you can (among others), read the registry of the remote device, start the execution of an application in the device, transfer files between the two.

I suppose that if you don't want real-time transfer of data this will work. For Linux, I don't know if there is a RAPI SDK available. In Windows you could use OpenNetCF's RAPI SDK, which will make your life a lot easier.

OwnerDisplayName: Alef

OwnerDisplayName: kgiannakakis


问:
Git - Forking without Github
Is the function of "forking" specific to github? or is there a purely git process for creating "copied" child repositories that can pull updates from the parent? If so, how?

EDIT : I must be confused about what git clone does then.  It was my understanding that git clone is what I do on my machine to get a local copy of the repository to make changes to, commit, and push from.  We are currently hosting our repos with gitosis.  So if I wanted to accompish a 'fork' I would clone the repository on the gitosis server itself (at the origin)?  Would that create a new git address?

答:
You probably don't want to actually do this.  Branches in git are very nice and lightweight, and there really isn't a reason why you shouldn't just make a branch in the repository that you have right now.   The only reason I can think of to do this with a gitosis repository is in order to make access control interesting, if you have a continuous deploy or something which pulls from one gitosis repository and you want to give commit access to the same code but don't want them to be able to write to the one that is deployed.   For all other uses, you should just make a branch with git branch and do all your work on the branch.  Alternately you might want to clone a github repository and then have a team work on it within your central gitosis architecture.

Given that pre-warning, the easiest way to create a "fork" in the way that you describe, is to make a separate repository on the gitosis server.  So set up another repository with the other name - for example if your original repository is gitosis@server:repo1.git you would set up another one at gitosis@server:repo1-fork.git.   Add whatever users you want to have access.

Then you would clone the repository: git clone gitosis@server:repo1.git which puts a full copy of the repo into ./repo1.   To copy it from your local version to the forked repository, you can do a git push gitosis@server:repo-fork.git --mirror.

Title: Git - Forking without Github


问:
centering CSS: margin-left and -right auto, but funny results
You can view the page at http://led.dlugosz.com/.※  I want to make the "Gallery" section centered in the available space, not flush left.

So, I added rules

```<code>margin-left: auto;
margin-right: auto;
</code>```

and it seemed to work just right.  But, when I did the same thing on another page, it didn't work at all, and I can't find any difference.  Then, playing around with this page some more, I find that at different window widths it works, doesn't work, or does something very odd.  What's going on here?  More to the point, how can I accomplish this effect?

※ I updated the page and eventually removed it.

答:
margin-left :auto and margin-right:auto will center the element if you set display: block and specify the width of the element then the element align to center.

or else

```<code>margin: 0 auto;
width: 100px;
display: block;
</code>```

Body:
You can view the page at http://led.dlugosz.com/.※  I want to make the "Gallery" section centered in the available space, not flush left.

So, I added rules

margin-left: auto;
margin-right: auto;

and it seemed to work just right.  But, when I did the same thing on another page, it didn't work at all, and I can't find any difference.  Then, playing around with this page some more, I find that at different window widths it works, doesn't work, or does something very odd.  What's going on here?  More to the point, how can I accomplish this effect?

※ I updated the page and eventually removed it.

Body:
margin-left :auto and margin-right:auto will center the element if you set display: block and specify the width of the element then the element align to center.

or else

margin: 0 auto;
width: 100px;
display: block;


问:
Writing from Future of CachedThreadPool. Is my implementation incorrect?
I need help with my multithreading code.
I have a callable class which returns a value. I have a cachedThreadPool to submit ~60,000 tasks. I collect all the Futures in a List. After the ExecutiveService has shutdown, I loop through the list of Futures, and write the returned values using a bufferedWriter. Is this correct way of implementation?

```<code>ExecutorService execService = Executors.newCachedThreadPool();
List<Future<ValidationDataObject<String, Boolean>>> futureList = new ArrayList<>();
for (int i = 0; i < emailArrayList.size(); i++) {
    String emailAddress = emailArrayList.get(i);
    ValidateEmail validateEmail = new ValidateEmail(emailAddress);
    Future<ValidationDataObject<String, Boolean>> future =
         execService.submit(validateEmail);
    futureList.add(future);
}

execService.shutdown();

for (Future<ValidationDataObject<String, Boolean>> future: futureList) {
    ValidationDataObject<String, Boolean> validationObject = future.get();
    bufferedWriter.write(validationObject.getEmailAddress() + "|"
             + validationObject.getIsValid());
    bufferedWriter.newLine();
    bufferedWriter.flush();
}

if (execService.isTerminated()) bufferedWriter.close();
</code>```

Should I using synchronized block for the bufferedWriter? I am thinking, It doesn't need to be synchronized because, I am using the bufferedWriter from the main Thread, right?

答:
Apart from the fact, that executor.shutdown() will most likely not do, what you believe it to do (it simply stops the Executor from accepting new Tasks, it will not wait for all tasks to terminate), your code looks fine.

You are right, there is no need for synchronization with respect to the writer, as you access it only single threaded.

There are things, that can be improved, though. Firstly, you are not doing a lot of Exception handling. Future.get() will throw an ExecutionException, if the Callable hits an Exception.

I'm not certain, how large the deviations in execution-time of your Callables are. Assume, there are notable deviations look at the following case: Say we submit Callables A, B and C, you receive FutA, FutB and FutC. Calling the get methods will block until the calculation behind the Future is finished. In your setting, you might be waiting for FutA to complete, while FutB/FutC might already be finished and ready for writing. Worst case here is, that processing of A will delay writing for all 60000 tasks.

I think, I would go for another approach, where every Callable gets the reference to the same ConcurrentLinkedQueue and instead of returning the result via Future writes the result into that queue. In this scenario, the ordering of the result is not dependent on the ordering of the Callables but on the time, the Callables finish execution. Whether or not this results in a speedup depends on your setting (especially time to write result and deviation in execution times of the Callables).

Body:
I need help with my multithreading code.
I have a callable class which returns a value. I have a cachedThreadPool to submit ~60,000 tasks. I collect all the Futures in a List. After the ExecutiveService has shutdown, I loop through the list of Futures, and write the returned values using a bufferedWriter. Is this correct way of implementation?

ExecutorService execService = Executors.newCachedThreadPool();
List<Future<ValidationDataObject<String, Boolean>>> futureList = new ArrayList<>();
for (int i = 0; i < emailArrayList.size(); i++) {
    String emailAddress = emailArrayList.get(i);
    ValidateEmail validateEmail = new ValidateEmail(emailAddress);
    Future<ValidationDataObject<String, Boolean>> future =
         execService.submit(validateEmail);
    futureList.add(future);
}

execService.shutdown();

for (Future<ValidationDataObject<String, Boolean>> future: futureList) {
    ValidationDataObject<String, Boolean> validationObject = future.get();
    bufferedWriter.write(validationObject.getEmailAddress() + "|"
             + validationObject.getIsValid());
    bufferedWriter.newLine();
    bufferedWriter.flush();
}

if (execService.isTerminated()) bufferedWriter.close();

Should I using synchronized block for the bufferedWriter? I am thinking, It doesn't need to be synchronized because, I am using the bufferedWriter from the main Thread, right?


问:
Bash addition by the first column, if data in second column is the same
I have a list with delimiters |

```<code>40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2
</code>```

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

```<code>40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11
</code>```

How you can see, we have counted the numbers from first column.

答:
Short GNU datamash + awk solution:

```<code>datamash -st'|' -g2,3 sum 1 <file | awk -F'|' '{print $3,$1,$2}' OFS='|'
</code>```

g2,3 - group by the 2nd and 3rd field (i.e. by IP address and user id)

sum 1 - sum the 1st field values within grouped records

The output:

```<code>40|192.168.1.2|user4
109|192.168.1.25|user2
118|192.168.1.3|user11
58|192.168.1.55|user3
</code>```

Body:
I have a list with delimiters |

40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11

How you can see, we have counted the numbers from first column.

Body:
Short GNU datamash + awk solution:

datamash -st'|' -g2,3 sum 1 <file | awk -F'|' '{print $3,$1,$2}' OFS='|'

g2,3 - group by the 2nd and 3rd field (i.e. by IP address and user id)

sum 1 - sum the 1st field values within grouped records

The output:

40|192.168.1.2|user4
109|192.168.1.25|user2
118|192.168.1.3|user11
58|192.168.1.55|user3


问:
Image source change on hover not working as expected
I'm trying to create an image that plays a GIF on hover. I found some jquery on this site that supposedly works but for some reason isn't working for me. Any ideas as to why?

This is the html and javascript:

$(document).ready(function(){

//animate image on hover
    $(document).ready(function()
    {
        $("#imgAnimate").hover(
            function()
            {
                $(this).attr("src", "Videos/Mathew-Demo.gif");
            },
            function()
            {
                $(this).attr("src", "Static shots/Mathew-Demo.png");
            });
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="team.css">
  <script src="team.js" type="text/javascript">
  <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">

</body>

</html></code>```

There is probably a very simple reason why not.

答:
You have a documentReady in a documentReady which has no use (documentReady waits until the DOM is ready, the 2nd check is double).

Also, you can use the .src property directly, resulting in the following code:

```<code>$(document).ready(function()
{
    $("#imgAnimate").hover(
        function(){
            this.src = "Videos/Mathew-Demo.gif";
        },
        function(){
            this.src = "Static shots/Mathew-Demo.png";
        }
    );
});
</code>```

Apart from that, your code seems fine. Are you sure jQuery is loaded? Your snippet does not include it. Here is a snippet with working example.

Body:
I'm trying to create an image that plays a GIF on hover. I found some jquery on this site that supposedly works but for some reason isn't working for me. Any ideas as to why?

This is the html and javascript:

$(document).ready(function(){

//animate image on hover
    $(document).ready(function()
    {
        $("#imgAnimate").hover(
            function()
            {
                $(this).attr("src", "Videos/Mathew-Demo.gif");
            },
            function()
            {
                $(this).attr("src", "Static shots/Mathew-Demo.png");
            });
    });

});

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="team.css">

There is probably a very simple reason why not.

Body:
You have a documentReady in a documentReady which has no use (documentReady waits until the DOM is ready, the 2nd check is double).

Also, you can use the .src property directly, resulting in the following code:

$(document).ready(function()
{
    $("#imgAnimate").hover(
        function(){
            this.src = "Videos/Mathew-Demo.gif";
        },
        function(){
            this.src = "Static shots/Mathew-Demo.png";
        }
    );
});

Apart from that, your code seems fine. Are you sure jQuery is loaded? Your snippet does not include it. Here is a snippet with working example.


问:
Ubuntu 16.04 apt-get not working through proxy
In Ubuntu 14.04, in order to use some commands in terminal (like apt-get) trough the company proxy, I need to do the following changes, beyond System Settings > Network > Network proxy > "Apply system wide" (shame on you, Ubuntu)

```<code>/etc/environment (actually this is the only file modified by System Settings)
http_proxy="http://[webproxy]:[port]/"
https_proxy="https://[webproxy]:[port]/"
ftp_proxy="ftp://[webproxy]:[port]/"
socks_proxy="socks://[webproxy]:[port]/"

/etc/profile
export http_proxy=http://[username]:[password]@[webproxy]:[port]
export https_proxy=http://[username]:[password]@[webproxy]:[port]
export ftp_proxy=http://[username]:[password]@[webproxy]:[port]

sudo visudo
Defaults        env_reset
Defaults        env_keep = "http_proxy https_proxy ftp_proxy DISPLAY XAUTHORITY"

/etc/apt/apt.conf
Acquire::http::proxy "http://[username]:[password]@[webproxy]:[port]/";
Acquire::https::proxy "https://[username]:[password]@[webproxy]:[port]/";
Acquire::ftp::proxy "ftp://[username]:[password]@[webproxy]:[port]/";
Acquire::socks::proxy "socks://[username]:[password]@[webproxy]:[port]/";

or the same changes in
/etc/apt/apt.conf.d/95proxies
</code>```

I think that at least the following command (from here)

```<code>sudo http_proxy='http://[username]:[password]@[webproxy]:[port]' apt-get update
</code>```

should work, right?

That's what I remember right now. Not even sure if all of them are really necessary. I did all these changes in Ubuntu 16.04, though, but still can't make sudo apt-get update work through the same proxy (another computer in the same room). Got

```<code>Temporary failure resolving '[webproxy]'
</code>```

What am I missing?

答:
Create a new empty conf file: $ sudo vi /etc/apt/apt.conf

Add this line to the file if you are using http proxy else https of  ftp:

Acquire::http::Proxy "http://user:pass@proxy_host:port";

If you don't have a usename and password for your proxy then write:

Acquire::http::Proxy "http://proxy_host:port";

Note: don't miss the semicolon at the end of line.

Body:
In Ubuntu 14.04, in order to use some commands in terminal (like apt-get) trough the company proxy, I need to do the following changes, beyond System Settings > Network > Network proxy > "Apply system wide" (shame on you, Ubuntu)

/etc/environment (actually this is the only file modified by System Settings)
http_proxy="http://[webproxy]:[port]/"
https_proxy="https://[webproxy]:[port]/"
ftp_proxy="ftp://[webproxy]:[port]/"
socks_proxy="socks://[webproxy]:[port]/"

/etc/profile
export http_proxy=http://[username]:[password]@[webproxy]:[port]
export https_proxy=http://[username]:[password]@[webproxy]:[port]
export ftp_proxy=http://[username]:[password]@[webproxy]:[port]

sudo visudo
Defaults        env_reset
Defaults        env_keep = "http_proxy https_proxy ftp_proxy DISPLAY XAUTHORITY"

/etc/apt/apt.conf
Acquire::http::proxy "http://[username]:[password]@[webproxy]:[port]/";
Acquire::https::proxy "https://[username]:[password]@[webproxy]:[port]/";
Acquire::ftp::proxy "ftp://[username]:[password]@[webproxy]:[port]/";
Acquire::socks::proxy "socks://[username]:[password]@[webproxy]:[port]/";

or the same changes in
/etc/apt/apt.conf.d/95proxies

I think that at least the following command (from here)

sudo http_proxy='http://[username]:[password]@[webproxy]:[port]' apt-get update

should work, right?

That's what I remember right now. Not even sure if all of them are really necessary. I did all these changes in Ubuntu 16.04, though, but still can't make sudo apt-get update work through the same proxy (another computer in the same room). Got

Temporary failure resolving '[webproxy]'

What am I missing?


问:
Debugging keyboard events like 'Ctrl+Up Arrow'
I want to debug a part of a program that is intended to respond to keyboard input such as Ctrl+↑.

So, I put a breakpoint in the code in the area interest. However, once I press the Ctrl key the program jumps to that breakpoint. This happens before I have pressed an arrow key, so I'm finding this situation difficult to debug.

So, how can I debug a multi-key input event such as Ctrl+↑?

答:
You can use System.Diagnostics.Debug.WriteLine to write debug information to the trace listeners in the Listeners collection.

Example:

```<code>private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.Up)
        System.Diagnostics.Debug.WriteLine("Up with control have pressed");
}
</code>```

In the Visual Studio menu bar, select View->Output to see the output.

Body:
You can use System.Diagnostics.Debug.WriteLine to write debug information to the trace listeners in the Listeners collection.

Example:

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.Up)
        System.Diagnostics.Debug.WriteLine("Up with control have pressed");
}

In the Visual Studio menu bar, select View->Output to see the output.


问:
pyspark.sql.utils.IllegalArgumentException: "Error while instantiating 'org.apache.spark.sql.hive.HiveSessionStateBuild in windows 10
I have installed spark 2.2 with winutils in windows 10.when i am going to run pyspark i am facing bellow exception

```<code>pyspark.sql.utils.IllegalArgumentException: "Error while instantiating 'org.apache.spark.sql.hive.HiveSessionStateBuilder'
</code>```

I have already tried permission 777 commands in tmp/hive folder as well.but it is not working for now

```<code>winutils.exe chmod -R 777 C:\tmp\hive
</code>```

after applying this the problem remains same. I am using pyspark 2.2 in my windows 10.
Her is spark-shell env

Here is pyspark shell

Kindly help me to figure out
Thankyou

答:
I had the same problem using the command 'pyspark' as well as 'spark-shell' (for scala) in my mac os with apache-spark 2.2. Based on some research I figured its because of my JDK version 9.0.1 which does not work well with Apache-Spark. Both errors got resolved by switching back from Java JDK 9 to JDK 8.

Maybe that might help with your windows spark installation too.

Body:
I have installed spark 2.2 with winutils in windows 10.when i am going to run pyspark i am facing bellow exception

pyspark.sql.utils.IllegalArgumentException: "Error while instantiating 'org.apache.spark.sql.hive.HiveSessionStateBuilder'

I have already tried permission 777 commands in tmp/hive folder as well.but it is not working for now

winutils.exe chmod -R 777 C:\tmp\hive

after applying this the problem remains same. I am using pyspark 2.2 in my windows 10.
Her is spark-shell env

Here is pyspark shell

Kindly help me to figure out
Thankyou


问:
GCC does not complain about re-definition of external variable?
This simple code (MCVE):

```<code>#include <stdio.h>

int a = 3;
int main(){
    printf("%d\n", a);
    return 0;
}
int a; // This line
</code>```

To my surprise, GCC (MinGW GCC 4.8.2, 4.9.2 and 6.3.0) does not give any error, not even warnings about the marked line! However it does if I assign a value to a at its second definition.

More strangely, g++ tells me that the second re-definition is an error, but gcc doesn't.

Isn't it supposed to be a re-definition of an existing variable because there's no keyword extern?

答:
From the C Standard (6.9.2 External object definitions)

1 If the declaration of an identifier for an object has file scope and
  an initializer, the declaration is an external definition for the
  identifier.

and

2 A declaration of an identifier for an object that has file scope
  without an initializer, and without a storage-class specifier or with
  the storage-class specifier static, constitutes a tentative
  definition. If a translation unit contains one or more tentative
  definitions for an identifier, and the translation unit contains no
  external definition for that identifier, then the behavior is exactly
  as if the translation unit contains a file scope declaration of that
  identifier, with the composite type as of the end of the translation
  unit, with an initializer equal to 0.

And there is an example in the C Standard

```<code>int i1 = 1; // definition, external linkage
//...
int i1; // valid tentative definition, refers to previous
</code>```

So in your program this one declaration

```<code>int a = 3;
</code>```

is an external definition for the identifier a

and this one

```<code>int a;
</code>```

is a tentative definition that refers to the previous external definition of the identifier.

If to use an initializer in the second declaration then you will get two external definitions for the identifier and the compiler will issue an error because only one external definition can exist.

Take into account that C and C++ differ relative to this context,

From the C++ Standard (C.1.2 Clause 6: basic concepts)

6.1

Change: C++ does not have “tentative definitions” as in C. E.g., at
  file scope,

```<code>int i;
int i;
</code>```

is valid in C, invalid in C++.

Body:
This simple code (MCVE):

#include <stdio.h>

int a = 3;
int main(){
    printf("%d\n", a);
    return 0;
}
int a; // This line

To my surprise, GCC (MinGW GCC 4.8.2, 4.9.2 and 6.3.0) does not give any error, not even warnings about the marked line! However it does if I assign a value to a at its second definition.

More strangely, g++ tells me that the second re-definition is an error, but gcc doesn't.

Isn't it supposed to be a re-definition of an existing variable because there's no keyword extern?

Body:
From the C Standard (6.9.2 External object definitions)

1 If the declaration of an identifier for an object has file scope and
  an initializer, the declaration is an external definition for the
  identifier.

and

2 A declaration of an identifier for an object that has file scope
  without an initializer, and without a storage-class specifier or with
  the storage-class specifier static, constitutes a tentative
  definition. If a translation unit contains one or more tentative
  definitions for an identifier, and the translation unit contains no
  external definition for that identifier, then the behavior is exactly
  as if the translation unit contains a file scope declaration of that
  identifier, with the composite type as of the end of the translation
  unit, with an initializer equal to 0.

And there is an example in the C Standard

int i1 = 1; // definition, external linkage
//...
int i1; // valid tentative definition, refers to previous

So in your program this one declaration

int a = 3;

is an external definition for the identifier a

and this one

int a;

is a tentative definition that refers to the previous external definition of the identifier.

If to use an initializer in the second declaration then you will get two external definitions for the identifier and the compiler will issue an error because only one external definition can exist.

Take into account that C and C++ differ relative to this context,

From the C++ Standard (C.1.2 Clause 6: basic concepts)

6.1

Change: C++ does not have “tentative definitions” as in C. E.g., at
  file scope,

int i;
int i;

is valid in C, invalid in C++.


问:
How to unzip a file using batch?
I have coded a batch file to unzip a file as follows:

```<code>unzip images.zip

exit
</code>```

But its not working. Its for creating exe file using IExpress.

What is the code to unzip a file?

答:
The other answers require additional software to be installed. Here is a solution using PowerShell (included in Windows 7 and upwards):

```<code>powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"
</code>```

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16 to CopyHere is a "yes to all" for possible questions while extraction.

Title: How to unzip a file using batch?

Body:
I have coded a batch file to unzip a file as follows:

unzip images.zip

exit

But its not working. Its for creating exe file using IExpress.

What is the code to unzip a file?

Body:
The other answers require additional software to be installed. Here is a solution using PowerShell (included in Windows 7 and upwards):

powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16 to CopyHere is a "yes to all" for possible questions while extraction.


问:
How to wrap legend items in highcharts?
I have a big problem using highcharts, because I have been trying for hours  to wrap legend items if they very long.

I have tried to set legend and legend item width, but my text still get out from a legend. Only thing that I found is to change highcharts.src.js but I think that's not a way to solve this problem.

Here my code:

```<code><script type="text/javascript">
  var chart;
  $(document).ready(function() {
    chart = new Highcharts.Chart({
      chart: {
        renderTo: 'graph_container',
        defaultSeriesType: 'line',
        zoomType: 'y',
        marginRight: 130,
        marginBottom: $ {
          marginBottom
        }
      },
      title: {
        x: -10,
        text: null
      },
      xAxis: {
        title: {
          text: '<fmt:message key="html.time" bundle="${msg}"/>',
          align: 'high'
        },
        categories: [$ {
          years
        }]
      },
      yAxis: {
        title: {
          text: '<fmt:message key="html.value" bundle="${msg}"/>',
          align: 'high'
        },
        plotLines: [{
          value: 0,
          width: 1,
          color: '#808080'
        }]
      },
      tooltip: {
        style: {
          fontSize: '9pt',
          width: '400px', //,
          wrap: 'hard'
        },
        formatter: function() {
          return '<b>' + this.series.name + '<br>' +
            +this.x + ': ' + this.y + '</b>';
        }
      },
      legend: {
        layout: 'vertical',
        width: 600,
        floating: true,
        align: 'center',
        verticalAlign: 'bottom',
        borderWidth: 1,
        itemWidth: '500px'

      },
      credits: {
        enabled: false
      },
      exporting: {
        enabled: false
      },
      series: [ <
        c: forEach items = "${graphValues}"
        var = "value"
        varStatus = "counter" >
        <
        c: if test = "${counter.count != 1}" > , < /c:if> {
          name: '${value.name}',
          data: $ {
            value.jsonData
          }
        } <
        /c:forEach>
      ]
    });

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

答:
as a note, in 2017 you can use textOverflow option

legend.itemStyle

CSS styles for each legend item. Only a subset of CSS is supported,
  notably those options related to text. The default textOverflow
  property makes long texts truncate. Set it to null to wrap text
  instead.

Title: How to wrap legend items in highcharts?


问:
Crash if I try to copy uncompressed filtering_istream to stringstream
I want to uncompress a file and write its content into a stringstream.

This is the code I tried:

```<code>string readGZipLog () {
 try {
      using namespace boost::iostreams;
      ifstream file(currentFile.c_str(), std::ios_base::in | std::ios_base::binary);
      boost::iostreams::filtering_istream in;
      in.push(gzip_decompressor());
      in.push(file);
      std::stringstream strstream;
      boost::iostreams::copy(in, strstream);
      return strstream.str();
 } catch (std::exception& e) {
      cout << e.what() << endl;
 }
}

void writeGZipLog (char* data) {
    try {
      using namespace boost::iostreams;
      std::ofstream file( currentFile.c_str(), std::ios_base::out |  std::ios_base::binary );
      boost::iostreams::filtering_ostream out;
      out.push( gzip_compressor() );
      out.push(file);
      std::stringstream strstream;
      strstream << data;
      boost::iostreams::copy( strstream, data );
    } catch (std::exception& e) {
      cout << e.what() << endl;
    }
 }
</code>```

It compiles without any warnings (and of course errors) but the function readGZipLog() crashes while running:

```<code>gzip error
./build: line 3: 22174 Segmentation fault      ./test
</code>```

./build is the script that compiles and starts the application ./test automatically

I checked the file: It contains something, but I can't ungzip it using gunzip. So I am not sure whether the compression worked properly and if this has something to do with the gzip error thrown by Boost.

Can you give me a hit where the error(s) is(/are)?

Thanks for your help!

Paul

答:
after a lot of research and trying I finally found a way how to handle (de)compression correctly.

This is the code that works for me without any problems (with gzip and bzip2):

```<code>string readGZipLog () {
    using namespace boost::iostreams;
    using namespace std;
   try {
      ifstream file(currentFile.c_str(), ios_base::in | ios_base::binary);
      boost::iostreams::filtering_istream in;
      in.push(gzip_decompressor());
      in.push(file);
      stringstream strstream;
      boost::iostreams::copy(in, strstream);
      return strstream.str();
    } catch (const gzip_error& exception) {
      cout << "Boost Description of Error: " << exception.what() << endl;
      return "err";
    }
}

bool writeGZipLog (char* data) {
    using namespace boost::iostreams;
    using namespace std;
    try {
      std::ofstream file( currentFile.c_str(), std::ios_base::app );
      boost::iostreams::filtering_ostream out;
      out.push( gzip_compressor() );
      out.push(file);
      stringstream strstream;
      strstream << data;
      boost::iostreams::copy(strstream, out);
      return true;
    } catch (const gzip_error& exception) {
       cout << "Boost Description of Error: " << exception.what() << endl;
       return false;
    }
}
</code>```

What I can say is that I did some errors that were not necessary and I just found by looking at the code again many hours later. boost::iostreams::copy( std::stringstream , char* ); for example will even fail if 1 + 1 was 3.

I hope that this code piece will help somebody as it helped me.

Paul :)

Body:
I want to uncompress a file and write its content into a stringstream.

This is the code I tried:

string readGZipLog () {
 try {
      using namespace boost::iostreams;
      ifstream file(currentFile.c_str(), std::ios_base::in | std::ios_base::binary);
      boost::iostreams::filtering_istream in;
      in.push(gzip_decompressor());
      in.push(file);
      std::stringstream strstream;
      boost::iostreams::copy(in, strstream);
      return strstream.str();
 } catch (std::exception& e) {
      cout << e.what() << endl;
 }
}

void writeGZipLog (char* data) {
    try {
      using namespace boost::iostreams;
      std::ofstream file( currentFile.c_str(), std::ios_base::out |  std::ios_base::binary );
      boost::iostreams::filtering_ostream out;
      out.push( gzip_compressor() );
      out.push(file);
      std::stringstream strstream;
      strstream << data;
      boost::iostreams::copy( strstream, data );
    } catch (std::exception& e) {
      cout << e.what() << endl;
    }
 }

It compiles without any warnings (and of course errors) but the function readGZipLog() crashes while running:

gzip error
./build: line 3: 22174 Segmentation fault      ./test

./build is the script that compiles and starts the application ./test automatically

I checked the file: It contains something, but I can't ungzip it using gunzip. So I am not sure whether the compression worked properly and if this has something to do with the gzip error thrown by Boost.

Can you give me a hit where the error(s) is(/are)?

Thanks for your help!

Paul

Body:
after a lot of research and trying I finally found a way how to handle (de)compression correctly.

This is the code that works for me without any problems (with gzip and bzip2):

string readGZipLog () {
    using namespace boost::iostreams;
    using namespace std;
   try {
      ifstream file(currentFile.c_str(), ios_base::in | ios_base::binary);
      boost::iostreams::filtering_istream in;
      in.push(gzip_decompressor());
      in.push(file);
      stringstream strstream;
      boost::iostreams::copy(in, strstream);
      return strstream.str();
    } catch (const gzip_error& exception) {
      cout << "Boost Description of Error: " << exception.what() << endl;
      return "err";
    }
}

bool writeGZipLog (char* data) {
    using namespace boost::iostreams;
    using namespace std;
    try {
      std::ofstream file( currentFile.c_str(), std::ios_base::app );
      boost::iostreams::filtering_ostream out;
      out.push( gzip_compressor() );
      out.push(file);
      stringstream strstream;
      strstream << data;
      boost::iostreams::copy(strstream, out);
      return true;
    } catch (const gzip_error& exception) {
       cout << "Boost Description of Error: " << exception.what() << endl;
       return false;
    }
}

What I can say is that I did some errors that were not necessary and I just found by looking at the code again many hours later. boost::iostreams::copy( std::stringstream , char* ); for example will even fail if 1 + 1 was 3.

I hope that this code piece will help somebody as it helped me.

Paul :)


问:
Spring test: how to 'pass' model into controller post method
I'm working in Spring Boot and am trying to write an integration test for a controller that looks like this:

```<code>public String pagerequestSubmit(@ModelAttribute Pagerequest pagerequest, Model model) {
...
 }
</code>```

Now I'm trying to write an integration test for this controller like this:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes=PageAnalyzerInSpringApplication.class)
public class PagerequestControllerIntegrationTest {

@Autowired
PagerequestController pagerequestController;

@Test
public void testHappyPath() {

    Pagerequest mockPageRequest = new Pagerequest();
    mockPageRequest.setUrl("https://www.somedomain.com/");
    ....

    String outcome = pagerequestController.pagerequestSubmit(mockPageRequest);

    assertThat(outcome, is(equalTo("result")));

}
</code>```

I don't have any problem doing the 'mock pagerequest' and passing it into the post method, so I got that far, but the above test does not work because I get:

"The method pagerequestSubmit(Pagerequest, Model) in the type PagerequestController is not applicable for the arguments (Pagerequest)"

Which makes sense because I'm not passing in any argument of the type Model
and I'm completely stuck on how to do that.

I've tried to instantiate a Model, which doesn't work, creating a fake Model, which also didn't work, and passing in a Model variable that was null, which at least gets the test running, but then throws a null pointer exception when the model in used in the controller.

Any ideas on how to resolve this?

Thanks in advance!

答:
Your pagerequestSubmit(@ModelAttribute Pagerequest pagerequest, Model model)  accepts two arguments one is pagerequest and other is model but in your test you are passing only pagerequest .You need to pass model object as well.This is just wrong method signature in your test class .
Create a mock of model object and paste that in your code as

```<code> @Mock
    private Model model;

 String outcome = pagerequestController.pagerequestSubmit(mockPageRequest,model);
 assertThat(outcome, is(equalTo("result")));
</code>```

Body:
I'm working in Spring Boot and am trying to write an integration test for a controller that looks like this:

public String pagerequestSubmit(@ModelAttribute Pagerequest pagerequest, Model model) {
...
 }

Now I'm trying to write an integration test for this controller like this:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes=PageAnalyzerInSpringApplication.class)
public class PagerequestControllerIntegrationTest {

@Autowired
PagerequestController pagerequestController;

@Test
public void testHappyPath() {

    Pagerequest mockPageRequest = new Pagerequest();
    mockPageRequest.setUrl("https://www.somedomain.com/");
    ....

    String outcome = pagerequestController.pagerequestSubmit(mockPageRequest);

    assertThat(outcome, is(equalTo("result")));

}

I don't have any problem doing the 'mock pagerequest' and passing it into the post method, so I got that far, but the above test does not work because I get:

"The method pagerequestSubmit(Pagerequest, Model) in the type PagerequestController is not applicable for the arguments (Pagerequest)"

Which makes sense because I'm not passing in any argument of the type Model
and I'm completely stuck on how to do that.

I've tried to instantiate a Model, which doesn't work, creating a fake Model, which also didn't work, and passing in a Model variable that was null, which at least gets the test running, but then throws a null pointer exception when the model in used in the controller.

Any ideas on how to resolve this?

Thanks in advance!

Body:
Your pagerequestSubmit(@ModelAttribute Pagerequest pagerequest, Model model)  accepts two arguments one is pagerequest and other is model but in your test you are passing only pagerequest .You need to pass model object as well.This is just wrong method signature in your test class .
Create a mock of model object and paste that in your code as

 @Mock
    private Model model;

 String outcome = pagerequestController.pagerequestSubmit(mockPageRequest,model);
 assertThat(outcome, is(equalTo("result")));


问:
Are C constant character strings always null terminated?
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

```<code>const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}
</code>```

答:
In short, yes. A string constant is of course a string and a string is by definition 0-terminated.

If you use a string constant as an array initializer like this:

```<code>char x[5] = "hello";
</code>```

you won't have a 0 terminator in x simply because there's no room for it.

But with

```<code>char x[] = "hello";
</code>```

it will be there and the size of x is 6.

Body:
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}

Body:
In short, yes. A string constant is of course a string and a string is by definition 0-terminated.

If you use a string constant as an array initializer like this:

char x[5] = "hello";

you won't have a 0 terminator in x simply because there's no room for it.

But with

char x[] = "hello";

it will be there and the size of x is 6.