答:
The reason for not specifying the exact results are

First the exact result doesnt matter. The caller just needs to know one of three results <, =, or >. The defined behavior works. Now the spec could have said return -1, 0, or 1. So why does it matter that this is not said. See second point

Second. By not specifying the exact result the implementer can write code that is very efficient. memcmp could be implemented by counting bits or doing some clever and. or. xor etc that does not naturally produce 1 or -1. So the spec is silent on the exact return value.

Title: What, exactly, is memcmp supposed to return?

Body:
I would like to know what the function memcmp must return.

I've been searching on the Internet, and usually, memcmp definitions state something like the following:

The memcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.

It is never explicitly said what, exactly, is returned: is it the difference between two byte values, or is it -1, 0 or 1? I am confused:

When testing the function memcmp in a little program, it returns -1, 0 or 1, even when the difference between the two bytes evaluated is higher than 1 or lower than -1.

When looking at functions named memcmp on the Internet, they almost all return the difference between 2 bytes, as an int, instead of returning either -1, 0 or 1.

Since I can't get a precise enough definition of the function memcmp, I ask this question here: what, exactly, is the function memcmp supposed to return? Is there an "official" source code somewhere? (I have seen a lot of source codes for memcmp but none gave me an answer: I then suppose that they are not the function that is written in the library string.h, at least not on my computer...)


来源: stackexchange

问:
Choose maven profile from OS family
I want to set some properties based on the OS type, so I have the following in my pom.xml:

```<code><project ...>
    <profiles>
        <profile>
            <id>KenMacbook</id>
            <activation>
                <os><family>mac</family></os>
            </activation>
            <properties>
                <test.r.version>3.3</test.r.version>
            </properties>
        </profile>
        <profile>
            <id>LinuxBox</id>
            <activation>
                <os><family>unix</family></os>
            </activation>
            <properties>
                <test.r.version>3.2</test.r.version>
            </properties>
        </profile>
    </profiles>
    ...
</project>
</code>```

On my Mac, I check what profiles are active:

```<code>% mvn help:active-profiles | grep -v INFO
Active Profiles for Project 'com.foo:bar:jar:2.0.3-SNAPSHOT':

The following profiles are active:

 - nexus (source: external)
 - KenMacbook (source: com.foo:bar:2.0.3-SNAPSHOT)
 - LinuxBox (source: com.foo:bar:2.0.3-SNAPSHOT)
</code>```

So it looks like the <activation> for the LinuxBox profile isn't successfully excluding that profile on Mac.  Am I misunderstanding something about how profile selection works?

Maven details:

```<code>% mvn --version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T10:41:47-06:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.7.0_75, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.5", arch: "x86_64", family: "mac"
</code>```

答:
The proper solution is to specify name.

```<code><activation>
            <os>
                <family>unix</family>
                <name>Linux</name>
            </os>
</activation>
</code>```

A full cross-platform solution is:

```<code><profile>
  <id>mac</id>
  <activation>
    <os>
      <family>mac</family>
    </os>
  </activation>
      <modules>
        <module>tests/org.eclipse.swt.tests.cocoa</module>
      </modules>
</profile>
<profile>
  <id>unix</id>
  <activation>
    <os>
      <family>unix</family>
      <name>Linux</name>
    </os>
  </activation>
      <modules>
        <module>tests/org.eclipse.swt.tests.gtk</module>
      </modules>
</profile>
<profile>
  <id>windows</id>
  <activation>
    <os>
      <family>windows</family>
    </os>
  </activation>
      <modules>
        <module>tests/org.eclipse.swt.tests.win32</module>
      </modules>
</profile>
</code>```

Source: http://maven.40175.n5.nabble.com/Profile-activation-for-mac-and-linux-td3263043.html

ContentLicense: CC BY-SA 3.0

Title: Choose maven profile from OS family

Body:
I want to set some properties based on the OS type, so I have the following in my pom.xml:

<project ...>
    <profiles>
        <profile>
            <id>KenMacbook</id>
            <activation>
                <os><family>mac</family></os>
            </activation>
            <properties>
                <test.r.version>3.3</test.r.version>
            </properties>
        </profile>
        <profile>
            <id>LinuxBox</id>
            <activation>
                <os><family>unix</family></os>
            </activation>
            <properties>
                <test.r.version>3.2</test.r.version>
            </properties>
        </profile>
    </profiles>
    ...
</project>

On my Mac, I check what profiles are active:

% mvn help:active-profiles | grep -v INFO
Active Profiles for Project 'com.foo:bar:jar:2.0.3-SNAPSHOT':

The following profiles are active:

 - nexus (source: external)
 - KenMacbook (source: com.foo:bar:2.0.3-SNAPSHOT)
 - LinuxBox (source: com.foo:bar:2.0.3-SNAPSHOT)

So it looks like the <activation> for the LinuxBox profile isn't successfully excluding that profile on Mac.  Am I misunderstanding something about how profile selection works?

Maven details:

% mvn --version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T10:41:47-06:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.7.0_75, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.5", arch: "x86_64", family: "mac"

Body:
The proper solution is to specify name.

<activation>
            <os>
                <family>unix</family>
                <name>Linux</name>
            </os>
</activation>

A full cross-platform solution is:

<profile>
  <id>mac</id>
  <activation>
    <os>
      <family>mac</family>
    </os>
  </activation>
      <modules>
        <module>tests/org.eclipse.swt.tests.cocoa</module>
      </modules>
</profile>
<profile>
  <id>unix</id>
  <activation>
    <os>
      <family>unix</family>
      <name>Linux</name>
    </os>
  </activation>
      <modules>
        <module>tests/org.eclipse.swt.tests.gtk</module>
      </modules>
</profile>
<profile>
  <id>windows</id>
  <activation>
    <os>
      <family>windows</family>
    </os>
  </activation>
      <modules>
        <module>tests/org.eclipse.swt.tests.win32</module>
      </modules>
</profile>

Source: http://maven.40175.n5.nabble.com/Profile-activation-for-mac-and-linux-td3263043.html


问:
Converting excel formulae to JS?
I have this formula and it uses powers e.g. '10 to the power 30'

```<code>=B2*(B3/12) / (1-(1+(B3/12)) ^ -B6)
</code>```

The problem is that I can't put ^ in JS/jQuery, I have to use Math.pow() as the equivalent.

I've tried quite a few different positions but I can't seem to get it correct, the brackets really confuse me. Which parts of the formula would I wrap the .pow within?

My attempt:  =B2*(B3/12) / Math.pow(   (1-(1+(B3/12)) ,  -B6)  )

UPDATE:
Please see this Fiddle

Fiddle code:

```<code>var B2 = 500000; //£500,000
var B3 = 2.00; //2.00%
var B6 = 300; //Total number of payments

var original_formula =  'B2*(B3/12)/(1-(1+(B3/12))^-B6)';

var x = B2 * (B3 / 12) / Math.pow(1 - (1 + (B3 / 12)), -B6)

console.log(x);

//Expected/Excel result = 2,119.27
//Actual result  = 2.9884337938456618e-229 <- what's going on here?
</code>```

答:
```<code>=B2*(B3/12) / (1-(1+(B3/12)) ^ -B6)
</code>```

is the same as

```<code>=B2*B3/12 / ( 1 - (1+B3/12) ^ -B6 )
</code>```

With this reduced number of parantheses it is perhaps easier to see that the javascript implementation should be

```<code>= B2*B3/12 / ( 1 - Math.pow(1+B3/12, -B6) )
</code>```

You also need to translate B3=2.00% into B3=2.00/100 or B3=0.02. Then the result is indeed 2119.2716932202998

var B2 = 500000; //£500,000
var B3 = 2.00; //2.00%
var B6 = 300; //Total number of payments

var original_formula =  'B2*(B3/12)/(1-(1+(B3/12))^-B6)';

B3 = B3/100 // 2.0% is 0.02 as number
var x = B2*B3/12 / (1 - Math.pow(1 + B3/12, -B6) )

var log = document.getElementById("log")
log.innerHTML += "x="+x;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="log"></div></code>```

Title: Converting excel formulae to JS?

Body:
I have this formula and it uses powers e.g. '10 to the power 30'

=B2*(B3/12) / (1-(1+(B3/12)) ^ -B6)

The problem is that I can't put ^ in JS/jQuery, I have to use Math.pow() as the equivalent.

I've tried quite a few different positions but I can't seem to get it correct, the brackets really confuse me. Which parts of the formula would I wrap the .pow within?

My attempt:  =B2*(B3/12) / Math.pow(   (1-(1+(B3/12)) ,  -B6)  )

UPDATE:
Please see this Fiddle

Fiddle code:

var B2 = 500000; //£500,000
var B3 = 2.00; //2.00%
var B6 = 300; //Total number of payments

var original_formula =  'B2*(B3/12)/(1-(1+(B3/12))^-B6)';

var x = B2 * (B3 / 12) / Math.pow(1 - (1 + (B3 / 12)), -B6)

console.log(x);

//Expected/Excel result = 2,119.27
//Actual result  = 2.9884337938456618e-229 <- what's going on here?

Body:
=B2*(B3/12) / (1-(1+(B3/12)) ^ -B6)

is the same as

=B2*B3/12 / ( 1 - (1+B3/12) ^ -B6 )

With this reduced number of parantheses it is perhaps easier to see that the javascript implementation should be

= B2*B3/12 / ( 1 - Math.pow(1+B3/12, -B6) )

You also need to translate B3=2.00% into B3=2.00/100 or B3=0.02. Then the result is indeed 2119.2716932202998

var B2 = 500000; //£500,000
var B3 = 2.00; //2.00%
var B6 = 300; //Total number of payments

var original_formula =  'B2*(B3/12)/(1-(1+(B3/12))^-B6)';

B3 = B3/100 // 2.0% is 0.02 as number
var x = B2*B3/12 / (1 - Math.pow(1 + B3/12, -B6) )

var log = document.getElementById("log")
log.innerHTML += "x="+x;

<div id="log"></div>


问:
Is it possible to add a slight delay to parallel luigi.Tasks?
I have a number of luigi.Tasks in a workflow that have no dependencies.  However, each of these task sends a command to a server that can get overwhelmed if I do not slightly stagger sending the commands.(i.e. put a 5 second delay between sending each command) Any way to handle this with an argument that I have not found?</p>

答:
Luigi has the concept of resources were you can limit the utilization of certain resources (in this case your server). You can configure that only a max number of task that require such resource to be executed concurrently. This is useful for example for databases where many tasks writing in parallel might hit server really bad.

Check the documentation:

http://luigi.readthedocs.io/en/stable/configuration.html?highlight=resources#resources

You basically add a section to your configuration:

```<code>   [resources]
   hive=2
   server=2
