问:
Traversing an object in javascript and convert it in specific format
I have the following object structure:

```<code>{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}
</code>```

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

```<code>const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");
</code>```

My expected output should be

```<code>[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]
</code>```

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output

答:
there are two things you are missing to get the expected output:
 - You are not adding the path when data["key"] is not an object
 - You are looking for get an array output but you are printing every element separatedly.

Looking at you desired output i see the path always includes b, even when b and c are siblings, and that doesn´t allow have them both in the same path.Taking this as a typing mistake, I modified a bit the script in order to get the correct output:

var data = {a: { b: "abc", c: [ { d: "pqr", e: true},{ f: 1, e: ["xyz", 1] }]}};

var output = [];

getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
        path.push(key)
        getFinalNode(data[key], path)

        // console.log(true);
        if (typeof data[key] != 'object'){
        output.push({
          value: data[key],
          key: key,
          path:path.join("/")
        });}
    }
  }
  path.splice(-1,1)
}

getFinalNode(data, []);

console.log(output);```

Body:
I have the following object structure:

{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");

My expected output should be

[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output


来源: stackexchange

问:
Ionic 3 native deeplinking
Managed to install and setup the native deeplinking module for Ionic.

App loads up fine even in cold state, where it is fully shutdown.

However, my route doesn't take me to the correct page. It just displays the last page the app was one, or the main page if it starts the application from cold state.

app.component.ts

```<code>...
import { Deeplinks } from '@ionic-native/deeplinks';
import { Detail1Page } from '../pages/layout/app1/detail1/detail1';
...
constructor(private deeplinks: Deeplinks.........
...
this.platform.ready().then(() => {
this.splashScreen.hide();
this.deeplinks.route({
  '/item/:itemId': Detail1Page
}).subscribe((match) => {
    console.log('Successfully matched route', JSON.stringify(match));
  }, (nomatch) => {
    console.error('Got a deeplink that didn\'t match', JSON.stringify(nomatch));
  });
}
...
</code>```

The console log shows:

```<code>Successfully matched route {"$args":{"itemId":"9"},"$link":{"path":"/item/9","queryString":"","fragment":"","host":"my.app.com","url":"https://my.app.com/item/9","scheme":"https"}}
</code>```

app.module.ts

```<code>...
import { Deeplinks } from '@ionic-native/deeplinks';
...
providers: [
    Deeplinks,
...
</code>```

detail1.ts

```<code>...
this.itemId = this.navParams.get('itemId');
...
</code>```

Your help is greatly appreciated - been working on this the whole day :)

答:
I ran into that same problem just yesterday...

In my case, I didn't register my page everywhere that your supposed to in my app.module.

```<code>@NgModule({
  declarations: [
    MyPage
  ],
  imports: [
    IonicPageModule.forChild(MyPage)
  ],
  entryComponents: [
    MyPage
  ]
})
export class MyPageModule {}
</code>```

For me I was missing the IonicPageModule.forChild reference.
Here is the documentation page where it talks about setting a page up for deeplinking.
https://ionicframework.com/docs/api/navigation/IonicPage/#usage

ContentLicense: CC BY-SA 3.0

Title: Ionic 3 native deeplinking

Body:
Managed to install and setup the native deeplinking module for Ionic.

App loads up fine even in cold state, where it is fully shutdown.

However, my route doesn't take me to the correct page. It just displays the last page the app was one, or the main page if it starts the application from cold state.

app.component.ts

...
import { Deeplinks } from '@ionic-native/deeplinks';
import { Detail1Page } from '../pages/layout/app1/detail1/detail1';
...
constructor(private deeplinks: Deeplinks.........
...
this.platform.ready().then(() => {
this.splashScreen.hide();
this.deeplinks.route({
  '/item/:itemId': Detail1Page
}).subscribe((match) => {
    console.log('Successfully matched route', JSON.stringify(match));
  }, (nomatch) => {
    console.error('Got a deeplink that didn\'t match', JSON.stringify(nomatch));
  });
}
...

The console log shows:

Successfully matched route {"$args":{"itemId":"9"},"$link":{"path":"/item/9","queryString":"","fragment":"","host":"my.app.com","url":"https://my.app.com/item/9","scheme":"https"}}

app.module.ts

...
import { Deeplinks } from '@ionic-native/deeplinks';
...
providers: [
    Deeplinks,
...

detail1.ts

...
this.itemId = this.navParams.get('itemId');
...

Your help is greatly appreciated - been working on this the whole day :)

Body:
I ran into that same problem just yesterday...

In my case, I didn't register my page everywhere that your supposed to in my app.module.

@NgModule({
  declarations: [
    MyPage
  ],
  imports: [
    IonicPageModule.forChild(MyPage)
  ],
  entryComponents: [
    MyPage
  ]
})
export class MyPageModule {}

For me I was missing the IonicPageModule.forChild reference.
Here is the documentation page where it talks about setting a page up for deeplinking.
https://ionicframework.com/docs/api/navigation/IonicPage/#usage

ContentLicense: CC BY-SA 4.0


问:
Error while doing Linear Regression in R
I am trying to do a simple linear regression in R and I keep getting an error.
Here is my code:

```<code>> LinearMod <- lm('2015--teen pregnancy rates' ~ '2012 -- Domestic Violence Calls For Service per 1,000 Residents', data=Copy_of_BNIA_data_7_24_17)
</code>```

I keep getting this error:
Error in terms.formula(formula, data = data) :
  invalid term in model formula

Also here is some more info:

```<code>> str(Copy_of_BNIA_data_7_24_17)
</code>```

$ 2012 -- Domestic Violence Calls For Service per 1,000 Residents                                              : num  60.5 51.5 56...
 $ 2015--teen pregnancy rates                                                                                : num  126.3 73.9 69 ...

```<code>> dput(head(Copy_of_BNIA_data_7_24_17, 10))
</code>```

structure(list( 2012 -- Domestic Violence Calls For Service per 1,000 Residents = c(60.5,
51.5, 56.6),
"2015--teen pregnancy rates"), row.names = c(NA, 10L), class = c("tbl_df",
"tbl", "data.frame")

Please let me know what the issue is. Thank you!

答:
sample data:

```<code>library(data.table)

Copy_of_BNIA_data_7_24_17 <- data.table("2015--teen pregnancy rates" = c(0,1,4,5),
                 "2012 -- Domestic Violence Calls For Service per 1,000 Residents" = c(10,12,15,16))
</code>```

Linear regression formula:

```<code>LinearMod <- lm(`2015--teen pregnancy rates` ~ `2012 -- Domestic Violence Calls For Service per 1,000 Residents`, data=Copy_of_BNIA_data_7_24_17)
</code>```

In the lm formula you shouldn't put the single quote ' but the symbol above the tab button: `

Body:
I am trying to do a simple linear regression in R and I keep getting an error.
Here is my code:

> LinearMod <- lm('2015--teen pregnancy rates' ~ '2012 -- Domestic Violence Calls For Service per 1,000 Residents', data=Copy_of_BNIA_data_7_24_17)

I keep getting this error:
Error in terms.formula(formula, data = data) :
  invalid term in model formula

Also here is some more info:

> str(Copy_of_BNIA_data_7_24_17)

$ 2012 -- Domestic Violence Calls For Service per 1,000 Residents                                              : num  60.5 51.5 56...
 $ 2015--teen pregnancy rates                                                                                : num  126.3 73.9 69 ...

> dput(head(Copy_of_BNIA_data_7_24_17, 10))

structure(list( 2012 -- Domestic Violence Calls For Service per 1,000 Residents = c(60.5,
51.5, 56.6),
"2015--teen pregnancy rates"), row.names = c(NA, 10L), class = c("tbl_df",
"tbl", "data.frame")

Please let me know what the issue is. Thank you!

Body:
sample data:

library(data.table)

Copy_of_BNIA_data_7_24_17 <- data.table("2015--teen pregnancy rates" = c(0,1,4,5),
                 "2012 -- Domestic Violence Calls For Service per 1,000 Residents" = c(10,12,15,16))

Linear regression formula:

LinearMod <- lm(`2015--teen pregnancy rates` ~ `2012 -- Domestic Violence Calls For Service per 1,000 Residents`, data=Copy_of_BNIA_data_7_24_17)

In the lm formula you shouldn't put the single quote ' but the symbol above the tab button: `


问:
SQL Server - What coding/development rules does your team have in place?
I asked a similar question last week and didn't get a very good response, so perhaps I didn't phrase the question in the right way.

I'd like to know what processes/policies/rules your team has in place for writing T-SQL code and database schema. Here are a couple examples:

```<code>1) All foreign key columns should be indexed
2) All primary key columns should be integer Identity
3) All stored procedures/user defined functions need comments
4) No underscores in T-SQL variable names
</code>```

These are the sorts of things I'm curious about.

Thanks!

答:
Not really. We don't have indexes on some larger table FKs because we never delete or update the parent value, or poor selectivity

Mostly, but understand why. That said, I'd use the 3 digit code itself for a table that stored ISO currency codes such as CHF or GBP. And you'll still need a unique constraint on the natural key

ContentLicense: CC BY-SA 2.5

Body:
I asked a similar question last week and didn't get a very good response, so perhaps I didn't phrase the question in the right way.

I'd like to know what processes/policies/rules your team has in place for writing T-SQL code and database schema. Here are a couple examples:

1) All foreign key columns should be indexed
2) All primary key columns should be integer Identity
3) All stored procedures/user defined functions need comments
4) No underscores in T-SQL variable names

These are the sorts of things I'm curious about.

Thanks!


问:
Move the PDF's from folders to a "not to be sent folder" in SSIS
I have about a dozen folders with up to 2500 PDF's. I need to move out 163 of the PDF's from t-SQL statement into a "not to be sent" folder in SSIS.. I already have the for each loop container and file system task.. How can I only search/select the files from my T-SQL statement to be moved?

Note: I already have the filenames that need to be moved in my T-SQL statement

答:
I think you might be asking, how do i use the TSQL statement and results from it in SSIS.

Create a variable filenames type ADO.Object

Add an execute SQL task

Add you TSQL to it

Change Result Set to Full

Map Result Set to @filenames

Add for each

Enumerator is Foreach ADO Enum

Set filenames as object

Map a new variable type string called filename to index 0

Add your file Transfer Task and use filename.

*** This assumes that filename has the full path.


问:
For loop is only checking last value
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}
</code>```

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