</code>```

and then in your class

```<code>class MyTask(luigi.Task):
   resources = {'server': 1}
</code>```

With this configuration you will only execute up two Task that use such resource. I know this is not what you were asking but I believe this is the closet feature Luigi has for your use case.

Body:
Luigi has the concept of resources were you can limit the utilization of certain resources (in this case your server). You can configure that only a max number of task that require such resource to be executed concurrently. This is useful for example for databases where many tasks writing in parallel might hit server really bad.

Check the documentation:

http://luigi.readthedocs.io/en/stable/configuration.html?highlight=resources#resources

You basically add a section to your configuration:

   [resources]
   hive=2
   server=2

and then in your class

class MyTask(luigi.Task):
   resources = {'server': 1}

With this configuration you will only execute up two Task that use such resource. I know this is not what you were asking but I believe this is the closet feature Luigi has for your use case.


问:
Remove the string from URL
How to remove the string after last '/' from a URL?

Example: <cfset normalURL = "http://test.com/myhome/live">

Expected outcome: http://test.com/myhome

答:
Here is one way to do it.

```<code><cfset normalURL = "http://test.com/myhome/live">
<cfoutput><p>#normalURL#</p></cfoutput>
</code>```

Output from above code:

http://test.com/myhome/live

```<code><cfset stringAfterLastSlash = ListLast(normalURL,"/")>
<cfoutput><p>#stringAfterLastSlash#</p></cfoutput>
</code>```

Output from above code:

live

```<code><cfset stringRemovedFromURL = Replace(normalURL,"/#stringAfterLastSlash#","")>
<cfoutput><p>#stringRemovedFromURL#</p></cfoutput>
</code>```

Output from above code:

http://test.com/myhome

You can play with this code and see the results here.

Title: Remove the string from URL

Body:
Here is one way to do it.

<cfset normalURL = "http://test.com/myhome/live">
<cfoutput><p>#normalURL#</p></cfoutput>

Output from above code:

http://test.com/myhome/live

<cfset stringAfterLastSlash = ListLast(normalURL,"/")>
<cfoutput><p>#stringAfterLastSlash#</p></cfoutput>

Output from above code:

live

<cfset stringRemovedFromURL = Replace(normalURL,"/#stringAfterLastSlash#","")>
<cfoutput><p>#stringRemovedFromURL#</p></cfoutput>

Output from above code:

http://test.com/myhome

You can play with this code and see the results here.


问:
Possible to reference previous query in new select query?
If i just created a select query and want to use the new data in a new query do I reference the previously created query as the FROM in a new select query? The query I just created in my database is listed as SQLQuery1.sql so is that what I put as the FROM for the new query?

答:
Here is an example of a query that contains multiple select statements:</p>

```<code>SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
</code>```

Body:
Here is an example of a query that contains multiple select statements:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a


问:
How to use output artifact of CodeBuild in CloudFormation?
So I have a fairly simple stack I'm trying to setup consisting of a single Lambda function subscribed to an SNS topic. I'd like to use CodePipeline with three stages: Source (GitHub) -> Build (CodeBuild) -> Deploy (CloudFormation).

I managed to cobble together a template and buildspec file that that work, except I'm lost on how I'm supposed to reference the output artifact that CodeBuild makes in the CloudFormation template; right now I just have placeholder inline code.

Basically, what am I supposed to put in the Code: property of the Lambda function in order to get the CodeBuild files (which is my output artifact in CodePipeline)?

template.yml:

```<code>AWSTemplateFormatVersion: 2010-09-09
Resources:
  SNSTopic:
    Type: 'AWS::SNS::Topic'
    Properties:
      Subscription:
        - Endpoint: !GetAtt
            - LambdaFunction
            - Arn
          Protocol: lambda
  LambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Runtime: python3.6
      Handler: main.lamda_handler
      Timeout: '10'
      Role: !GetAtt
        - LambdaExecutionRole
        - Arn
      Code:
        ZipFile: >
          def lambda_handler(event, context):
            print(event)
            return 'Hello, world!'
  LambdaExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      FunctionName: !GetAtt
        - LambdaFunction
        - Arn
      Action: 'lambda:InvokeFunction'
      Principal: sns.amazonaws.com
      SourceArn: !Ref SNSTopic
</code>```

buildspec.yml:

```<code>version: 0.2
phases:
  install:
    commands:
      - pip install -r requirements.txt -t libs
artifacts:
  type: zip
  files:
    - template.yml
    - main.py
    - lib/*
</code>```

答:
Your CodeBuild should be dropping your zip file to an S3 bucket.  So in the Code section of your LambdaFunction resource you point to it.

```<code>Code:
   S3Bucket: the_bucket_where_CodeBuild_dropped_your_zip
   S3Key: the_name_of_the_zip_file_dropped
</code>```

You don't need 'ZipFile: '

Body:
So I have a fairly simple stack I'm trying to setup consisting of a single Lambda function subscribed to an SNS topic. I'd like to use CodePipeline with three stages: Source (GitHub) -> Build (CodeBuild) -> Deploy (CloudFormation).

I managed to cobble together a template and buildspec file that that work, except I'm lost on how I'm supposed to reference the output artifact that CodeBuild makes in the CloudFormation template; right now I just have placeholder inline code.

Basically, what am I supposed to put in the Code: property of the Lambda function in order to get the CodeBuild files (which is my output artifact in CodePipeline)?

template.yml:

AWSTemplateFormatVersion: 2010-09-09
Resources:
  SNSTopic:
    Type: 'AWS::SNS::Topic'
    Properties:
      Subscription:
        - Endpoint: !GetAtt
            - LambdaFunction
            - Arn
          Protocol: lambda
  LambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Runtime: python3.6
      Handler: main.lamda_handler
      Timeout: '10'
      Role: !GetAtt
        - LambdaExecutionRole
        - Arn
      Code:
        ZipFile: >
          def lambda_handler(event, context):
            print(event)
            return 'Hello, world!'
  LambdaExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      FunctionName: !GetAtt
        - LambdaFunction
        - Arn
      Action: 'lambda:InvokeFunction'
      Principal: sns.amazonaws.com
      SourceArn: !Ref SNSTopic

buildspec.yml:

version: 0.2
phases:
  install:
    commands:
      - pip install -r requirements.txt -t libs
artifacts:
  type: zip
  files:
    - template.yml
    - main.py
    - lib/*

Body:
Your CodeBuild should be dropping your zip file to an S3 bucket.  So in the Code section of your LambdaFunction resource you point to it.

Code:
   S3Bucket: the_bucket_where_CodeBuild_dropped_your_zip
   S3Key: the_name_of_the_zip_file_dropped

You don't need 'ZipFile: '


问:
Checking OpenGL resource leaks
So I have a rather large openGL program going, and checking for normal memory leaks (those by new and delete) is rather trivial -- just run it on valgrind.

But what is the best way to check for potential opengl leaks? Is there an opengl utility that'll tell you how many resources (e.g framebuffers) are being used at the time, or such? Or is the only way to attach a counter to every glGenBlah and glDeleteBlah pairs?

答: There are definitely tools to do that for you. The commercial gDEBugger can do it, but it isn't free. glslDevil might work as a free alternative, but I'm not sure whether it can find leaks.</p>

ContentLicense: CC BY-SA 2.5

Title: Checking OpenGL resource leaks


问:
mongoose model.find query string
I have a problem with a query string of a mongoose model. The code below is working fine. But if I construct the same query as a String it is not working.
The console output of "query" is

```<code>'diagnosis_text_de': /.*depression.*/i
</code>```

I do not understand why this is not working and how to fix this.

working:

```<code>getByFullText = (req, res) => {
    let query: String = '\'diagnosis_text_de\': /.*' + req.body.qICD + '.*/i';
    console.log(query);
    this.model.find({
        'diagnosis_text_de': /.*depression.*/i
    }, (err, docs) => {
        if (err) {
            return console.error(err);
        }
        res.json(docs);
    });
}
</code>```

not working:

```<code>...
this.model.find({ query }, (err, docs)
...
</code>```

答:
Dear you can use mongodb operators $regex and $options as below    </p>

```<code>getByFullText = (req, res) => {
        let query = {
           diagnosis_text_de:{
            $regex: req.body.qICD,
            $options:"i"
          }
        }
        this.model.find(query,(err, docs) => {
            if (err) {
                return console.error(err);
            }
            res.json(docs);
        });
    }
</code>```

Title: mongoose model.find query string

Body:
I have a problem with a query string of a mongoose model. The code below is working fine. But if I construct the same query as a String it is not working.
The console output of "query" is

'diagnosis_text_de': /.*depression.*/i

I do not understand why this is not working and how to fix this.

working:

getByFullText = (req, res) => {
    let query: String = '\'diagnosis_text_de\': /.*' + req.body.qICD + '.*/i';
    console.log(query);
    this.model.find({
        'diagnosis_text_de': /.*depression.*/i
    }, (err, docs) => {
        if (err) {
            return console.error(err);
        }
        res.json(docs);
    });
}

not working:

...
this.model.find({ query }, (err, docs)
...

Body:
Dear you can use mongodb operators $regex and $options as below

getByFullText = (req, res) => {
        let query = {
           diagnosis_text_de:{
            $regex: req.body.qICD,
            $options:"i"
          }
        }
        this.model.find(query,(err, docs) => {
            if (err) {
                return console.error(err);
            }
            res.json(docs);
        });
    }


问:
Curl and PHP - how can I pass a json through curl by PUT,POST,GET
I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD

I can successfully make these call from the command line

```<code>curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
</code>```

The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl.  As you can see, I pass data as a json string.  I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET.  Everything I see says you must attached it to the url, but it doesn't look that way on the command line form.  Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page.  I would like to see the simplest way to do it with curl and php.  I think I need to pass everything through the http body because my php api catching everything with php://input

答: set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false); </p>

Body:
I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD

I can successfully make these call from the command line

curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1

The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl.  As you can see, I pass data as a json string.  I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET.  Everything I see says you must attached it to the url, but it doesn't look that way on the command line form.  Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page.  I would like to see the simplest way to do it with curl and php.  I think I need to pass everything through the http body because my php api catching everything with php://input


问:
IOException on writing a file to Hdfs
I'm working on a program that takes gps data from a mqtt broker and loads it into the hadoop cluster. On trying to write the data to hdfs, I'm getting and IOException. The following is the full stacktrace:

```<code>java.io.IOException: Failed on local exception: com.google.protobuf.InvalidProtocolBufferException: Message missing required fields: callId, status; Host Details : local host is: "quickstart.cloudera/192.168.25.170"; destination host is: "quickstart.cloudera":8020;
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:765)
    at org.apache.hadoop.ipc.Client.call(Client.java:1165)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:184)
    at com.sun.proxy.$Proxy7.create(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:165)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:84)
    at com.sun.proxy.$Proxy7.create(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.create(ClientNamenodeProtocolTranslatorPB.java:187)
    at org.apache.hadoop.hdfs.DFSOutputStream.<init>(DFSOutputStream.java:1250)
    at org.apache.hadoop.hdfs.DFSOutputStream.newStreamForCreate(DFSOutputStream.java:1269)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1063)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1021)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:232)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:75)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:806)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:787)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:686)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:675)
    at com.mqttHadoopLoader.hadoop.MqttLoader.HdfsWriter.writeToHdfs(HdfsWriter.java:19)
    at com.mqttHadoopLoader.hadoop.MqttLoader.MqttDataLoader.messageArrived(MqttDataLoader.java:43)
    at org.eclipse.paho.client.mqttv3.internal.CommsCallback.handleMessage(CommsCallback.java:354)
    at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:162)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.google.protobuf.InvalidProtocolBufferException: Message missing required fields: callId, status
    at com.google.protobuf.UninitializedMessageException.asInvalidProtocolBufferException(UninitializedMessageException.java:81)
    at org.apache.hadoop.ipc.protobuf.RpcPayloadHeaderProtos$RpcResponseHeaderProto$Builder.buildParsed(RpcPayloadHeaderProtos.java:1094)
    at org.apache.hadoop.ipc.protobuf.RpcPayloadHeaderProtos$RpcResponseHeaderProto$Builder.access$1300(RpcPayloadHeaderProtos.java:1028)
    at org.apache.hadoop.ipc.protobuf.RpcPayloadHeaderProtos$RpcResponseHeaderProto.parseDelimitedFrom(RpcPayloadHeaderProtos.java:986)
    at org.apache.hadoop.ipc.Client$Connection.receiveResponse(Client.java:850)
    at org.apache.hadoop.ipc.Client$Connection.run(Client.java:781)