答:
You are going through the entire list and resetting the return value every time so the last one is the only one which matters.  You need something like:</p>

```<code>boolean userFound = false;
for (User u : localArray )
{
    if (u.getUsername().equals(username))
    {
        userFound = true;
        break;
    }
 }

return userFound ;
</code>```

Title: For loop is only checking last value

Body:
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

Body:
You are going through the entire list and resetting the return value every time so the last one is the only one which matters.  You need something like:

boolean userFound = false;
for (User u : localArray )
{
    if (u.getUsername().equals(username))
    {
        userFound = true;
        break;
    }
 }

return userFound ;


问:
Efficient/optimized way of evaluating several conditions?
Which of the following code snippets (A and B below) is more efficient (performance wise) and why?

Furthermore:

Does the compiler rearrange the validate() method calls so that they are called "when needed" i.e. when evaluating each separate condition in the if-statement? In other words, will the compiler treat snippet A just as if it were written as snippet B?

Are there other alternatives (besides snippet A and B) for better perfomance?

(validate(...) checks if a field (provided as an argument)  contains valid values)

Snippet A:

```<code>    boolean okTitle = validate(inputTitle);
    boolean okLocation = validate(inputLocation);
    boolean okDuration = validate(inputDuration);
    boolean okReminder = validate(inputReminder);
    boolean okRepetition = validate(inputRepetition);
    boolean okDate = validate(inputDate);

    if(okTitle && (okLocation || okDuration || okReminder || okRepetition || okDate)){
        setEnabled(true);
    }else{
        setEnabled(false);
    }
</code>```

Snippet B:

```<code>setEnabled(
     validate(inputTitle) &&
     ( validate(inputLocation) || validate(inputDuration) || validate(inputReminder) || validate(inputRepetition) || validate(inputDate) )
   );
</code>```

答:
Not related to the compiler, how the code will be executed depend on the values of input at runtime.

Snippet B will certainly be better performance-wise than snippet A, because A will execute all validate() calls but B will stop when the conditions are satisfied.

When I was younger I would definitely prefer B over A because of the performance advantage. Now, if the validate() method is not really "expensive" to call, I would definitely choose A, because it is much more readable and easier to maintain than B.

Body:
Which of the following code snippets (A and B below) is more efficient (performance wise) and why?

Furthermore:

Does the compiler rearrange the validate() method calls so that they are called "when needed" i.e. when evaluating each separate condition in the if-statement? In other words, will the compiler treat snippet A just as if it were written as snippet B?

Are there other alternatives (besides snippet A and B) for better perfomance?

(validate(...) checks if a field (provided as an argument)  contains valid values)

Snippet A:

    boolean okTitle = validate(inputTitle);
    boolean okLocation = validate(inputLocation);
    boolean okDuration = validate(inputDuration);
    boolean okReminder = validate(inputReminder);
    boolean okRepetition = validate(inputRepetition);
    boolean okDate = validate(inputDate);

    if(okTitle && (okLocation || okDuration || okReminder || okRepetition || okDate)){
        setEnabled(true);
    }else{
        setEnabled(false);
    }

Snippet B:

setEnabled(
     validate(inputTitle) &&
     ( validate(inputLocation) || validate(inputDuration) || validate(inputReminder) || validate(inputRepetition) || validate(inputDate) )
   );


问:
Select Blob return a function
```<code>exports.carregaContrato = function(id, cb){
  Firebird.attach(firebirdConfig, function (err, db) {
    if (err)
      throw err;

    db.query("select contrato_escaniado as IMAGE from cad_prospectos_contratos where codigo = ?", [id], function(err, result){
      console.log(err, result[0].IMAGE)
      db.detach();
      cb(result)
    })

   })
}
</code>```

I have this select from a Blob field I do not know what I'm doing wrong that the feedback I get is a function. In the console.log I have I get the following:

```<code>undefined [Function]
</code>```

What I'm doing wrong, and how to solve. I want to receive as a return an image that I saved converted to base64 as a string, it's like this in my bank:

答:
Solution: As my select will always return only a string I do not need for and as in the database it saves a string in base64 I just need this string using toString ()     </p>

```<code>result[0].IMAGE(function(err, name, eventEmitter) {
  var buffers = [];
  eventEmitter.on('data', function(chunk) {
    buffers.push(chunk);
  });
  eventEmitter.once('end', function() {
    var buffer = Buffer.concat(buffers);
    retorno = (buffer.toString());
    db.detach();
    cb(retorno)
  });
});
</code>```

Title: Select Blob return a function

Body:
exports.carregaContrato = function(id, cb){
  Firebird.attach(firebirdConfig, function (err, db) {
    if (err)
      throw err;

    db.query("select contrato_escaniado as IMAGE from cad_prospectos_contratos where codigo = ?", [id], function(err, result){
      console.log(err, result[0].IMAGE)
      db.detach();
      cb(result)
    })

   })
}

I have this select from a Blob field I do not know what I'm doing wrong that the feedback I get is a function. In the console.log I have I get the following:

undefined [Function]

What I'm doing wrong, and how to solve. I want to receive as a return an image that I saved converted to base64 as a string, it's like this in my bank:

Body:
Solution: As my select will always return only a string I do not need for and as in the database it saves a string in base64 I just need this string using toString ()

result[0].IMAGE(function(err, name, eventEmitter) {
  var buffers = [];
  eventEmitter.on('data', function(chunk) {
    buffers.push(chunk);
  });
  eventEmitter.once('end', function() {
    var buffer = Buffer.concat(buffers);
    retorno = (buffer.toString());
    db.detach();
    cb(retorno)
  });
});


问:
Passing String Arrays to Functions?

I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?

```<code>using System;

class SalesPeeps {

    string[] people = new string[8];
    double[] salaries = new double[8];

    static void Main() {

        getInformation(people);

    }

    static void getInformation(string[] arr) {

        int i = 0;

        do {

            Console.WriteLine("Please input a the sales person's last name.");
            i++;

        } while (i < people.Length);

    }
}
</code>```

答:
You cannot access non-static field people from static method Main. Change its declaration to:

```<code>static string[] people = new string[8];
</code>```

Title: Passing String Arrays to Functions?

Body:
I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?

using System;

class SalesPeeps {

    string[] people = new string[8];
    double[] salaries = new double[8];

    static void Main() {

        getInformation(people);

    }

    static void getInformation(string[] arr) {

        int i = 0;

        do {

            Console.WriteLine("Please input a the sales person's last name.");
            i++;

        } while (i < people.Length);

    }
}

Body:
You cannot access non-static field people from static method Main. Change its declaration to:

static string[] people = new string[8];


问:
sql test condition if failed move to next person
I am trying to get the urns that don't have a status_mvf  = 88

```<code>status_mvf    urn        desc        date
88            104        no show     2017-03-06
9             104        late        2017-03-07
2             104        on time     2017-03-08
2             210        on time     2017-03-06
2             210        on time     2017-03-07
9             320        late        2017-03-06

SELECT
    a.Status_Mvf,
    p.URN,
    v.ADMIT_DATE

FROM APPOINTMENT
WHERE  Status_Mvf <> '88'

--group by p.urn,

ORDER BY URN, STATUS_MVF
</code>```

Desired result - no urn 104 because it had an 88

```<code>status_mvf   urn       desc      date
2            210       on time   2017-03-06
2            210       on time   2017-03-07
9            320       late      2017-03-06
</code>```

答:
Try something like this (with a NOT IN statement):</p>

```<code>SELECT a.Status_Mvf, p.URN, v.ADMIT_DATE
FROM APPOINTMENT a
WHERE urn NOT IN
 (
    SELECT a2.urn FROM APPOINTMENT a2
    WHERE a2.Status_Mvf = '88'
 )
ORDER BY URN, STATUS_MVF
</code>```

Body:
I am trying to get the urns that don't have a status_mvf  = 88

status_mvf    urn        desc        date
88            104        no show     2017-03-06
9             104        late        2017-03-07
2             104        on time     2017-03-08
2             210        on time     2017-03-06
2             210        on time     2017-03-07
9             320        late        2017-03-06

SELECT
    a.Status_Mvf,
    p.URN,
    v.ADMIT_DATE

FROM APPOINTMENT
WHERE  Status_Mvf <> '88'

--group by p.urn,

ORDER BY URN, STATUS_MVF

Desired result - no urn 104 because it had an 88

status_mvf   urn       desc      date
2            210       on time   2017-03-06
2            210       on time   2017-03-07
9            320       late      2017-03-06

Body:
Try something like this (with a NOT IN statement):

SELECT a.Status_Mvf, p.URN, v.ADMIT_DATE
FROM APPOINTMENT a
WHERE urn NOT IN
 (
    SELECT a2.urn FROM APPOINTMENT a2
    WHERE a2.Status_Mvf = '88'
 )
ORDER BY URN, STATUS_MVF


问:
Kafka + Zookeeper: Connection to node -1 could not be established. Broker may not be available
I am running in my locahost both Zookeeper and Kafka (1 instance each).

I create succesfully a topic from kafka:

```<code>./bin/kafka-topics.sh --zookeeper localhost:2181 --create --replication-factor 1 --partitions 1 --topic Hello-Nicola

Created topic "Hello-Nicola".
</code>```

Kafka logs show:

```<code>[2017-12-06 16:00:17,753] INFO [KafkaServer id=0] started (kafka.server.KafkaServer)
[2017-12-06 16:03:19,347] INFO [ReplicaFetcherManager on broker 0] Removed fetcher for partitions Hello-Nicola-0 (kafka.server.ReplicaFetcherManager)
[2017-12-06 16:03:19,393] INFO Loading producer state from offset 0 for partition Hello-Nicola-0 with message format version 2 (kafka.log.Log)
[2017-12-06 16:03:19,406] INFO Completed load of log Hello-Nicola-0 with 1 log segments, log start offset 0 and log end offset 0 in 35 ms (kafka.log.Log)
[2017-12-06 16:03:19,408] INFO Created log for partition [Hello-Nicola,0] in /tmp/kafka-logs with properties {compression.type -> producer, message.format.version -> 1.0-IV0, file.delete.delay.ms -> 60000, max.message.bytes -> 1000012, min.compaction.lag.ms -> 0, message.timestamp.type -> CreateTime, min.insync.replicas -> 1, segment.jitter.ms -> 0, preallocate -> false, min.cleanable.dirty.ratio -> 0.5, index.interval.bytes -> 4096, unclean.leader.election.enable -> false, retention.bytes -> -1, delete.retention.ms -> 86400000, cleanup.policy -> [delete], flush.ms -> 9223372036854775807, segment.ms -> 604800000, segment.bytes -> 1073741824, retention.ms -> 604800000, message.timestamp.difference.max.ms -> 9223372036854775807, segment.index.bytes -> 10485760, flush.messages -> 9223372036854775807}. (kafka.log.LogManager)
[2017-12-06 16:03:19,409] INFO [Partition Hello-Nicola-0 broker=0] No checkpointed highwatermark is found for partition Hello-Nicola-0 (kafka.cluster.Partition)
[2017-12-06 16:03:19,411] INFO Replica loaded for partition Hello-Nicola-0 with initial high watermark 0 (kafka.cluster.Replica)
[2017-12-06 16:03:19,413] INFO [Partition Hello-Nicola-0 broker=0] Hello-Nicola-0 starts at Leader Epoch 0 from offset 0. Previous Leader Epoch was: -1 (kafka.cluster.Partition)
</code>```

But Zookeeper logs show:

```<code>2017-12-06 16:03:19,299 [myid:] - INFO  [ProcessThread(sid:0 cport:2181)::PrepRequestProcessor@653] - Got user-level KeeperException when processing sessionid:0x1000177fb3d0001 type:create cxid:0x43 zxid:0x26 txntype:-1 reqpath:n/a Error Path:/brokers/topics/Hello-Nicola/partitions/0 Error:KeeperErrorCode = NoNode for /brokers/topics/Hello-Nicola/partitions/0
2017-12-06 16:03:19,302 [myid:] - INFO  [ProcessThread(sid:0 cport:2181)::PrepRequestProcessor@653] - Got user-level KeeperException when processing sessionid:0x1000177fb3d0001 type:create cxid:0x44 zxid:0x27 txntype:-1 reqpath:n/a Error Path:/brokers/topics/Hello-Nicola/partitions Error:KeeperErrorCode = NoNode for /brokers/topics/Hello-Nicola/partitions
</code>```

If I try to produce messages:

```<code>./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Nicola
>ciao
[2017-12-06 16:04:21,897] WARN [Producer clientId=console-producer] Connection to node -1 could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2017-12-06 16:04:22,000] WARN [Producer clientId=console-producer] Connection to node -1 could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
</code>```

server.properties (in kafka) is:

```<code>broker.id=0
listeners=PLAINTEXT://mylocal-0:9092
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
num.partitions=1
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
group.initial.rebalance.delay.ms=0
</code>```

It seems that Zookeeper didn't registrer any broker.

Any suggestion, please?

答:
I found the error.
Observing zookeeper logs when the server started I noticed:

```<code>server.1=mylocal-0.:2888:3888
</code>```

with a dot (.) after the name of the host.

The script that produces the zookeeper's config is from
https://github.com/kubernetes/contrib/blob/master/statefulsets/zookeeper/zkGenConfig.sh

Looking inside I see that DOMAIN is not filled:

```<code>HOST=`hostname -s`
DOMAIN=`hostname -d`

function print_servers() {
    for (( i=1; i<=$ZK_REPLICAS; i++ ))
    do
        echo "server.$i=$NAME-$((i-1)).$DOMAIN:$ZK_SERVER_PORT:$ZK_ELECTION_PORT"
    done
}
</code>```

For my case (localhost) I don't need domain, so I removed that variable.

Now zookeeper and kafka communicate with no errors.

Body:
I am running in my locahost both Zookeeper and Kafka (1 instance each).

I create succesfully a topic from kafka:

./bin/kafka-topics.sh --zookeeper localhost:2181 --create --replication-factor 1 --partitions 1 --topic Hello-Nicola

Created topic "Hello-Nicola".

Kafka logs show:

[2017-12-06 16:00:17,753] INFO [KafkaServer id=0] started (kafka.server.KafkaServer)
[2017-12-06 16:03:19,347] INFO [ReplicaFetcherManager on broker 0] Removed fetcher for partitions Hello-Nicola-0 (kafka.server.ReplicaFetcherManager)
[2017-12-06 16:03:19,393] INFO Loading producer state from offset 0 for partition Hello-Nicola-0 with message format version 2 (kafka.log.Log)
[2017-12-06 16:03:19,406] INFO Completed load of log Hello-Nicola-0 with 1 log segments, log start offset 0 and log end offset 0 in 35 ms (kafka.log.Log)
[2017-12-06 16:03:19,408] INFO Created log for partition [Hello-Nicola,0] in /tmp/kafka-logs with properties {compression.type -> producer, message.format.version -> 1.0-IV0, file.delete.delay.ms -> 60000, max.message.bytes -> 1000012, min.compaction.lag.ms -> 0, message.timestamp.type -> CreateTime, min.insync.replicas -> 1, segment.jitter.ms -> 0, preallocate -> false, min.cleanable.dirty.ratio -> 0.5, index.interval.bytes -> 4096, unclean.leader.election.enable -> false, retention.bytes -> -1, delete.retention.ms -> 86400000, cleanup.policy -> [delete], flush.ms -> 9223372036854775807, segment.ms -> 604800000, segment.bytes -> 1073741824, retention.ms -> 604800000, message.timestamp.difference.max.ms -> 9223372036854775807, segment.index.bytes -> 10485760, flush.messages -> 9223372036854775807}. (kafka.log.LogManager)
[2017-12-06 16:03:19,409] INFO [Partition Hello-Nicola-0 broker=0] No checkpointed highwatermark is found for partition Hello-Nicola-0 (kafka.cluster.Partition)
[2017-12-06 16:03:19,411] INFO Replica loaded for partition Hello-Nicola-0 with initial high watermark 0 (kafka.cluster.Replica)
[2017-12-06 16:03:19,413] INFO [Partition Hello-Nicola-0 broker=0] Hello-Nicola-0 starts at Leader Epoch 0 from offset 0. Previous Leader Epoch was: -1 (kafka.cluster.Partition)

But Zookeeper logs show:

2017-12-06 16:03:19,299 [myid:] - INFO  [ProcessThread(sid:0 cport:2181)::PrepRequestProcessor@653] - Got user-level KeeperException when processing sessionid:0x1000177fb3d0001 type:create cxid:0x43 zxid:0x26 txntype:-1 reqpath:n/a Error Path:/brokers/topics/Hello-Nicola/partitions/0 Error:KeeperErrorCode = NoNode for /brokers/topics/Hello-Nicola/partitions/0
2017-12-06 16:03:19,302 [myid:] - INFO  [ProcessThread(sid:0 cport:2181)::PrepRequestProcessor@653] - Got user-level KeeperException when processing sessionid:0x1000177fb3d0001 type:create cxid:0x44 zxid:0x27 txntype:-1 reqpath:n/a Error Path:/brokers/topics/Hello-Nicola/partitions Error:KeeperErrorCode = NoNode for /brokers/topics/Hello-Nicola/partitions

If I try to produce messages:

./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Nicola
>ciao
[2017-12-06 16:04:21,897] WARN [Producer clientId=console-producer] Connection to node -1 could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2017-12-06 16:04:22,000] WARN [Producer clientId=console-producer] Connection to node -1 could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)

server.properties (in kafka) is:

broker.id=0
listeners=PLAINTEXT://mylocal-0:9092
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
num.partitions=1
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
group.initial.rebalance.delay.ms=0

It seems that Zookeeper didn't registrer any broker.

Any suggestion, please?

Body:
I found the error.
Observing zookeeper logs when the server started I noticed:

server.1=mylocal-0.:2888:3888

with a dot (.) after the name of the host.

The script that produces the zookeeper's config is from
https://github.com/kubernetes/contrib/blob/master/statefulsets/zookeeper/zkGenConfig.sh

Looking inside I see that DOMAIN is not filled:

HOST=`hostname -s`
DOMAIN=`hostname -d`

function print_servers() {
    for (( i=1; i<=$ZK_REPLICAS; i++ ))
    do
        echo "server.$i=$NAME-$((i-1)).$DOMAIN:$ZK_SERVER_PORT:$ZK_ELECTION_PORT"
    done
}

For my case (localhost) I don't need domain, so I removed that variable.

Now zookeeper and kafka communicate with no errors.


问:
Brace on new line only if current line overflows clang format
I've recently decided to include a .clang-format file in a C++ project of mine to make the code more uniform and easy to read. I mostly like the Google defaults, except I'd like to use 4 space indents instead of two.

The problem with this is that it makes certain statements harder to read when the current line overflows the 80 character column limit. For example, in an if statement that overflows:

```<code>if (some_condition || some_other_condition ||
    yet_another_condition) {
    // block starts here
}
</code>```

The alignment of yet_another_condition matches that of the start of the if-block, which makes it hard to read without some kind of a break. Ideally, what I would want to happen in this situation is something like this:

```<code>if (some_condition || some_other_condition ||
    yet_another_condition)
{
    // block starts here
}
</code>```

However, I only want the opening brace on a new line when the current line overflows into the next, like in the above example. In all other cases I want the opening brace on the same line (that goes for if/for/while/switch etc. statements as well as functions).

Is it possible to specify this behavior in my .clang-format file while keeping the rest of the Google defaults intact?

答:
The clang-format tool allows to specify custom brace wrapping with BraceWrapping: Custom, but it is not flexible enough to be aware of the context you require.

The alternative solution to improve readability is to use continuation indent greater than 4, e.g. ContinuationIndentWidth: 8.

Body:
I've recently decided to include a .clang-format file in a C++ project of mine to make the code more uniform and easy to read. I mostly like the Google defaults, except I'd like to use 4 space indents instead of two.

The problem with this is that it makes certain statements harder to read when the current line overflows the 80 character column limit. For example, in an if statement that overflows:

if (some_condition || some_other_condition ||
    yet_another_condition) {
    // block starts here
}

The alignment of yet_another_condition matches that of the start of the if-block, which makes it hard to read without some kind of a break. Ideally, what I would want to happen in this situation is something like this:

if (some_condition || some_other_condition ||
    yet_another_condition)
{
    // block starts here
}

However, I only want the opening brace on a new line when the current line overflows into the next, like in the above example. In all other cases I want the opening brace on the same line (that goes for if/for/while/switch etc. statements as well as functions).

Is it possible to specify this behavior in my .clang-format file while keeping the rest of the Google defaults intact?


问:
C++ suffix L vs specifying long double
Question What does the "L" mean at the end of an integer literal? describes what L means at the end of int literal. I am confused why not to specify long int i = 33 instead of int i = 33L? The same thing applies to other types. Instead of specifying double b = 3.0L why not to write long double?

答:
Although in many instances, you can rely on the extremely well-defined widening conversion rules, sometimes you need to be explicit about the type of a literal.

For example

```<code>long double f = 1.0;
f = std::max(f, 2.0L);
</code>```

does not compile unless the arguments of max have the same type. Writing double b = 3.0L would indeed be pointless, and a compiler will almost certainly ignore you and compile double b = 3.0.

Title: C++ suffix L vs specifying long double

Body:
Although in many instances, you can rely on the extremely well-defined widening conversion rules, sometimes you need to be explicit about the type of a literal.

For example

long double f = 1.0;
f = std::max(f, 2.0L);

does not compile unless the arguments of max have the same type. Writing double b = 3.0L would indeed be pointless, and a compiler will almost certainly ignore you and compile double b = 3.0.


问:
Excel VBA To Split Workbook Every 4 Worksheets
I have a workbook that contains about 100 worksheets.  I want to create 25 individual workbooks that contain 4 sheets each.  I am trying to write an Excel VBA foor loop that will do such - but it is generating a workbook for every 1 page.

```<code>totalPages = PDDoc.GetNumPages

For i = 1 To totalPages - 4
    'This is where you would add the workbook and transfer the page
Next i
</code>```

答:
```<code>Sub SplitPages()
   Dim i As Integer

   Dim wb As Workbook

   For i = 1 To ThisWorkbook.Worksheets.Count
        If i Mod 4 = 1 Then
           Set wb = Workbooks.Add
        End If
       ThisWorkbook.Worksheets(i).Copy wb.Worksheets(1)
    Next i
End Sub
</code>```

You have to copy to avoid messing up the count, and the new workbooks have an extra sheet - but a quick

```<code>  for each wb in workbooks:wb.sheets("sheet1").delete:next wb
</code>```

will fix that

Body:
I have a workbook that contains about 100 worksheets.  I want to create 25 individual workbooks that contain 4 sheets each.  I am trying to write an Excel VBA foor loop that will do such - but it is generating a workbook for every 1 page.

totalPages = PDDoc.GetNumPages

For i = 1 To totalPages - 4
    'This is where you would add the workbook and transfer the page
Next i

Body:
Sub SplitPages()
   Dim i As Integer

   Dim wb As Workbook

   For i = 1 To ThisWorkbook.Worksheets.Count
        If i Mod 4 = 1 Then
           Set wb = Workbooks.Add
        End If
       ThisWorkbook.Worksheets(i).Copy wb.Worksheets(1)
    Next i
End Sub

You have to copy to avoid messing up the count, and the new workbooks have an extra sheet - but a quick

  for each wb in workbooks:wb.sheets("sheet1").delete:next wb

will fix that


问:
exception stack trace
regarding th stack trace depth in debug and release mode.
I have come to the following conclusion (calling exception.ToString()):

at debug mode you get the complete stack trace with line numbers (several frames)
at release mode instead complete stack trace you get only the throwing method in try block
(single frame) with line numbers

is that true ?
-is there any way to get the complete stack tracve on release mode ?

hello,

I want to log exception details
log should include all stack trace (all methods in the chain)
log shoud include line numbers of each method in the stack trace.

I have been trying two methods in debug and release mode.
I did no like the results:

on debug mode both returns the complete stack trace with line numbers :-)
on release mode  both returned only the details of catch method. one cant really

   know which call in the try block failed

can anyone please explain it ?
also, is the stack trace information of excepyion lost when referencing the exception
from other method called in the catch block

thanks

option1:  exception.ToString-

option2:  same results (see below)

```<code>        calling static method receving  the exception as parameter
        System.Diagnostics.StackTrace exceptionStackTrace =
            new System.Diagnostics.StackTrace(e, true);
        System.Diagnostics.StackFrame [] exceptionStackFrames =
            exceptionStackTrace.GetFrames();
         foreach (System.Diagnostics.StackFrame stackFrame in exceptionStackFrames)
        {
            message += String.Format("at {0} {1} line {2} column {3} \n",
                stackFrame.GetFileName() == null ? string.Empty : stackFrame.GetFileName(),
                stackFrame.GetMethod().ToString(),
                stackFrame.GetFileLineNumber(),
                stackFrame.GetFileColumnNumber());
        }
</code>```

答:
A debug build includes quite a lot more information than a release build, to assist debugging, including things like line numbers.

This information lives in the pdb file - if you are not including these in your released application, you can't get the line numbers in the stack trace.

Follow the instructions on this SO answer to enable line numbers in a release build.

Title: exception stack trace

Body:
regarding th stack trace depth in debug and release mode.
I have come to the following conclusion (calling exception.ToString()):

at debug mode you get the complete stack trace with line numbers (several frames)
at release mode instead complete stack trace you get only the throwing method in try block
(single frame) with line numbers