</code>```

It seems like the error is occurring when I try to create the OutputStream but it's difficult to say because my eclipse debugger isn't working correctly (it says that it cannot connect to the VM and I've tried a multitude of fixes posted here on stackoverflow). Here is my code for my HdfsWriter:

```<code>String destFile = "hdfs://127.0.0.0.1:8020/gpsData/output/gps_data.txt";
 //Note *this is just a placeholder IP address for the purpose of this post. I do have the fully correct IP address for the program.

    public void writeToHdfs(String gpsInfo) {
        try {
            Configuration conf = new Configuration();
            System.out.println("Connecting to -- " + conf.get("fs.defaultFS"));

            FileSystem fs = FileSystem.get(URI.create(destFile), conf);
            System.out.println(fs.getUri());

            // Error seems to occur here
            OutputStream outStream = fs.create(new Path(destFile));

            byte[] messageByt = gpsInfo.getBytes();
            outStream.write(messageByt);
            outStream.close();

            System.out.println(destFile + " copied to HDFS");

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>```

This is the mqtt method that calls for the HdfsWriter:

```<code>public void messageArrived(String topic, MqttMessage message)
        throws Exception {
            System.out.println(message);
            HdfsWriter hdfsWriter = new HdfsWriter();
            hdfsWriter.writeToHdfs(message.toString());
    }
</code>```

I'm still really new to hadoop so any and all help would be great.

UPDATE
I've got my debug working and can definitively tell you that the error occurs whenever I try to call a FileSystem method. For example the error is also triggered by fs.exists(pt) and by fs.setReplication().

答:
The protocol between the HDFS client and the NameNode uses Google Protocol Buffers to serialize messages.  The error indicates that the message sent by the client did not contain all of the expected fields, so it is incompatible with the server.

This likely indicates that you are running a version of the HDFS client that is older than the version of the NameNode.  For example, the callId field was implemented in the feature tracked by Apache JIRA issue HADOOP-9762 and shipped in Apache Hadoop 2.1.0-beta.  A client prior to that version would not have included callId in its messages, so it would be incompatible with a NameNode running 2.1.0-beta or later.

I suggest reviewing your client application to make sure that it is using the Hadoop client library version that matches the Hadoop cluster version.  From the stack trace, it appears that you are using the Cloudera distribution.  If so, then you'll likely have the most success by using the matching client library dependency version provided by Cloudera in their Maven repository.  See Using the CDH 5 Maven Repository for details.

Title: IOException on writing a file to Hdfs

Body:
I'm working on a program that takes gps data from a mqtt broker and loads it into the hadoop cluster. On trying to write the data to hdfs, I'm getting and IOException. The following is the full stacktrace:

java.io.IOException: Failed on local exception: com.google.protobuf.InvalidProtocolBufferException: Message missing required fields: callId, status; Host Details : local host is: "quickstart.cloudera/192.168.25.170"; destination host is: "quickstart.cloudera":8020;
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:765)
    at org.apache.hadoop.ipc.Client.call(Client.java:1165)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:184)
    at com.sun.proxy.$Proxy7.create(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:165)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:84)
    at com.sun.proxy.$Proxy7.create(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.create(ClientNamenodeProtocolTranslatorPB.java:187)
    at org.apache.hadoop.hdfs.DFSOutputStream.<init>(DFSOutputStream.java:1250)
    at org.apache.hadoop.hdfs.DFSOutputStream.newStreamForCreate(DFSOutputStream.java:1269)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1063)
    at org.apache.hadoop.hdfs.DFSClient.create(DFSClient.java:1021)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:232)
    at org.apache.hadoop.hdfs.DistributedFileSystem.create(DistributedFileSystem.java:75)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:806)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:787)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:686)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:675)
    at com.mqttHadoopLoader.hadoop.MqttLoader.HdfsWriter.writeToHdfs(HdfsWriter.java:19)
    at com.mqttHadoopLoader.hadoop.MqttLoader.MqttDataLoader.messageArrived(MqttDataLoader.java:43)
    at org.eclipse.paho.client.mqttv3.internal.CommsCallback.handleMessage(CommsCallback.java:354)
    at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:162)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.google.protobuf.InvalidProtocolBufferException: Message missing required fields: callId, status
    at com.google.protobuf.UninitializedMessageException.asInvalidProtocolBufferException(UninitializedMessageException.java:81)
    at org.apache.hadoop.ipc.protobuf.RpcPayloadHeaderProtos$RpcResponseHeaderProto$Builder.buildParsed(RpcPayloadHeaderProtos.java:1094)
    at org.apache.hadoop.ipc.protobuf.RpcPayloadHeaderProtos$RpcResponseHeaderProto$Builder.access$1300(RpcPayloadHeaderProtos.java:1028)
    at org.apache.hadoop.ipc.protobuf.RpcPayloadHeaderProtos$RpcResponseHeaderProto.parseDelimitedFrom(RpcPayloadHeaderProtos.java:986)
    at org.apache.hadoop.ipc.Client$Connection.receiveResponse(Client.java:850)
    at org.apache.hadoop.ipc.Client$Connection.run(Client.java:781)

It seems like the error is occurring when I try to create the OutputStream but it's difficult to say because my eclipse debugger isn't working correctly (it says that it cannot connect to the VM and I've tried a multitude of fixes posted here on stackoverflow). Here is my code for my HdfsWriter:

String destFile = "hdfs://127.0.0.0.1:8020/gpsData/output/gps_data.txt";
 //Note *this is just a placeholder IP address for the purpose of this post. I do have the fully correct IP address for the program.

    public void writeToHdfs(String gpsInfo) {
        try {
            Configuration conf = new Configuration();
            System.out.println("Connecting to -- " + conf.get("fs.defaultFS"));

            FileSystem fs = FileSystem.get(URI.create(destFile), conf);
            System.out.println(fs.getUri());

            // Error seems to occur here
            OutputStream outStream = fs.create(new Path(destFile));

            byte[] messageByt = gpsInfo.getBytes();
            outStream.write(messageByt);
            outStream.close();

            System.out.println(destFile + " copied to HDFS");

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

This is the mqtt method that calls for the HdfsWriter:

public void messageArrived(String topic, MqttMessage message)
        throws Exception {
            System.out.println(message);
            HdfsWriter hdfsWriter = new HdfsWriter();
            hdfsWriter.writeToHdfs(message.toString());
    }

I'm still really new to hadoop so any and all help would be great.

UPDATE
I've got my debug working and can definitively tell you that the error occurs whenever I try to call a FileSystem method. For example the error is also triggered by fs.exists(pt) and by fs.setReplication().


问:
Does AWS certificate manager auto deploy to my resources?
I ask this because there are many resources out there for Lets Encrypt to auto renew and deploy (via Lambda) to ELBs. Doesn't AWS' Certificate Manager do the same thing?

https://aws.amazon.com/certificate-manager/faqs/

Says:

Q: What can I do with AWS Certificate Manager?

...

ACM manages certificate renewals and certificate deployment for you.

However the AWS docs don't talk about this at all.

So if I understand this correctly...

I request a cert

Verify the cert in my email

Manually deploy the cert

ACM will every year renew my cert and deploy my cert back to all the resources I deployed it to previously

Is this correct? Is there documentation that talks about this explicitly?

Any direction on this would be helpful.

答:
If you are using AWS SSL Certificates from Certificate Manager, renewal is automatically handled and changing the certificate from your application load balancer or CloudFront is not required.

Check this documentation for more details.


问:
how to use event onChange in ionic2
Basically I am trying to make a registration form in which I have some drop down lists. And I want to apply "(change)" event on it which will trigger a function whenever value will be changed or we can say value be selected from that drop down list and based on that I will be assigning next fields dynamically but this event is not working on drop-down while its working fine with text fields.
Can someone help me out with this?

Sample code:

home.html -->

```<code><ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>

<form [formGroup]="myForm">
    <ion-item>
        <ion-label>Dropdown1 :</ion-label>
        <ion-select formControlName="dd" (ionChange)='f()'  #dd>
         <ion-option value='1'>A</ion-option>
            <ion-option value='2'>B</ion-option>
            <ion-option value='3'>C</ion-option>
            <ion-option value='4'>D</ion-option>
        </ion-select>
    </ion-item>

     <ion-item>
    <ion-label>Dropdown2 :</ion-label>
    <ion-select>
     <ion-option value='1'>E</ion-option>
        <ion-option value='2'>F</ion-option>
        <ion-option value='3'>G</ion-option>
        <ion-option value='4'>H</ion-option>
    </ion-select>
</ion-item>

</form>
</ion-content>
</code>```

home.ts -->

```<code>import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }

  function f(){
  alert('Value Changed!');
  alert(this.myForm.dd);

  }

}
</code>```

答:
You can use ionSelect on ion-option this will fire each time the item is selected.

Ionic docs ion-option

```<code><ion-select>
    <ion-option (ionSelect)="optionSelected($event)" *ngFor="let item of items$ | async" [value]="item.id">{{item.name}}</ion-option>
</ion-select>
</code>```

Title: how to use event onChange in ionic2

Body:
Basically I am trying to make a registration form in which I have some drop down lists. And I want to apply "(change)" event on it which will trigger a function whenever value will be changed or we can say value be selected from that drop down list and based on that I will be assigning next fields dynamically but this event is not working on drop-down while its working fine with text fields.
Can someone help me out with this?

Sample code:

home.html -->

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>

<form [formGroup]="myForm">
    <ion-item>
        <ion-label>Dropdown1 :</ion-label>
        <ion-select formControlName="dd" (ionChange)='f()'  #dd>
         <ion-option value='1'>A</ion-option>
            <ion-option value='2'>B</ion-option>
            <ion-option value='3'>C</ion-option>
            <ion-option value='4'>D</ion-option>
        </ion-select>
    </ion-item>

     <ion-item>
    <ion-label>Dropdown2 :</ion-label>
    <ion-select>
     <ion-option value='1'>E</ion-option>
        <ion-option value='2'>F</ion-option>
        <ion-option value='3'>G</ion-option>
        <ion-option value='4'>H</ion-option>
    </ion-select>
</ion-item>

</form>
</ion-content>

home.ts -->

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }

  function f(){
  alert('Value Changed!');
  alert(this.myForm.dd);

  }

}

Body:
You can use ionSelect on ion-option this will fire each time the item is selected.

Ionic docs ion-option

<ion-select>
    <ion-option (ionSelect)="optionSelected($event)" *ngFor="let item of items$ | async" [value]="item.id">{{item.name}}</ion-option>
</ion-select>


问:
Cannot send an e-mail without a Postmark API Key
I got this Error when user want to register:

PMMailMissingValueException at /accounts/register/

Cannot send an e-mail without a Postmark API Key

Request Method: POST
Request URL:    http://127.0.0.1:8009/accounts/register/
Django Version: 1.11.3
Exception Type: PMMailMissingValueException
```

<p>and  I dont know to which value for </p>

```POSTMARK_API_TOKEN=''
```

in settings.py file.

答: Not clear what exact application you use and how you configure it, but seems it's configured to sent emails using https://postmarkapp.com/ service. You have to register and get your API access credentials.</p>

Body:
I got this Error when user want to register:

PMMailMissingValueException at /accounts/register/

Cannot send an e-mail without a Postmark API Key

Request Method: POST
Request URL:    http://127.0.0.1:8009/accounts/register/
Django Version: 1.11.3
Exception Type: PMMailMissingValueException

and  I dont know to which value for

POSTMARK_API_TOKEN=''

in settings.py file.


问:
Use values outside excel cell in apache poi Bar chart
I am trying to create a bar chart in excel file using Apache poi and following the code mentioned here:
Create Bar Chart in Excel with Apache POI.

In my case, I need to use data values coming from a different source instead of the excel cells. How can I use those values in the BarChart?

Assume that the values will come as an array of float/double values. Also, I need to be able to set Bar colors independently. For example, some bars will be green while some others will be red.

I modified the data portion of Create Bar Chart in Excel with Apache POI code in the following manner:

```<code> CTBarSer ctBarSer = ctBarChart.addNewSer();
 CTSerTx ctSerTx = ctBarSer.addNewTx();
 CTStrRef ctStrRef = ctSerTx.addNewStrRef();
ctStrRef.setF("hardcoded" + r);
ctBarSer.addNewIdx().setVal(r-2);
CTAxDataSource cttAxDataSource = ctBarSer.addNewCat();
CTStrData ctStrData = cttAxDataSource.addNewStrLit();
ctStrData.addNewPt().setV("Val1");
ctStrData.addNewPt().setV("Val2");
ctStrData.addNewPt().setV("Val3");

CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();

CTNumData ctNumData = ctNumDataSource.addNewNumLit();
CTNumVal ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.92));

ctNumData = ctNumDataSource.addNewNumLit();
ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.95));

ctNumData = ctNumDataSource.addNewNumLit();
ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.98));
</code>```

Any help is greatly appreciated. Thanks!

When I output the excel file using print, it gives the following result:

```<code><xml-fragment xmlns:char="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:main="http://schemas.openxmlformats.org/drawingml/2006/main">
  <char:plotArea>
    <char:layout/>
    <char:barChart>
      <char:barDir val="col"/>
      <char:varyColors val="false"/>
      <char:ser>
        <char:idx val="0"/>
        <char:tx>
          <char:strRef>
            <char:f>hardcoded2</char:f>
          </char:strRef>
        </char:tx>
        <char:spPr>
          <main:ln>
            <main:solidFill>
              <main:srgbClr val="000000"/>
            </main:solidFill>
          </main:ln>
        </char:spPr>
        <char:cat>
          <char:strLit>
            <char:pt>
              <char:v>Val1</char:v>
            </char:pt>
            <char:pt>
              <char:v>Val2</char:v>
            </char:pt>
            <char:pt>
              <char:v>Val3</char:v>
            </char:pt>
          </char:strLit>
        </char:cat>
        <char:val>
          <char:numLit>
            <char:pt>
              <char:v>0.92</char:v>
            </char:pt>
          </char:numLit>
          <char:numLit>
            <char:pt>
              <char:v>0.95</char:v>
            </char:pt>
          </char:numLit>
          <char:numLit>
            <char:pt>
              <char:v>0.98</char:v>
            </char:pt>
          </char:numLit>
        </char:val>
      </char:ser>
      <char:axId val="123456"/>
      <char:axId val="123457"/>
    </char:barChart>
    <char:catAx>
      <char:axId val="123456"/>
      <char:scaling>
        <char:orientation val="minMax"/>
      </char:scaling>
      <char:delete val="false"/>
      <char:axPos val="b"/>
      <char:tickLblPos val="nextTo"/>
      <char:crossAx val="123457"/>
    </char:catAx>
    <char:valAx>
      <char:axId val="123457"/>
      <char:scaling>
        <char:orientation val="minMax"/>
      </char:scaling>
      <char:delete val="false"/>
      <char:axPos val="l"/>
      <char:tickLblPos val="nextTo"/>
      <char:crossAx val="123456"/>
    </char:valAx>
  </char:plotArea>
  <char:plotVisOnly val="true"/>
</xml-fragment>
</code>```