is that true ?
-is there any way to get the complete stack tracve on release mode ?

hello,

I want to log exception details
log should include all stack trace (all methods in the chain)
log shoud include line numbers of each method in the stack trace.

I have been trying two methods in debug and release mode.
I did no like the results:

on debug mode both returns the complete stack trace with line numbers :-)
on release mode  both returned only the details of catch method. one cant really

   know which call in the try block failed

can anyone please explain it ?
also, is the stack trace information of excepyion lost when referencing the exception
from other method called in the catch block

thanks

option1:  exception.ToString-

option2:  same results (see below)

        calling static method receving  the exception as parameter
        System.Diagnostics.StackTrace exceptionStackTrace =
            new System.Diagnostics.StackTrace(e, true);
        System.Diagnostics.StackFrame [] exceptionStackFrames =
            exceptionStackTrace.GetFrames();
         foreach (System.Diagnostics.StackFrame stackFrame in exceptionStackFrames)
        {
            message += String.Format("at {0} {1} line {2} column {3} \n",
                stackFrame.GetFileName() == null ? string.Empty : stackFrame.GetFileName(),
                stackFrame.GetMethod().ToString(),
                stackFrame.GetFileLineNumber(),
                stackFrame.GetFileColumnNumber());
        }


问:
Count number of Special Character in Unix Shell
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

```<code>Example|Running|123|
</code>```

Expected output:

```<code>3
</code>```

答:
This will work as far as I know

```<code>echo "Example|Running|123|" | tr -cd '|' | wc -c
</code>```

Output

3

Body:
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

Example|Running|123|

Expected output:

3

Body:
This will work as far as I know

echo "Example|Running|123|" | tr -cd '|' | wc -c

Output

3


问:
How to reset or "un-initialize" vault?
I'm trying to automate vault v0.8.0 deployment (vaultproject from Hashicorp) with a consul v0.9.1 backend.

Because it is a trial and error process I need to run "vault init" a couple of times (until I get it right) and get the keys.

Unfortunately I lost the keys and the root token.

I tried to stop vault and consul service - nothing
"* Vault is already initialized" and "* Vault is sealed"

I stopped vault, removed the vault path from consul, started vault - same result - and at "vault init" I receive this error:

```<code>* expiration state restore failed: failed to scan for leases: list failed at path '': Unexpected response code: 403
</code>```

and it's creating the vault/ path again in consul and remain sealed.

How can I "reset" vault or make it UN-initialized and start over with "vault init" ?

This is the log:

```<code>Aug 10 05:01:49 TSLASOWROMM01 vault[9156]: ==> Vault server started! Log data will stream in below:
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.238436 [INFO ] core: security barrier not initialized
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.271844 [INFO ] core: security barrier initialized: shares=5 threshold=3
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.320363 [INFO ] core: post-unseal setup starting
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.342931 [INFO ] core: loaded wrapping token key
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.356895 [INFO ] core: successfully mounted backend: type=generic path=secret/
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.357342 [INFO ] core: successfully mounted backend: type=cubbyhole path=cubbyhole/
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.357736 [INFO ] core: successfully mounted backend: type=system path=sys/
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.358293 [INFO ] rollback: starting rollback manager
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.381808 [INFO ] expiration: restoring leases
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.383943 [INFO ] core: pre-seal teardown starting
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384154 [INFO ] core: cluster listeners not running
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384365 [INFO ] rollback: stopping rollback manager
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384633 [INFO ] core: pre-seal teardown complete
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384909 [ERROR] core: post-unseal setup failed during init: error=expiration state restore failed: failed to scan for leases: list failed at path '': Unexpected response code: 403
</code>```

答:
Per the discussion of this same question here: https://groups.google.com/forum/#!msg/vault-tool/xuO8IInubDg/SBHMP2PKAwAJ, the answer is:

Vault is storing its state in Consul, so if you shut down Vault and delete Vault's key prefix in Consul things should start clean again.

Title: How to reset or "un-initialize" vault?

Body:
I'm trying to automate vault v0.8.0 deployment (vaultproject from Hashicorp) with a consul v0.9.1 backend.

Because it is a trial and error process I need to run "vault init" a couple of times (until I get it right) and get the keys.

Unfortunately I lost the keys and the root token.

I tried to stop vault and consul service - nothing
"* Vault is already initialized" and "* Vault is sealed"

I stopped vault, removed the vault path from consul, started vault - same result - and at "vault init" I receive this error:

* expiration state restore failed: failed to scan for leases: list failed at path '': Unexpected response code: 403

and it's creating the vault/ path again in consul and remain sealed.

How can I "reset" vault or make it UN-initialized and start over with "vault init" ?

This is the log:

Aug 10 05:01:49 TSLASOWROMM01 vault[9156]: ==> Vault server started! Log data will stream in below:
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.238436 [INFO ] core: security barrier not initialized
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.271844 [INFO ] core: security barrier initialized: shares=5 threshold=3
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.320363 [INFO ] core: post-unseal setup starting
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.342931 [INFO ] core: loaded wrapping token key
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.356895 [INFO ] core: successfully mounted backend: type=generic path=secret/
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.357342 [INFO ] core: successfully mounted backend: type=cubbyhole path=cubbyhole/
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.357736 [INFO ] core: successfully mounted backend: type=system path=sys/
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.358293 [INFO ] rollback: starting rollback manager
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.381808 [INFO ] expiration: restoring leases
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.383943 [INFO ] core: pre-seal teardown starting
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384154 [INFO ] core: cluster listeners not running
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384365 [INFO ] rollback: stopping rollback manager
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384633 [INFO ] core: pre-seal teardown complete
Aug 10 05:03:26 TSLASOWROMM01 vault[9156]: 2017/08/10 05:03:26.384909 [ERROR] core: post-unseal setup failed during init: error=expiration state restore failed: failed to scan for leases: list failed at path '': Unexpected response code: 403


问:
display grayscale image in java
I created 2D array of floats in java, representing gray scale image, when each pixel is normalized - it between [0,1].

How can I take the 2D array and display the image (in gray scale of course)?

ty!

答:
The easiest way is to make a BufferedImage out of it. To do that, you'll have to convert the values into colors:

```<code>int toRGB(float value) {
    int part = Math.round(value * 255);
    return part * 0x10101;
}
</code>```

That first converts the 0-1 range into 0-255 range, then produces a color where all three channels (RGB - red, green and blue) have the same value, which makes a gray.

Then, to make the whole image, set all the pixel values:

```<code>BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
        image.setRGB(x, y, toRGB(theFloats[y][x]));
</code>```

Once you have the image, you can save it to a file:

```<code>ImageIO.save(image, 'png', new File('some/path/file.png'));
</code>```

Or, display it in some way, perhaps with Swing.. See for example this question.

Title: display grayscale image in java

Body:
The easiest way is to make a BufferedImage out of it. To do that, you'll have to convert the values into colors:

int toRGB(float value) {
    int part = Math.round(value * 255);
    return part * 0x10101;
}

That first converts the 0-1 range into 0-255 range, then produces a color where all three channels (RGB - red, green and blue) have the same value, which makes a gray.

Then, to make the whole image, set all the pixel values:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
        image.setRGB(x, y, toRGB(theFloats[y][x]));

Once you have the image, you can save it to a file:

ImageIO.save(image, 'png', new File('some/path/file.png'));

Or, display it in some way, perhaps with Swing.. See for example this question.


问:
Is KeyGenerator thread safe?
I am wondering if I can instantiate the javax.crypto.KeyGenerator only once and then use this instance in a multithread environment.

Its JavaDoc documentation does not say anything about its thread-safeness. Or it will be better to use a ThreadLocal<KeyGenerator> approach?

UPDATE: A related question is Is SecureRandom thread safe?
While the JavaDoc doesn't state that class is thread safe, the community still found the decision that it is thread-safe what is quite important from the practical point of view. I would like to know the same for the KeyProvider.

答:
Unless the documentation explicitly guarantees thread-safety then treat anything as if it is not thread-safe.

You're right this philosophy is hardly helpful with the scarcity of thread-safety documentation... But without the documentation guaranteeing thread-safety then you simply can't assume something is or will continue to be thread-safe.

Here's some research into the actual implementation of KeyGenerator and why we can't assume that it's thread safe

I found the source and at first glance it would seem like the current implementation is thread safe. However, even if we were to assume this implementation were to never change, it makes calls to Security Providers which could be any implementation of their own and also have no guarantee of being thread-safe since the documentation says nothing about it.

Summary of the source:

Calls to generateKey() use a "Key Generator Service Provider" calling KeyGeneratorSpi.engineGenerateKey() (which could be thread-unsafe) to generate the SecretKey.

If you constructed the KeyGenerator with a specific provider then it will use that specific provider to generate the key.

If you did not construct KeyGenerator with a specific provider then nextSpi() will iterate (thread-safely) through the JVMs list of available providers and try to generate the key until one works or you run out of providers..

The main point is documentation... If the documentation says nothing about thread-safety then any current implementer or an update to the current implementation might not be thread safe.

So you simply cannot assume or depend on any thread safety from KeyGenerator.