答:
Main problems with your changings are:

You forgot setting the Idx of the CTStrVal and the CTNumVal, you have added using addNewPt.

CTNumData added to CTNumDataSource with addNewNumLit should contain as much CTNumVals like there are data points in the series. There should not be multiple CTNumDatain one series. With CTStrData in CTAxDataSource you have done it right - except the missing Idx, see 1.

Following  code is creating the same chart as the one in the linked answer but without cell references:

```<code>import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFChart;

import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarSer;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTScaling;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTLegend;
import org.openxmlformats.schemas.drawingml.x2006.chart.STAxPos;
import org.openxmlformats.schemas.drawingml.x2006.chart.STBarDir;
import org.openxmlformats.schemas.drawingml.x2006.chart.STOrientation;
import org.openxmlformats.schemas.drawingml.x2006.chart.STLegendPos;
import org.openxmlformats.schemas.drawingml.x2006.chart.STTickLblPos;

/*
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumRef;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef;
*/

import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal;

public class BarChartPlainValues {

    public static void main(String[] args) throws Exception {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");

/*
cell filing code deleted
*/

        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);

        Chart chart = drawing.createChart(anchor);

        CTChart ctChart = ((XSSFChart)chart).getCTChart();
        CTPlotArea ctPlotArea = ctChart.getPlotArea();
        CTBarChart ctBarChart = ctPlotArea.addNewBarChart();
        CTBoolean ctBoolean = ctBarChart.addNewVaryColors();
        ctBoolean.setVal(true);
        ctBarChart.addNewBarDir().setVal(STBarDir.COL);

//new code start

        for (int s = 1; s < 5; s++) {
           CTBarSer ctBarSer = ctBarChart.addNewSer();
           CTSerTx ctSerTx = ctBarSer.addNewTx();
           ctSerTx.setV("Serie " + s);
           ctBarSer.addNewIdx().setVal(s-1);

           CTAxDataSource ctAxDataSource = ctBarSer.addNewCat();
           CTStrData ctStrData = ctAxDataSource.addNewStrLit();
           ctStrData.addNewPtCount().setVal(3);
           CTStrVal ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(0);
           ctStrVal.setV("HEADER 1");
           ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(1);
           ctStrVal.setV("HEADER 2");
           ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(2);
           ctStrVal.setV("HEADER 3");

           CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();
           CTNumData ctNumData = ctNumDataSource.addNewNumLit();
           ctNumData.addNewPtCount().setVal(3);
           CTNumVal ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(0);
           ctNumVal.setV("" + new java.util.Random().nextDouble());
           ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(1);
           ctNumVal.setV("" + new java.util.Random().nextDouble());
           ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(2);
           ctNumVal.setV("" + new java.util.Random().nextDouble());

           //at least the border lines in Libreoffice Calc ;-)
           ctBarSer.addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[] {0,0,0});

        }

//new code end

/*
chart reference code deleted
*/

        //telling the BarChart that it has axes and giving them Ids
        ctBarChart.addNewAxId().setVal(123456);
        ctBarChart.addNewAxId().setVal(123457);

        //cat axis
        CTCatAx ctCatAx = ctPlotArea.addNewCatAx();
        ctCatAx.addNewAxId().setVal(123456); //id of the cat axis
        CTScaling ctScaling = ctCatAx.addNewScaling();
        ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
        ctCatAx.addNewDelete().setVal(false);
        ctCatAx.addNewAxPos().setVal(STAxPos.B);
        ctCatAx.addNewCrossAx().setVal(123457); //id of the val axis
        ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

        //val axis
        CTValAx ctValAx = ctPlotArea.addNewValAx();
        ctValAx.addNewAxId().setVal(123457); //id of the val axis
        ctScaling = ctValAx.addNewScaling();
        ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
        ctValAx.addNewDelete().setVal(false);
        ctValAx.addNewAxPos().setVal(STAxPos.L);
        ctValAx.addNewCrossAx().setVal(123456); //id of the cat axis
        ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

        //legend
        CTLegend ctLegend = ctChart.addNewLegend();
        ctLegend.addNewLegendPos().setVal(STLegendPos.B);
        ctLegend.addNewOverlay().setVal(false);

System.out.println(ctChart);

        FileOutputStream fileOut = new FileOutputStream("BarChartPlainValues.xlsx");
        wb.write(fileOut);
        fileOut.close();
    }
}
</code>```

Problem: Normally arrays of string literals like ={"HEADER 1","HEADER 2","HEADER 3"} are not allowed as axis labels. Only references are allowed here. Excel accepts this while rendering the chart but you cannot edit those axis labels in Excel GUI.

Body:
I am trying to create a bar chart in excel file using Apache poi and following the code mentioned here:
Create Bar Chart in Excel with Apache POI.

In my case, I need to use data values coming from a different source instead of the excel cells. How can I use those values in the BarChart?

Assume that the values will come as an array of float/double values. Also, I need to be able to set Bar colors independently. For example, some bars will be green while some others will be red.

I modified the data portion of Create Bar Chart in Excel with Apache POI code in the following manner:

 CTBarSer ctBarSer = ctBarChart.addNewSer();
 CTSerTx ctSerTx = ctBarSer.addNewTx();
 CTStrRef ctStrRef = ctSerTx.addNewStrRef();
ctStrRef.setF("hardcoded" + r);
ctBarSer.addNewIdx().setVal(r-2);
CTAxDataSource cttAxDataSource = ctBarSer.addNewCat();
CTStrData ctStrData = cttAxDataSource.addNewStrLit();
ctStrData.addNewPt().setV("Val1");
ctStrData.addNewPt().setV("Val2");
ctStrData.addNewPt().setV("Val3");

CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();

CTNumData ctNumData = ctNumDataSource.addNewNumLit();
CTNumVal ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.92));

ctNumData = ctNumDataSource.addNewNumLit();
ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.95));

ctNumData = ctNumDataSource.addNewNumLit();
ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.98));

Any help is greatly appreciated. Thanks!

When I output the excel file using print, it gives the following result:

<xml-fragment xmlns:char="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:main="http://schemas.openxmlformats.org/drawingml/2006/main">
  <char:plotArea>
    <char:layout/>
    <char:barChart>
      <char:barDir val="col"/>
      <char:varyColors val="false"/>
      <char:ser>
        <char:idx val="0"/>
        <char:tx>
          <char:strRef>
            <char:f>hardcoded2</char:f>
          </char:strRef>
        </char:tx>
        <char:spPr>

        </char:spPr>
        <char:cat>
          <char:strLit>
            <char:pt>
              <char:v>Val1</char:v>
            </char:pt>
            <char:pt>
              <char:v>Val2</char:v>
            </char:pt>
            <char:pt>
              <char:v>Val3</char:v>
            </char:pt>
          </char:strLit>
        </char:cat>
        <char:val>
          <char:numLit>
            <char:pt>
              <char:v>0.92</char:v>
            </char:pt>
          </char:numLit>
          <char:numLit>
            <char:pt>
              <char:v>0.95</char:v>
            </char:pt>
          </char:numLit>
          <char:numLit>
            <char:pt>
              <char:v>0.98</char:v>
            </char:pt>
          </char:numLit>
        </char:val>
      </char:ser>
      <char:axId val="123456"/>
      <char:axId val="123457"/>
    </char:barChart>
    <char:catAx>
      <char:axId val="123456"/>
      <char:scaling>
        <char:orientation val="minMax"/>
      </char:scaling>
      <char:delete val="false"/>
      <char:axPos val="b"/>
      <char:tickLblPos val="nextTo"/>
      <char:crossAx val="123457"/>
    </char:catAx>
    <char:valAx>
      <char:axId val="123457"/>
      <char:scaling>
        <char:orientation val="minMax"/>
      </char:scaling>
      <char:delete val="false"/>
      <char:axPos val="l"/>
      <char:tickLblPos val="nextTo"/>
      <char:crossAx val="123456"/>
    </char:valAx>
  </char:plotArea>
  <char:plotVisOnly val="true"/>
</xml-fragment>

Body:
Main problems with your changings are:

You forgot setting the Idx of the CTStrVal and the CTNumVal, you have added using addNewPt.

CTNumData added to CTNumDataSource with addNewNumLit should contain as much CTNumVals like there are data points in the series. There should not be multiple CTNumDatain one series. With CTStrData in CTAxDataSource you have done it right - except the missing Idx, see 1.

Following  code is creating the same chart as the one in the linked answer but without cell references:

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFChart;

import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarSer;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTScaling;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTLegend;
import org.openxmlformats.schemas.drawingml.x2006.chart.STAxPos;
import org.openxmlformats.schemas.drawingml.x2006.chart.STBarDir;
import org.openxmlformats.schemas.drawingml.x2006.chart.STOrientation;
import org.openxmlformats.schemas.drawingml.x2006.chart.STLegendPos;
import org.openxmlformats.schemas.drawingml.x2006.chart.STTickLblPos;

/*
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumRef;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef;
*/

import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal;

public class BarChartPlainValues {

    public static void main(String[] args) throws Exception {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");

/*
cell filing code deleted
*/

        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);

        Chart chart = drawing.createChart(anchor);

        CTChart ctChart = ((XSSFChart)chart).getCTChart();
        CTPlotArea ctPlotArea = ctChart.getPlotArea();
        CTBarChart ctBarChart = ctPlotArea.addNewBarChart();
        CTBoolean ctBoolean = ctBarChart.addNewVaryColors();
        ctBoolean.setVal(true);
        ctBarChart.addNewBarDir().setVal(STBarDir.COL);

//new code start

        for (int s = 1; s < 5; s++) {
           CTBarSer ctBarSer = ctBarChart.addNewSer();
           CTSerTx ctSerTx = ctBarSer.addNewTx();
           ctSerTx.setV("Serie " + s);
           ctBarSer.addNewIdx().setVal(s-1);

           CTAxDataSource ctAxDataSource = ctBarSer.addNewCat();
           CTStrData ctStrData = ctAxDataSource.addNewStrLit();
           ctStrData.addNewPtCount().setVal(3);
           CTStrVal ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(0);
           ctStrVal.setV("HEADER 1");
           ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(1);
           ctStrVal.setV("HEADER 2");
           ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(2);
           ctStrVal.setV("HEADER 3");

           CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();
           CTNumData ctNumData = ctNumDataSource.addNewNumLit();
           ctNumData.addNewPtCount().setVal(3);
           CTNumVal ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(0);
           ctNumVal.setV("" + new java.util.Random().nextDouble());
           ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(1);
           ctNumVal.setV("" + new java.util.Random().nextDouble());
           ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(2);
           ctNumVal.setV("" + new java.util.Random().nextDouble());

           //at least the border lines in Libreoffice Calc ;-)
           ctBarSer.addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[] {0,0,0});

        }

//new code end

/*
chart reference code deleted
*/

        //telling the BarChart that it has axes and giving them Ids
        ctBarChart.addNewAxId().setVal(123456);
        ctBarChart.addNewAxId().setVal(123457);

        //cat axis
        CTCatAx ctCatAx = ctPlotArea.addNewCatAx();
        ctCatAx.addNewAxId().setVal(123456); //id of the cat axis
        CTScaling ctScaling = ctCatAx.addNewScaling();
        ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
        ctCatAx.addNewDelete().setVal(false);
        ctCatAx.addNewAxPos().setVal(STAxPos.B);
        ctCatAx.addNewCrossAx().setVal(123457); //id of the val axis
        ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

        //val axis
        CTValAx ctValAx = ctPlotArea.addNewValAx();
        ctValAx.addNewAxId().setVal(123457); //id of the val axis
        ctScaling = ctValAx.addNewScaling();
        ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
        ctValAx.addNewDelete().setVal(false);
        ctValAx.addNewAxPos().setVal(STAxPos.L);
        ctValAx.addNewCrossAx().setVal(123456); //id of the cat axis
        ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

        //legend
        CTLegend ctLegend = ctChart.addNewLegend();
        ctLegend.addNewLegendPos().setVal(STLegendPos.B);
        ctLegend.addNewOverlay().setVal(false);

System.out.println(ctChart);

        FileOutputStream fileOut = new FileOutputStream("BarChartPlainValues.xlsx");
        wb.write(fileOut);
        fileOut.close();
    }
}

Problem: Normally arrays of string literals like ={"HEADER 1","HEADER 2","HEADER 3"} are not allowed as axis labels. Only references are allowed here. Excel accepts this while rendering the chart but you cannot edit those axis labels in Excel GUI.


问:
Plotly in R Power BI
How I can create interactive R plots in Power BI (for example Plotly)? Below code doesn't return any error, but also doesn't show chart:

```<code>library(plotly)
library(ggplot2)

z = ggplot(data = dataset) + geom_point(mapping = aes(x = Console, y = Search))
ggplotly(z)
</code>```

Data source:

```<code>source <- "https://cdn.rawgit.com/BlueGranite/Microsoft-R-Resources/master/power-bi/gameconsole.csv"
game.console <- read.csv(source, header = TRUE)
</code>```

答:
According to this question in Power BI's Community forums

Plotly lib is supported as part of HTML support for R powered Custom
Visuals only, not R Visuals in general currently.

Plotly can only be used if it produces an IMAGE\PNG for R visuals in
PBI. Not HTML.

For Custom Visuals we have an upcoming feature which will also enable R-based custom visuals to render as htmls.

Hope this helps.

Title: Plotly in R Power BI

Body:
How I can create interactive R plots in Power BI (for example Plotly)? Below code doesn't return any error, but also doesn't show chart:

library(plotly)
library(ggplot2)

z = ggplot(data = dataset) + geom_point(mapping = aes(x = Console, y = Search))
ggplotly(z)

Data source:

source <- "https://cdn.rawgit.com/BlueGranite/Microsoft-R-Resources/master/power-bi/gameconsole.csv"
game.console <- read.csv(source, header = TRUE)

ContentLicense: CC BY-SA 4.0


问:
Adjust UILabel height depending on the text
Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players must use the post-apocalyptic world to their advantage, such as seeking cover behind dumpsters, pillars, cars, rubble, and other objects.

I want to resize the UILabel's height so that the text can fit in. I'm using following properties of UILabel to make the text within to wrap.

```<code>myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;
</code>```

Please let me know if I'm not heading in the right direction. Thanks.

答:
Finally, it worked. Thank you guys.

I was not getting it to work because i was trying to resize the label in heightForRowAtIndexPath method:

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

and (yeah silly me), i was resizing the label to default in cellForRowAtIndexPath method - i was overlooking the code i had written earlier:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

OwnerDisplayName: Mustafa

Body:
Consider I have the following text in a UILabel (a long line of dynamic text):

Since the alien army vastly outnumbers the team, players must use the post-apocalyptic world to their advantage, such as seeking cover behind dumpsters, pillars, cars, rubble, and other objects.

I want to resize the UILabel's height so that the text can fit in. I'm using following properties of UILabel to make the text within to wrap.

myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;

Please let me know if I'm not heading in the right direction. Thanks.

LastEditorDisplayName: Chris Hanson

Body:
Finally, it worked. Thank you guys.

I was not getting it to work because i was trying to resize the label in heightForRowAtIndexPath method:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

and (yeah silly me), i was resizing the label to default in cellForRowAtIndexPath method - i was overlooking the code i had written earlier:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


问:
jquery UI draggable with live
this is a draggable sortable example on the jqueryui website, i need to use live() with this (I think) because the elements are created through ajax, does anybody know how to apply the live event to the following?  </p>

```<code><script>
    $(function() {
        $( "#sortable" ).sortable({
            revert: true
        });
        $( "#draggable" ).draggable({
            connectToSortable: "#sortable",
            helper: "clone",
            revert: "invalid"
        });
        $( "ul, li" ).disableSelection();
    });
    </script>
</code>```

答:
I don't think it is possible to do the live event as you want it. The best option you have is to use a callback function when you add a new element to the list and reenable the new object to be draggable each time there is a new element.

Something like this:

```<code>// Call to add a new element
$.ajax({
  url: 'addElem',
  success: function(data) {
    $( "#newDraggableObject" ).draggable({
        connectToSortable: "#sortable",
        helper: "clone",
        revert: "invalid"
    });
  }
});
</code>```

Title: jquery UI draggable with live

Body:
I don't think it is possible to do the live event as you want it. The best option you have is to use a callback function when you add a new element to the list and reenable the new object to be draggable each time there is a new element.

Something like this:

// Call to add a new element
$.ajax({
  url: 'addElem',
  success: function(data) {
    $( "#newDraggableObject" ).draggable({
        connectToSortable: "#sortable",
        helper: "clone",
        revert: "invalid"
    });
  }
});


问:
Namespaces in XML
I'm looking through previous exam-sets and one of the questions pertains to the usage of namespaces in an XML document. The question goes as follows:

What is the namespace of the element foo in the following XML document?

```<code><xyz xmlns="http://baz.net" xmlns:foo="http://www.foo.org">
    <namespace xmlns:xyz="http://www.foo.org"/>
    <def xmlns:dwebtek="http://www.cs.au.dk/dWebTek">
        <foo foo:xmlns="http://www.bar.com"/>
    </def>
</xyz>
</code>```

http://www.foo.org

http://www.bar.com

http://baz.net

The empty string

http://www.cs.au.dk/dWebTek

My initial thought was option 2. I noticed that they swapped foo and xmlns around in the foo element tag though. What impact does this have? Would this still be considered well-formed XML?

My second thought was then option 1, as in the xyz element tag they define the namespace for foo to "http://www.foo.org".

Checking the answer sheet however, it says the correct answer is option 3. Why is this? Could this be a mistake in the answer key? If not, why is option 2 incorrect?

EDIT: small correction

答:
So how can you tell that potame's explanation is actually correct?  It can be queried!

```<code>DECLARE @t XML = '
<xyz xmlns="http://baz.net" xmlns:foo="http://www.foo.org">
    <namespace xmlns:xyz="http://www.foo.org"/>
    <def xmlns:dwebtek="http://www.cs.au.dk/dWebTek">
        <foo foo:xmlns="http://www.bar.com"/>
    </def>
</xyz>';
</code>```