Title: Is KeyGenerator thread safe?


问:
Python string join performance
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

```<code>import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t
</code>```

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697
```

Shouldn't it be exactly the other way around?

答:
It is true you should not use '+'. Your example is quite special. Try the same code with:

```<code>s1 = '*' * 100000
s2 = '+' * 100000
</code>```

Then the second version (str.join) is much faster.

OwnerDisplayName: Danny

Title: Python string join performance

Body:
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697

Shouldn't it be exactly the other way around?

LastEditorDisplayName: Danny

Body:
It is true you should not use '+'. Your example is quite special. Try the same code with:

s1 = '*' * 100000
s2 = '+' * 100000

Then the second version (str.join) is much faster.

OwnerDisplayName: RSabet


问:
gulp-jshint task is taking over 5 minutes to complete
I'm working with gulp and am fairly new, my gulp jshint task is as follow:

```<code> gulp.task('jshint', ()=>{
  return gulp.src([`${root}/**/*.js`])
  .pipe(jshint('.jshintrc'))
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('gulp-jshint-html-reporter', { filename: 'jshint-output.html' }))
  .pipe(jshint.reporter('fail'));
});
</code>```

The task is taking 5mins every time I run my build. Is there anyway to speed this up?

$root is src, it is not running through node_modules.

Thanks in advance!

答: Figured it out, there were some lib files being picked up that shouldn't have and as they were huge they caused jshint to take longer. flips desk

Body:
I'm working with gulp and am fairly new, my gulp jshint task is as follow:

 gulp.task('jshint', ()=>{
  return gulp.src([`${root}/**/*.js`])
  .pipe(jshint('.jshintrc'))
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('gulp-jshint-html-reporter', { filename: 'jshint-output.html' }))
  .pipe(jshint.reporter('fail'));
});

The task is taking 5mins every time I run my build. Is there anyway to speed this up?

$root is src, it is not running through node_modules.

Thanks in advance!


问:
HTML5 Video centering source
I have a video that I will be mainly displaying on a portrait screen and I would like the video to be the full height of the screen but centered so the centre of the video is the centre of the screen. I have my current CSS and HTML below. This will display the video of 100% the height but the actual source (video) is played from the left-hand side of itself, not the centre. Is there anyway to do what I'm asking? Also, the video maybe displayed landscape and would need the same result.

Left of this image is what im getting, right is what I want

```<code>.videoContainer
{
    position:absolute;
    height:100%;
    width:100%;
    overflow: hidden;
}

.videoContainer video
{
    width: auto;
    height: 100%
}

  <div class="videoContainer">
    <video width="944" height="532" controls preload="auto" poster="posterimg.jpg">
        <source src="test.mp4" type="video/mp4" />
        <source src="test.webm" type="video/webm">
        <source src="test.ogv" type="video/ogg" type='video/ogg; codecs="theora, vorbis"'>
    </video>
  </div>
</code>```

答:
video {
    display: block;
    margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video width="320" height="240" controls>
    <source src="http://static.videezy.com/system/resources/previews/000/000/328/original/bokeh2.mp4" type="video/mp4" />
</video></code>```

Title: HTML5 Video centering source

Body:
I have a video that I will be mainly displaying on a portrait screen and I would like the video to be the full height of the screen but centered so the centre of the video is the centre of the screen. I have my current CSS and HTML below. This will display the video of 100% the height but the actual source (video) is played from the left-hand side of itself, not the centre. Is there anyway to do what I'm asking? Also, the video maybe displayed landscape and would need the same result.

Left of this image is what im getting, right is what I want

.videoContainer
{
    position:absolute;
    height:100%;
    width:100%;
    overflow: hidden;
}

.videoContainer video
{
    width: auto;
    height: 100%
}

    <video width="944" height="532" controls preload="auto" poster="posterimg.jpg">
        <source src="test.mp4" type="video/mp4" />
        <source src="test.webm" type="video/webm">
        <source src="test.ogv" type="video/ogg" type='video/ogg; codecs="theora, vorbis"'>
    </video>

Body:
video {
    display: block;
    margin: 0 auto;
}

<video width="320" height="240" controls>
    <source src="http://static.videezy.com/system/resources/previews/000/000/328/original/bokeh2.mp4" type="video/mp4" />
</video>


问:
An efficient algorithm to count the number of integer grids
Consider a square 3 by 3 grid of non-negative integers.  For each row i the sum of the integers is set to be r_i.  Similarly for each column j the sum of integers in that column is set to be c_j.  An instance of the problem is therefore described by 6 non-negative integers.

Is there an efficient algorithm to count how many different
  assignments of integers to the grid there are given the row and column
  sum constraints?

Clearly one could enumerate all possible matrices of non-negative integers with values up to sum r_i and check the constraints for each, but that would be insanely slow.

Example

Say the row constraints are 1 2 3 and the column constraints are 3 2 1. The possible integer grids are:

```<code>┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
</code>```

In practice my main interest is when the total sum of the grid will be at most 100 but a more general solution would be very interesting.

答:
Maybe a simple 4-nested-loop solution is fast enough, if the total sum is small?