-- To see the NS of the 1st foo element
select @t.value('namespace-uri((//*:foo)[1])','varchar(200)');
-- To see the NS of all foo elements
select x.n.value('namespace-uri(.)','varchar(200)') from @t.nodes('//*:foo') x(n);
```

Thus proof that he is.

Title: Namespaces in XML

Body:
I'm looking through previous exam-sets and one of the questions pertains to the usage of namespaces in an XML document. The question goes as follows:

What is the namespace of the element foo in the following XML document?

<xyz xmlns="http://baz.net" xmlns:foo="http://www.foo.org">
    <namespace xmlns:xyz="http://www.foo.org"/>
    <def xmlns:dwebtek="http://www.cs.au.dk/dWebTek">
        <foo foo:xmlns="http://www.bar.com"/>
    </def>
</xyz>

http://www.foo.org

http://www.bar.com

http://baz.net

The empty string

http://www.cs.au.dk/dWebTek

My initial thought was option 2. I noticed that they swapped foo and xmlns around in the foo element tag though. What impact does this have? Would this still be considered well-formed XML?

My second thought was then option 1, as in the xyz element tag they define the namespace for foo to "http://www.foo.org".

Checking the answer sheet however, it says the correct answer is option 3. Why is this? Could this be a mistake in the answer key? If not, why is option 2 incorrect?

EDIT: small correction

Body:
So how can you tell that potame's explanation is actually correct?  It can be queried!

DECLARE @t XML = '
<xyz xmlns="http://baz.net" xmlns:foo="http://www.foo.org">
    <namespace xmlns:xyz="http://www.foo.org"/>
    <def xmlns:dwebtek="http://www.cs.au.dk/dWebTek">
        <foo foo:xmlns="http://www.bar.com"/>
    </def>
</xyz>';

-- To see the NS of the 1st foo element
select @t.value('namespace-uri((//*:foo)[1])','varchar(200)');
-- To see the NS of all foo elements
select x.n.value('namespace-uri(.)','varchar(200)') from @t.nodes('//*:foo') x(n);

Thus proof that he is.


问:
jQuery tablesorter does not work on my dynamically loaded table?
I'm trying to use the jquery.tablesorter.js on a dynamically loaded table. I can get it to work flawlessly on a table that is loaded at runtime but not on a table that is built by Ajax.

I have followed many previous tips I have found on here to no avail. Currently I am running a script to call table sorter on page load, with click of a button my table gets built and I call the an update to table sorter after the table is loaded into my page.

I have the following code.

```<code><!-- SCRIPT TO CALL TABLESORTER BEFORE TABLE IS BUILT -->
<script>
    $(document).ready(function () {
        $("#Observation").tablesorter();
    }
    );
</script>

<!-- SCRIPT TO BUILD TABLE AND CALL TRIGGER UPDATE TO TABLESORTER -->
<script>
    function loadObservations(status) {
        var xhttp = new XMLHttpRequest();
        var a = 'Status=' + status;
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                buildOpenTable(this);
            }
        };
        xhttp.open("POST", "http://localhost:57766/PALWebService.asmx/ObservationResult", true);

        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        xhttp.send(a);
    }
    function buildOpenTable(xml) {
        var i;
        var xmlDoc = xml.responseXML;
        var table = "<thead><tr><th>ID</th><th>SITE</th><th>BUILDING</th><th>OBSERVATION</th><th>ACTION</th><th>DATE OBSERVED</th><th>UPDATED BY</th><th></th></tr></thead>";
        var x = xmlDoc.getElementsByTagName("CurrentObservation");

        for (i = 0; i < x.length; i++) {
            table += "<tbody><tr><td class=col1>" +
                x[i].getElementsByTagName("GUID")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("SITE")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("BUILDING")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("OBSERVATION_DETAIL")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("ACTION")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("DATE_OBSERVED")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("UPDATED_BY")[0].childNodes[0].nodeValue +
                "</td><td>" +
                "<span class=btnSelect id=btnSelect>Select</span>" +
                "</td ></tr ></tbody> ";
        }
        document.getElementById("Observation").innerHTML = table;
        $("#Observation").trigger("update");
        window.location.hash = "#tableSummary";
    }

</script>

<!-- TABLE SUMMARY OF OBSERVATIONS -->
<div class="container-fluid" id="tableSummary">
    <h3 class="text-center">Observation Summary</h3>
    <div class="table-responsive">
        <table id="Observation" class="tablesorter table table-condensed table-hover table-bordered"  style="background-color:white"></table>
    </div>
</div>
</code>```

答:
When an "update" is triggered, tablesorter is only expecting the contents of the tbody to have changed. It will ignore any thead modifications, and if you completely replace the thead, the click bindings are not reapplied.

In your case it appears that the thead isn't changing, so I would recommend only modifying the tbody:

```<code>function buildOpenTable(xml) {
    var i;
    var xmlDoc = xml.responseXML;
    var tbody = "";
    var x = xmlDoc.getElementsByTagName("CurrentObservation");

    for (i = 0; i < x.length; i++) {
        tbody += "<tr><td class=col1>" +
            x[i].getElementsByTagName("GUID")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("SITE")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("BUILDING")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("OBSERVATION_DETAIL")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("ACTION")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("DATE_OBSERVED")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("UPDATED_BY")[0].childNodes[0].nodeValue +
            "</td><td>" +
            "<span class=btnSelect id=btnSelect>Select</span>" +
            "</td ></tr >";
    }
    $("#Observation tbody").html(tbody);
    $("#Observation").trigger("update");
    window.location.hash = "#tableSummary";
}
</code>```

Body:
I'm trying to use the jquery.tablesorter.js on a dynamically loaded table. I can get it to work flawlessly on a table that is loaded at runtime but not on a table that is built by Ajax.

I have followed many previous tips I have found on here to no avail. Currently I am running a script to call table sorter on page load, with click of a button my table gets built and I call the an update to table sorter after the table is loaded into my page.

I have the following code.

Observation Summary

Body:
When an "update" is triggered, tablesorter is only expecting the contents of the tbody to have changed. It will ignore any thead modifications, and if you completely replace the thead, the click bindings are not reapplied.

In your case it appears that the thead isn't changing, so I would recommend only modifying the tbody:

function buildOpenTable(xml) {
    var i;
    var xmlDoc = xml.responseXML;
    var tbody = "";
    var x = xmlDoc.getElementsByTagName("CurrentObservation");

    for (i = 0; i < x.length; i++) {
        tbody += "<tr><td class=col1>" +
            x[i].getElementsByTagName("GUID")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("SITE")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("BUILDING")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("OBSERVATION_DETAIL")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("ACTION")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("DATE_OBSERVED")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("UPDATED_BY")[0].childNodes[0].nodeValue +
            "</td><td>" +
            "<span class=btnSelect id=btnSelect>Select</span>" +
            "</td ></tr >";
    }
    $("#Observation tbody").html(tbody);
    $("#Observation").trigger("update");
    window.location.hash = "#tableSummary";
}


问:
How to treat a var as both int and string.
```<code>def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
</code>```

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

答:
You can use casting to change the structure of the var. You can either use them as strings and for total use this line:

```<code> total = int(first) + int(second)
</code>```

or use them as int and cast them to string in the print by using str(first) and str(second)

Best

Body:
def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

Body:
You can use casting to change the structure of the var. You can either use them as strings and for total use this line:

 total = int(first) + int(second)

or use them as int and cast them to string in the print by using str(first) and str(second)

Best


问:
Does EMRFS make S3 consistent for external clients
If I have a file in HFDS, or on the local filesystem, is it possible to copy this to S3 with EMRFS enabled, immediately shutdown the cluster, and have the file be guaranteed available for both listing and reading to external readers as soon as this copy operation is complete?  Or is EMRFS only consistent within the specific EMR cluster it was enabled for?  What would copying a file to S3 via EMRFS from HDFS look like?  From the local filesystem?</p>

答:
EMRFS is a consistent view enabled for objects that are created by the EMR hadoop jobs .

1) The main purpose of EMRFS is, the objects created by the hadoop jobs are immediate consistent. So the files can be used for the next job if there is dependency.

2) The way you copy files to S3 to make imediate consistent to next hadoop jobs is , copy the file to hdfs, and then copy to s3
Commands using following.

Hdfs dfs -put file.txt /user/hadoop/

hdfs dfs -cp /user/hadoop/file.txt s3://bucket-name

List the files in s3 is very costly, if you want data to be immediate consistency on s3, you have to implement the index on s3. Following is the link to have files immediate consistent using dynamodb
https://aws.amazon.com/blogs/big-data/building-and-maintaining-an-amazon-s3-metadata-index-without-servers/?

When you use s3 api then s3 consistency comes into picture because it will not goes through EMRFS metadata.


问:
Bars beginning at 1 instead of 0
I'm trying to build a bar chart chart with a logarithmic axis, but I want the bars to begin at one instead of zero. So far I have a basic bar chart,

```<code>df <- data.frame(Categ=c("a","b","a","a","b"),Num=c(1,2,3,4,5),Value=c(1.56,0.85,10.6,8.9,32.8))
plot_ly(data=df,x=~Num,y=~Value,type="bar",color=~Categ) %>%
layout(yaxis=list(exponentformat='power',type='log',title=ylab),legend=list(orientation='h'))
</code>```

And I can add white bars so everything goes from 1:

```<code>plot_ly(data=df,x=~Num,y=~rep(1,5),type="bar",opacity=0.0,showlegend=FALSE) %>%
add_trace(y=~(Value-1),opacity=1.0,color=~Categ,showlegend=TRUE) %>%
layout(yaxis=list(exponentformat='power',type='log'),legend=list(orientation='h'),barmode='stack')
</code>```

The issue here is if you double click the legend, to show only category b then the white bars also disappear and any values below 1 disappear.
I'm wondering if there are any better solutions to this problem, or a way to make the white bars permanent so values less than 1 are always displayed.

答:
I found a way around this, after scanning through the documentation a bunch...
https://plot.ly/r/reference/
If you use the base command, it sets the base to whatever you need.</p>

```<code>plot_ly(data=df,x=~Num,y=~(Value-1),base=1,type="bar",color=~Categ,showlegend=TRUE) %>%
layout(yaxis=list(exponentformat='power',type='log'),legend=list(orientation='h'))
</code>```

Title: Bars beginning at 1 instead of 0

Body:
I'm trying to build a bar chart chart with a logarithmic axis, but I want the bars to begin at one instead of zero. So far I have a basic bar chart,

df <- data.frame(Categ=c("a","b","a","a","b"),Num=c(1,2,3,4,5),Value=c(1.56,0.85,10.6,8.9,32.8))
plot_ly(data=df,x=~Num,y=~Value,type="bar",color=~Categ) %>%
layout(yaxis=list(exponentformat='power',type='log',title=ylab),legend=list(orientation='h'))

And I can add white bars so everything goes from 1:

plot_ly(data=df,x=~Num,y=~rep(1,5),type="bar",opacity=0.0,showlegend=FALSE) %>%
add_trace(y=~(Value-1),opacity=1.0,color=~Categ,showlegend=TRUE) %>%
layout(yaxis=list(exponentformat='power',type='log'),legend=list(orientation='h'),barmode='stack')

The issue here is if you double click the legend, to show only category b then the white bars also disappear and any values below 1 disappear.
I'm wondering if there are any better solutions to this problem, or a way to make the white bars permanent so values less than 1 are always displayed.

Body:
I found a way around this, after scanning through the documentation a bunch...
https://plot.ly/r/reference/
If you use the base command, it sets the base to whatever you need.

plot_ly(data=df,x=~Num,y=~(Value-1),base=1,type="bar",color=~Categ,showlegend=TRUE) %>%
layout(yaxis=list(exponentformat='power',type='log'),legend=list(orientation='h'))


问:
How to create Table using TableContainer in Dojo in a specific format
Can we use dojox/layout/TableContainer to show a table with Headers and multiple rows eg.

```<code> Id    ||       Header1              ||     Header2

 1     ||     Editable-TextBox1      ||   Combobox1
 2     ||     Editable-TextBox2      ||   Combobox1