function solve(rowsum, colsum) {
    var count = 0;
    for (var a = 0; a <= rowsum[0] && a <= colsum[0]; a++) {
        for (var b = 0; b <= rowsum[0] - a && b <= colsum[1]; b++) {
            var c = rowsum[0] - a - b;
            for (var d = 0; d <= rowsum[1] && d <= colsum[0] - a; d++) {
                var g = colsum[0] - a - d;
                for (var e = 0; e <= rowsum[1] - d && e <= colsum[1] - b; e++) {
                    var f = rowsum[1] - d - e;
                    var h = colsum[1] - b - e;
                    var i = rowsum[2] - g - h;
                    if (i >= 0 && i == colsum[2] - c - f) ++count;
                }
            }
        }
    }
    return count;
}
document.write(solve([1,2,3],[3,2,1]) + "
");
document.write(solve([22,33,44],[30,40,29]) + "
");```

Body:
Consider a square 3 by 3 grid of non-negative integers.  For each row i the sum of the integers is set to be r_i.  Similarly for each column j the sum of integers in that column is set to be c_j.  An instance of the problem is therefore described by 6 non-negative integers.

Is there an efficient algorithm to count how many different
  assignments of integers to the grid there are given the row and column
  sum constraints?

Clearly one could enumerate all possible matrices of non-negative integers with values up to sum r_i and check the constraints for each, but that would be insanely slow.

Example

Say the row constraints are 1 2 3 and the column constraints are 3 2 1. The possible integer grids are:

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 1│0 0 1│0 0 1│0 1 0│0 1 0│0 1 0│0 1 0│1 0 0│1 0 0│1 0 0│1 0 0│1 0 0│
│0 2 0│1 1 0│2 0 0│0 1 1│1 0 1│1 1 0│2 0 0│0 1 1│0 2 0│1 0 1│1 1 0│2 0 0│
│3 0 0│2 1 0│1 2 0│3 0 0│2 1 0│2 0 1│1 1 1│2 1 0│2 0 1│1 2 0│1 1 1│0 2 1│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

In practice my main interest is when the total sum of the grid will be at most 100 but a more general solution would be very interesting.

Body:
Maybe a simple 4-nested-loop solution is fast enough, if the total sum is small?

function solve(rowsum, colsum) {
    var count = 0;
    for (var a = 0; a <= rowsum[0] && a <= colsum[0]; a++) {
        for (var b = 0; b <= rowsum[0] - a && b <= colsum[1]; b++) {
            var c = rowsum[0] - a - b;
            for (var d = 0; d <= rowsum[1] && d <= colsum[0] - a; d++) {
                var g = colsum[0] - a - d;
                for (var e = 0; e <= rowsum[1] - d && e <= colsum[1] - b; e++) {
                    var f = rowsum[1] - d - e;
                    var h = colsum[1] - b - e;
                    var i = rowsum[2] - g - h;
                    if (i >= 0 && i == colsum[2] - c - f) ++count;
                }
            }
        }
    }
    return count;
}
document.write(solve([1,2,3],[3,2,1]) + "<br>");
document.write(solve([22,33,44],[30,40,29]) + "<br>");


问:
flash to php to jpeg/gif?
I have a flash swf.  It lets people draw cool things (just a pen tool).  Now I want to have them be able to export it somehow to a website so they can view what they've made online.

Whats the best way to do this?

I know as3 and php right now, but do I need anything else?

答:
First you need to make sure your drawing is a BitmapData (using draw if it's a shape), then you can encode it to JPEG or PNG, and then send it to PHP using something like this: Save ByteArray to file with PHP

There are a few GIF encoders also, but I wouldn't recommend them for drawings.

Title: flash to php to jpeg/gif?


问:
Move button on JFrame Java
I have a task to make an application which will do the following:

If I move a mouse the coordinates should be shown on the status bar

If mouse is clicked then the only one button which is on a JPanel should move to coordinates of click

So the problem is that when I do mouse click - it's fine, button moves to coordinates of click, but when I start moving mouse the button comes back to the original position.

```<code>    public class Window extends JFrame {
        private JLabel statusBar;
        private JPanel mainPanel, statusBarPanel;
        JButton button;
        public Window()
        {
            super("Window");
            setSize(400,600);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainPanel=new JPanel();
            statusBarPanel = new JPanel();
            statusBar=new JLabel("Coords: ");
            add(statusBarPanel, BorderLayout.SOUTH);
            add(mainPanel,BorderLayout.CENTER);
            mainPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
            statusBarPanel.add(statusBar,BorderLayout.CENTER);
            button = new JButton("Default text");
            mainPanel.add(button);
            MyMouseListener myMouseListener=new MyMouseListener();
            mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    super.mouseMoved(e);
                    statusBar.setText("Coords: ("+e.getX()+":"+e.getY()+")");
                }
            });
            mainPanel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    super.mouseClicked(e);
                    button.setLocation(e.getX()-button.getWidth()/2,e.getY()-button.getHeight()/2);
                }
            });
            mainPanel.setFocusable(true);
            setVisible(true);
        }
    }
</code>```

答:
This is one of the rare cases where you don't want your panel to have a layout manager, since you need absolute positioning.

JPanel has a default layout manager which is a FlowLayout, and your call to setLocation will only have a temporary effect until the panel revalidates its content and places things where they were supposed to be initially.

See the following example with comments, it should give you the general idea :

```<code>public class Window extends JFrame {
    private final JLabel statusBar;
    private final JPanel mainPanel, statusBarPanel;
    JButton button;

    public Window() {
        super("Window");
        setSize(400, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainPanel = new JPanel();
        mainPanel.setLayout(null);// no layout for absolute positioning
        statusBarPanel = new JPanel();
        statusBar = new JLabel("Coords: ");
        add(statusBarPanel, BorderLayout.SOUTH);
        add(mainPanel, BorderLayout.CENTER);
        mainPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
        statusBarPanel.add(statusBar, BorderLayout.CENTER);
        button = new JButton("Default text");

        // place the button "manually"
        button.setBounds((int) (400 - button.getPreferredSize().getWidth()) / 2, 0,
                (int) button.getPreferredSize().getWidth(),
                (int) button.getPreferredSize().getHeight());
        mainPanel.add(button);

        mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(final MouseEvent e) {
                super.mouseMoved(e);
                statusBar.setText("Coords: (" + e.getX() + ":" + e.getY() + ")");
            }
        });
        mainPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(final MouseEvent e) {
                super.mouseClicked(e);
                button.setLocation((int) (e.getX() - button.getPreferredSize().getWidth() / 2),
                        (int) (e.getY() - button.getPreferredSize().getHeight() / 2));

            }
        });
        mainPanel.setFocusable(true);
        setVisible(true);
    }

}
</code>```

Title: Move button on JFrame Java

Body:
I have a task to make an application which will do the following:

If I move a mouse the coordinates should be shown on the status bar

If mouse is clicked then the only one button which is on a JPanel should move to coordinates of click

So the problem is that when I do mouse click - it's fine, button moves to coordinates of click, but when I start moving mouse the button comes back to the original position.

    public class Window extends JFrame {
        private JLabel statusBar;
        private JPanel mainPanel, statusBarPanel;
        JButton button;
        public Window()
        {
            super("Window");
            setSize(400,600);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainPanel=new JPanel();
            statusBarPanel = new JPanel();
            statusBar=new JLabel("Coords: ");
            add(statusBarPanel, BorderLayout.SOUTH);
            add(mainPanel,BorderLayout.CENTER);
            mainPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
            statusBarPanel.add(statusBar,BorderLayout.CENTER);
            button = new JButton("Default text");
            mainPanel.add(button);
            MyMouseListener myMouseListener=new MyMouseListener();
            mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    super.mouseMoved(e);
                    statusBar.setText("Coords: ("+e.getX()+":"+e.getY()+")");
                }
            });
            mainPanel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    super.mouseClicked(e);
                    button.setLocation(e.getX()-button.getWidth()/2,e.getY()-button.getHeight()/2);
                }
            });
            mainPanel.setFocusable(true);
            setVisible(true);
        }
    }

Body:
This is one of the rare cases where you don't want your panel to have a layout manager, since you need absolute positioning.

JPanel has a default layout manager which is a FlowLayout, and your call to setLocation will only have a temporary effect until the panel revalidates its content and places things where they were supposed to be initially.

See the following example with comments, it should give you the general idea :

public class Window extends JFrame {
    private final JLabel statusBar;
    private final JPanel mainPanel, statusBarPanel;
    JButton button;

    public Window() {
        super("Window");
        setSize(400, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainPanel = new JPanel();
        mainPanel.setLayout(null);// no layout for absolute positioning
        statusBarPanel = new JPanel();
        statusBar = new JLabel("Coords: ");
        add(statusBarPanel, BorderLayout.SOUTH);
        add(mainPanel, BorderLayout.CENTER);
        mainPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
        statusBarPanel.add(statusBar, BorderLayout.CENTER);
        button = new JButton("Default text");

        // place the button "manually"
        button.setBounds((int) (400 - button.getPreferredSize().getWidth()) / 2, 0,
                (int) button.getPreferredSize().getWidth(),
                (int) button.getPreferredSize().getHeight());
        mainPanel.add(button);

        mainPanel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(final MouseEvent e) {
                super.mouseMoved(e);
                statusBar.setText("Coords: (" + e.getX() + ":" + e.getY() + ")");
            }
        });
        mainPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(final MouseEvent e) {
                super.mouseClicked(e);
                button.setLocation((int) (e.getX() - button.getPreferredSize().getWidth() / 2),
                        (int) (e.getY() - button.getPreferredSize().getHeight() / 2));

            }
        });
        mainPanel.setFocusable(true);
        setVisible(true);
    }

}


问:
Modify the Solr response using SolrJ
I'm using the SolrJ client to call the Solr service, is there any way to modify the response that I got from Solr like adding a new field in the response docs.

```<code>QueryResponse rsp = null;
    if (server != null) {
        try {
            rsp = server.query(solrParams);

        } catch (Exception e) {
            e.getMessage();
        }
    }
</code>```

If my response is something like below

```<code>    {
  "responseHeader":{
"status":400,
"QTime":15,
"params":{
  "q":"*:*",
  "indent":"true",
  "wt":"json",
  "group":"false"}},
  "response":{"numFound":1,"start":0,"docs":[
  {
    "Name":"Shirt",
    "inventory":"Nonn",
    "launchYear":2004,
    "Desc":"Men's Shirt",
    "ilnNumbers":"25326,25338,25341,29617,39267",}
    }}
</code>```

I need to change this response to add a new field

```<code> {
  "responseHeader":{
"status":400,
"QTime":15,
"params":{
  "q":"*:*",
  "indent":"true",
  "wt":"json",
  "group":"false"}},
  "response":{"numFound":1,"start":0,"docs":[
  {
    "Name":"Shirt",
    "inventory":"Nonn",
    "launchYear":2004,
    "myCustomField":"Test",
    "Desc":"Men's Shirt",
    "ilnNumbers":"25326,25338,25341,29617,39267",}
    }}
</code>```

Is this possible?

答:
Try JsonResponceWriter from Solr Documentation.This will help you solve your problem.

```<code>    <queryResponseWriter name="json" class="solr.JSONResponseWriter">
      <!-- For the purposes of the tutorial, JSON response are written as
      plain text so that it's easy to read in *any* browser.
      If you are building applications that consume JSON, just remove
      this override to get the default "application/json" mime type.
      -->
    <str name="content-type">text/plain</str>
    </queryResponseWriter>
</code>```

This will give you queryResponce in Text format. Modify That responce according to your use.

Title: Modify the Solr response using SolrJ

Body:
I'm using the SolrJ client to call the Solr service, is there any way to modify the response that I got from Solr like adding a new field in the response docs.

QueryResponse rsp = null;
    if (server != null) {
        try {
            rsp = server.query(solrParams);

        } catch (Exception e) {
            e.getMessage();
        }
    }