</code>```

Thanks in advance.

答:
Yes, you can use table container to create a table like HTML. Please go through below link which explains what a table container is and how to create one.

https://dojotoolkit.org/reference-guide/1.10/dojox/layout/TableContainer.html

Body:
Can we use dojox/layout/TableContainer to show a table with Headers and multiple rows eg.

 Id    ||       Header1              ||     Header2

 1     ||     Editable-TextBox1      ||   Combobox1
 2     ||     Editable-TextBox2      ||   Combobox1

Thanks in advance.


问:
Vuejs constants from backend API
I have an API at my backend

```<code>api/v1/constants
</code>```

that returns all the application constants when requested. I want to call this API when my Vuejs application gets loaded and set these constants somewhere so that each vuejs component can import these constants and use them.

I can call this API in my root component and pass constants as a prop wherever needed. But it is making a chain of passing a prop to nested components.

For example

component A passes constants to component B,

component B passes constants to component C,

and so on....

Please recommend if somebody has a better way to manage this.

答:
```<code>Vue.prototype.$constants = <your constants>
</code>```

Can be used anywhere in a Vue or component as

```<code>this.$constants.<some constant>
</code>```

Title: Vuejs constants from backend API

Body:
I have an API at my backend

api/v1/constants

that returns all the application constants when requested. I want to call this API when my Vuejs application gets loaded and set these constants somewhere so that each vuejs component can import these constants and use them.

I can call this API in my root component and pass constants as a prop wherever needed. But it is making a chain of passing a prop to nested components.

For example

component A passes constants to component B,

component B passes constants to component C,

and so on....

Please recommend if somebody has a better way to manage this.

Body:
Vue.prototype.$constants = <your constants>

Can be used anywhere in a Vue or component as

this.$constants.<some constant>


问:
NSButton state issues
I have two ViewControllers.
On VC1 I have search criteria and on VC2 I have the search results. If you want to go from VC2 to VC1 the VC2 is dismissed.

On VC1 I have an NSButton(style Check, type Switch) which by default I want it to be in ON state. The purpose of the NSButton is to include photos in the results.

If the user unchecks the button and presses search, it will go on to VC2 showing the search results without photos.

BUT when the user goes back to VC1 for a new search that's where the unwanted behaviour occurs:
The NSButton is unchecked(i want it to be checked by default, every time the user is at the VC1. Also, the button is nil.

Why is this happening, and how can i make it the button box to be ticked everytime the VC2 is dismissed?

I tried enabling it and setting it to ONState but as its nil it would crash.

答:
To set a state every time your controller opens use the method

```<code>-(void)viewWillAppear
</code>```

To let viewControllers communicate with each other you can implement delegates. Here is a pretty good tutorial: Link

Another approach is to communicate with Notifications -> Link

Or you can set values on methods like prepareForSegue - depending on what you use to imstantinate your controllers.

Title: NSButton state issues

Body:
To set a state every time your controller opens use the method

-(void)viewWillAppear

To let viewControllers communicate with each other you can implement delegates. Here is a pretty good tutorial: Link

Another approach is to communicate with Notifications -> Link

Or you can set values on methods like prepareForSegue - depending on what you use to imstantinate your controllers.


问:
Shell timeout does not stop cloudfoundry app-nozzle, there is still new output
I would like to run a CloudFoundry app-nozzle command for 10 seconds to gather some metrics about an application. Even though I stop the command, there is still new output in the output file afterwards. I have no idea what is happening.
My command (that would be run inside a script):

```<code>timeout 10s cf app-nozzle my_app --filter ContainerMetric > CF_nozzle.txt
</code>```

It looks that it stopped and exited in Git Bash, I can run other scripts, even after minutes there are new lines in the file. I closed the whole window, and it is still ongoing.

Update: I tried it in CLI only and after the timeout it still emmits data even to command line.

答: It seems that this might be a bug in Windows Git bash. The same command works well in Ubuntu terminal.</p>

Body:
I would like to run a CloudFoundry app-nozzle command for 10 seconds to gather some metrics about an application. Even though I stop the command, there is still new output in the output file afterwards. I have no idea what is happening.
My command (that would be run inside a script):

timeout 10s cf app-nozzle my_app --filter ContainerMetric > CF_nozzle.txt

It looks that it stopped and exited in Git Bash, I can run other scripts, even after minutes there are new lines in the file. I closed the whole window, and it is still ongoing.

Update: I tried it in CLI only and after the timeout it still emmits data even to command line.


问:
Color Scheme Plugin JAR file cant be imported, but individual files inside jar can be imported
I am a developer of an IntelliJ Plugin. It is a color scheme where I only change the editor colors (not the colors of the IDE). I originally had only one color scheme file for my whole plugin (one .icls file), and that code is live and working online.

Recently, I updated my color scheme to include two additional color schemes, which meant I had to add two new .icls files. This works on my local IDE that I am developing on; however, when I tested the finished plugin, the new instance of IntelliJ IDEA CE cannot extract the content from the new files.

Problem

I need a working JAR file that I can upload into the JetBrain Plugin Repository; however, I cannot create a working Jar file anymore.

Note: I am not looking to import a color scheme. I am a developer of a color scheme that needs to upload my plugin into the Jetbrain Plugin Repository

When I tested the Color Scheme through build, deploy, and run, the new instance of the IDE will fail to find any color scheme. I cannot seem to narrow down why the IDE cannot load the color scheme; however, I was able to do the following...

From the deployed JAR file, rename the file to be a zip file

Extract the content of the zip file

then...

try Settings >> Editor >> Color Scheme >> Import Scheme... >> Settings (.jar) and find the JAR file. Nothing happens. No color schemes were imported.

...but...

try Settings >> Editor >> Color Scheme >> Import Scheme... >> IntelliJ IDEA color scheme (.icls) and find each of the .icls files. Each individual color scheme is successfully found and loaded into the IDE.

Additional Information

Originally, I was receiving the following issue that I filed in JetBrain's Issue Tracker. However, after some tinkering, I was receiving a different set of issues. So, I started a new project and just copied the source files and plugin.xml file into the new project. Built, Deployed, and tested. No errors, no warnings (that I saw), but the color schemes are still not being loaded into the IDE.

答:
Cristopher, currently color schemes are supposed to be imported from settings.jar created  by Intellij IDEA upon File|Export Settings. The file has a certain structure, namely a 'colors' subdirectory with .icls files inside it. The IDE doesn't scan for other places where the files might reside.
If you create a plug-in, your users simply install it as a regular plugin, not importing any schemes. The difference is that these schemes become bundled. It means when a user makes changes to them, he can always revert to original color settings.</p>


问:
Sampling Bernoulli random variables in TensorFlow
Given a 1D tensor containing the means of a Bernoulli distribution, how do I sample a corresponding 1D tensor with the given means?

TensorFlow only seems to have random_normal and random_uniform functions implemented. I could use something complicated like:

```<code>tf.ceil(tf.sub(tf.random_uniform((1, means.get_shape()[0])),means))
</code>```

but the ceil function has no gradient defined in TensorFlow.

答:
Since TFr1.0, tf.select is deprecated in favor of tf.where. Furthermore, the answer given by @keveman should compare the uniform random sampling with < 0, neither with > 0.5 nor with > 0:

```<code>    means = tf.constant([.3,.8])
    sample = tf.where(tf.random_uniform([1, 2]) - means < 0,
      tf.ones([1,2]), tf.zeros([1,2]))
    with tf.Session(''): sample.eval()
</code>```

Body:
Given a 1D tensor containing the means of a Bernoulli distribution, how do I sample a corresponding 1D tensor with the given means?

TensorFlow only seems to have random_normal and random_uniform functions implemented. I could use something complicated like:

tf.ceil(tf.sub(tf.random_uniform((1, means.get_shape()[0])),means))

but the ceil function has no gradient defined in TensorFlow.

Body:
Since TFr1.0, tf.select is deprecated in favor of tf.where. Furthermore, the answer given by @keveman should compare the uniform random sampling with < 0, neither with > 0.5 nor with > 0:

    means = tf.constant([.3,.8])
    sample = tf.where(tf.random_uniform([1, 2]) - means < 0,
      tf.ones([1,2]), tf.zeros([1,2]))
    with tf.Session(''): sample.eval()