If my response is something like below

    {
  "responseHeader":{
"status":400,
"QTime":15,
"params":{
  "q":"*:*",
  "indent":"true",
  "wt":"json",
  "group":"false"}},
  "response":{"numFound":1,"start":0,"docs":[
  {
    "Name":"Shirt",
    "inventory":"Nonn",
    "launchYear":2004,
    "Desc":"Men's Shirt",
    "ilnNumbers":"25326,25338,25341,29617,39267",}
    }}

I need to change this response to add a new field

 {
  "responseHeader":{
"status":400,
"QTime":15,
"params":{
  "q":"*:*",
  "indent":"true",
  "wt":"json",
  "group":"false"}},
  "response":{"numFound":1,"start":0,"docs":[
  {
    "Name":"Shirt",
    "inventory":"Nonn",
    "launchYear":2004,
    "myCustomField":"Test",
    "Desc":"Men's Shirt",
    "ilnNumbers":"25326,25338,25341,29617,39267",}
    }}

Is this possible?

Body:
Try JsonResponceWriter from Solr Documentation.This will help you solve your problem.

    <queryResponseWriter name="json" class="solr.JSONResponseWriter">
      <!-- For the purposes of the tutorial, JSON response are written as
      plain text so that it's easy to read in *any* browser.
      If you are building applications that consume JSON, just remove
      this override to get the default "application/json" mime type.
      -->
    <str name="content-type">text/plain</str>
    </queryResponseWriter>

This will give you queryResponce in Text format. Modify That responce according to your use.


问:
Implementing AfterViewInit causes an endless loop of event invokations
I have a very strange problem. The following code produces an endless loop of invocations. Possibly only during server side rendering but I am not sure about that.

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

@Component({
  selector: 'test',
  template: '<div>nothing...</div>'
})
export class TestComponent implements AfterViewChecked {

  ngAfterViewChecked(): void {
    console.log('wtf');
  }
}
</code>```

The exact error message is as follows:

An unhandled exception occurred while processing the request.

NodeInvocationException: The Node invocation timed out after 60000ms.
  You can change the timeout duration by setting the
  InvocationTimeoutMilliseconds property on NodeServicesOptions.

The first debugging step is to ensure that your Node.js function
  always invokes the supplied callback (or throws an exception
  synchronously), even if it encounters an error. Otherwise, the .NET
  code has no way to know that it is finished or has failed.

Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance+d__13.MoveNext()

Funny enough compiling the ASP .Net Core project without implementing ngAfterViewChecked and THEN implementing it and injecting it with the HMR causes no error. Thats why I believe that the error might only be occure during the server side rendering step?

答: I had the same problem. The ngAfterViewChecked is called 3 times everytime the component detects some changes. Probably your server is talking to this component, or simply you're istantiating it somewhere. Another time i had this issue when i was asking something (with EventListener) from the component, same loop. Use ngAfterViewInit instead. Or try with ngAfterComponentChecked, but i'm not sure this would work.

Body:
I have a very strange problem. The following code produces an endless loop of invocations. Possibly only during server side rendering but I am not sure about that.

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

@Component({
  selector: 'test',
  template: '
nothing...
'
})
export class TestComponent implements AfterViewChecked {

  ngAfterViewChecked(): void {
    console.log('wtf');
  }
}

The exact error message is as follows:

An unhandled exception occurred while processing the request.

NodeInvocationException: The Node invocation timed out after 60000ms.
  You can change the timeout duration by setting the
  InvocationTimeoutMilliseconds property on NodeServicesOptions.

The first debugging step is to ensure that your Node.js function
  always invokes the supplied callback (or throws an exception
  synchronously), even if it encounters an error. Otherwise, the .NET
  code has no way to know that it is finished or has failed.

Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance+d__13.MoveNext()

Funny enough compiling the ASP .Net Core project without implementing ngAfterViewChecked and THEN implementing it and injecting it with the HMR causes no error. Thats why I believe that the error might only be occure during the server side rendering step?


问:
For loop is only checking last value
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}
</code>```

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

答:
Your idea to return the value at the last line is actually good - it's the principle of single-point-of-return and I would recommend to do that. It makes debugging easier. So the solution would be like:

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database" + localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
            break;
        }  else {
            result = false;
        }
    }
    return result;
}
</code>```

Though it should be mentioned that there are different schools of thought. I personally prefer single-point-of-return, but arguments can be found for both.

Title: For loop is only checking last value

Body:
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

Body:
Your idea to return the value at the last line is actually good - it's the principle of single-point-of-return and I would recommend to do that. It makes debugging easier. So the solution would be like:

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database" + localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
            break;
        }  else {
            result = false;
        }
    }
    return result;
}

Though it should be mentioned that there are different schools of thought. I personally prefer single-point-of-return, but arguments can be found for both.


问:
Why this HashMap not formatted correctly in Jersey/Tomcat?
I'm testing Jersey, I wanted to mack a mock endpoint that produces this JSON object

```<code>{
   "Flight1" : 757,
   "Flight2" : 107,
   "Flight3" : 637,
}
</code>```

so I've written written this resource:

```<code>@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Flight 1", 765);
    map.put("Flight 2", 657);
    map.put("Flight 3", 908);
    return map.toString();
}
</code>```

But then I get this response when I call /myjson

{
       Flight 1=765,
       Flight 2=657,
       Flight 3=908
  }

Jersey already knows which element is a String and which element is an Integer, yet it format then as if they're all numbers.
Also the Json as it stands can not be formatted by the "pretty" formatter, and I believe this makes parsing it difficult by http clients.

So my question are:

Why is this happening?

How to avoid it and write simple mock JSON object for testing that is correctly formatted

答:
This has nothing to do with Jersey/Tomcat. For core Java programming, that is how best toString() method could process the map to String.

In order to do so you can convert to JSONObject using

```<code>    String jon =  JSONObject.valueToString(map);

    System.out.println(jon);
</code>```

OR even using the gson like

```<code>    Gson gson = new Gson();
    String json = gson.toJson(map);
    System.out.println(json);
</code>```

Body:
I'm testing Jersey, I wanted to mack a mock endpoint that produces this JSON object

{
   "Flight1" : 757,
   "Flight2" : 107,
   "Flight3" : 637,
}

so I've written written this resource:

@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Flight 1", 765);
    map.put("Flight 2", 657);
    map.put("Flight 3", 908);
    return map.toString();
}

But then I get this response when I call /myjson

{
       Flight 1=765,
       Flight 2=657,
       Flight 3=908
  }

Jersey already knows which element is a String and which element is an Integer, yet it format then as if they're all numbers.
Also the Json as it stands can not be formatted by the "pretty" formatter, and I believe this makes parsing it difficult by http clients.

So my question are:

Why is this happening?

How to avoid it and write simple mock JSON object for testing that is correctly formatted

Body:
This has nothing to do with Jersey/Tomcat. For core Java programming, that is how best toString() method could process the map to String.

In order to do so you can convert to JSONObject using

    String jon =  JSONObject.valueToString(map);

    System.out.println(jon);

OR even using the gson like

    Gson gson = new Gson();
    String json = gson.toJson(map);
    System.out.println(json);


问:
Struggling to change the value of an element within an array in C++
One of my tasks in this assignment is to add 5 to the maximum value within my array. The professor said to use a void function and to pass a value, which I did. The program adds 5 to the max, 67, to get 72. But, when I printed the array it says 67 is in the array when it should say 72. Is there a way to make it say 72 in the main function, without just adding 5 to the element holding 67 in the main function, but by using void incre(int y)?

Here is the funtion I used to increment the maximum by 5.

```<code>void incre(int y){
y+=5;
cout << "The new max after 5 is added is " << y << endl;
</code>```

}

And here is the code I used to print out the array, which outputs

0    21

1    23

2    67

When it should output

0    21

1    23

2    72

```<code>cout << "Elements ------ Values\n";
for (int r = 0; r < array_size; r++){
cout << r << " ------------- " << A[r]<< endl;
}
</code>```

Also, how do you pass an array to a function using passing by reference? I'm not so sure if I did passing by value or passing by reference in my code here

```<code>void fill_array(int x[], int size){
cout << "Enter in the values 23, then 21 and then 67\n";
for (int z=0;z<size; z++) {
    cin >> x[z];
} }
</code>```

In the main function I put

```<code>fill_array(A, array_size);
</code>```

答:
Here is the funtion I used to increment the maximum by 5.

The argument is passed by value to the function.  Any changes made to it affect only the local copy of the argument, not the variable in the calling function. If you want to see the change reflected in the calling function, change the argument to be a reference argument.

```<code>//            |
//            v
void incre(int& y){
  y+=5;
  cout << "The new max after 5 is added is " << y << endl;
}
</code>```

Body:
One of my tasks in this assignment is to add 5 to the maximum value within my array. The professor said to use a void function and to pass a value, which I did. The program adds 5 to the max, 67, to get 72. But, when I printed the array it says 67 is in the array when it should say 72. Is there a way to make it say 72 in the main function, without just adding 5 to the element holding 67 in the main function, but by using void incre(int y)?

Here is the funtion I used to increment the maximum by 5.

void incre(int y){
y+=5;
cout << "The new max after 5 is added is " << y << endl;

}

And here is the code I used to print out the array, which outputs

0    21

1    23

2    67

When it should output

0    21

1    23

2    72

cout << "Elements ------ Values\n";
for (int r = 0; r < array_size; r++){
cout << r << " ------------- " << A[r]<< endl;
}

Also, how do you pass an array to a function using passing by reference? I'm not so sure if I did passing by value or passing by reference in my code here

void fill_array(int x[], int size){
cout << "Enter in the values 23, then 21 and then 67\n";
for (int z=0;z<size; z++) {
    cin >> x[z];
} }

In the main function I put

fill_array(A, array_size);

Body:
Here is the funtion I used to increment the maximum by 5.

The argument is passed by value to the function.  Any changes made to it affect only the local copy of the argument, not the variable in the calling function. If you want to see the change reflected in the calling function, change the argument to be a reference argument.

//            |
//            v
void incre(int& y){
  y+=5;
  cout << "The new max after 5 is added is " << y << endl;
}