问:
Can I pass type information to simplify this somehow?
I have a lot of code like this, it is all the same except for the type PositionJson, it could be AnotherJson or FooJson or BarJson

Is there some way I can exctract all this code into one function that I can somehow pass into it the type? So that I don't have several of these big blocks of almost identical code littering my class?

I'm not sure if this is possible or not, just thought I'd ask because it would be nice to do...

```<code>    /**
     * @return the _open_ [PositionJson]s
     */
    val positions: Array<PositionJson>?
        @Throws(AccountsAPIException::class)
        get() {
            val service = constructServiceURL(POSITIONS, null, true)
            try {
                val messageJson = mapper.readValue<MessageJson<Array<PositionJson>>>(
                        callURL(service),
                        object: TypeReference<MessageJson<Array<PositionJson>>>() {

                        })

                val error = messageJson.error
                if (error != null) throw AccountsAPIException(error.errorCode, error.description)
                return messageJson.data
            } catch (e: Exception) {
                throw AccountsAPIException(e)
            }
        }
</code>```

答:
You can do what you want with generics. However, to use generics we first need to extract that giant block of code into a method:

```<code>val positions: Array<PositionJson>? get() = getPositions()

fun getPositions(): Array<PositionJson>? {
    ...
}
</code>```

We haven't solved the problem, but now we're in a position to be able to solve it by making getPositions generic (note that I also rename the function):

```<code>val positions: Array<PositionJson> get() = getArrayOf<PositionJson>()
// thanks to type inference I can omit the type on getArrayOf if desired:
val positions: Array<PositionJson> get() = getArrayOf()

fun <T> getArrayOf(): Array<T>? {
    val service = constructServiceURL(POSITIONS, null, true)
    try {
        val messageJson = mapper.readValue<MessageJson<Array<T>>>(
                callURL(service),
                object: TypeReference<MessageJson<Array<T>>>() {

                })

        val error = messageJson.error
        if (error != null) throw AccountsAPIException(error.errorCode, error.description)
        return messageJson.data
    } catch (e: Exception) {
        throw AccountsAPIException(e)
    }
}
</code>```

Perfect! Except this won't compile thanks to type erasure. But we can fix this too by making the function inline and making the type parameter reified:

```<code>inline fun <reified T: Any> getArrayOf(): Array<T>? {
    ...
}
</code>```

And that should do it. Now you can reuse this function as needed:

```<code>val positions: Array<PositionJson>? get() = getArrayOf()
val persons: Array<PersonJson>? get() = getArrayOf()
val bananas: Array<BananaJson>? get() = getArrayOf()

inline fun <reified T: Any> getArrayOf(): Array<T>? {
    val service = constructServiceURL(POSITIONS, null, true)
    try {
        val messageJson = mapper.readValue<MessageJson<Array<T>>>(
                callURL(service),
                object: TypeReference<MessageJson<Array<T>>>() {

                })

        val error = messageJson.error
        if (error != null) throw AccountsAPIException(error.errorCode, error.description)
        return messageJson.data
    } catch (e: Exception) {
        throw AccountsAPIException(e)
    }
}
</code>```

One last thing: note that in all my examples I used property getters (get() = ...) as in your original code. However, I strongly suspect that you do NOT want to use a getter. Getters will be called every time someone accesses your property, which in this case means that every time someone reads the positions property you'll be calling constructServiceURL and making the service call, etc. If you want that code to only happen once then you should just call getArrayOf() once and assign the result to your property:

```<code>val positions: Array<PositionJson>? = getArrayOf()
// this syntax would also work:
val positions = getArrayOf<PositionJson>()
</code>```

Body:
I have a lot of code like this, it is all the same except for the type PositionJson, it could be AnotherJson or FooJson or BarJson

Is there some way I can exctract all this code into one function that I can somehow pass into it the type? So that I don't have several of these big blocks of almost identical code littering my class?

I'm not sure if this is possible or not, just thought I'd ask because it would be nice to do...

    /**
     * @return the _open_ [PositionJson]s
     */
    val positions: Array<PositionJson>?
        @Throws(AccountsAPIException::class)
        get() {
            val service = constructServiceURL(POSITIONS, null, true)
            try {
                val messageJson = mapper.readValue<MessageJson<Array<PositionJson>>>(
                        callURL(service),
                        object: TypeReference<MessageJson<Array<PositionJson>>>() {

                        })

                val error = messageJson.error
                if (error != null) throw AccountsAPIException(error.errorCode, error.description)
                return messageJson.data
            } catch (e: Exception) {
                throw AccountsAPIException(e)
            }
        }

Body:
You can do what you want with generics. However, to use generics we first need to extract that giant block of code into a method:

val positions: Array<PositionJson>? get() = getPositions()

fun getPositions(): Array<PositionJson>? {
    ...
}

We haven't solved the problem, but now we're in a position to be able to solve it by making getPositions generic (note that I also rename the function):

val positions: Array<PositionJson> get() = getArrayOf<PositionJson>()
// thanks to type inference I can omit the type on getArrayOf if desired:
val positions: Array<PositionJson> get() = getArrayOf()

fun <T> getArrayOf(): Array<T>? {
    val service = constructServiceURL(POSITIONS, null, true)
    try {
        val messageJson = mapper.readValue<MessageJson<Array<T>>>(
                callURL(service),
                object: TypeReference<MessageJson<Array<T>>>() {

                })

        val error = messageJson.error
        if (error != null) throw AccountsAPIException(error.errorCode, error.description)
        return messageJson.data
    } catch (e: Exception) {
        throw AccountsAPIException(e)
    }
}

Perfect! Except this won't compile thanks to type erasure. But we can fix this too by making the function inline and making the type parameter reified:

inline fun <reified T: Any> getArrayOf(): Array<T>? {
    ...
}

And that should do it. Now you can reuse this function as needed:

val positions: Array<PositionJson>? get() = getArrayOf()
val persons: Array<PersonJson>? get() = getArrayOf()
val bananas: Array<BananaJson>? get() = getArrayOf()

inline fun <reified T: Any> getArrayOf(): Array<T>? {
    val service = constructServiceURL(POSITIONS, null, true)
    try {
        val messageJson = mapper.readValue<MessageJson<Array<T>>>(
                callURL(service),
                object: TypeReference<MessageJson<Array<T>>>() {

                })

        val error = messageJson.error
        if (error != null) throw AccountsAPIException(error.errorCode, error.description)
        return messageJson.data
    } catch (e: Exception) {
        throw AccountsAPIException(e)
    }
}

One last thing: note that in all my examples I used property getters (get() = ...) as in your original code. However, I strongly suspect that you do NOT want to use a getter. Getters will be called every time someone accesses your property, which in this case means that every time someone reads the positions property you'll be calling constructServiceURL and making the service call, etc. If you want that code to only happen once then you should just call getArrayOf() once and assign the result to your property:

val positions: Array<PositionJson>? = getArrayOf()
// this syntax would also work:
val positions = getArrayOf<PositionJson>()


来源: stackexchange

问:
Space concatenated with an expression is sometimes dropped
JSFiddle contains:

```<code>var d = " " + true ? "am" : "pm";
var e = " " + "am";
alert("|" + d + "|");
alert("|" + e + "|");
</code>```

Why does d not contain the leading space?

答:
" " + true evaluates to boolean.. you need</p>

```<code>var d = " " + (true ? "am" : "pm");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
JSFiddle contains:

var d = " " + true ? "am" : "pm";
var e = " " + "am";
alert("|" + d + "|");
alert("|" + e + "|");

Why does d not contain the leading space?

Body:
" " + true evaluates to boolean.. you need

var d = " " + (true ? "am" : "pm");


问:
Guessing a number
I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).

I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner ran = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < 3) {
            System.out.println("Too low. Try again.");

            System.out.println("Enter a number: ");
        } else if (x > 3) {
            System.out.println("Too high. Try again");

        } else if(x == 3) {
            System.out.println("You win. Nice job.");
        } else {
            System.out.println("You lose");
        }

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}
</code>```

答:
I think the main purpose of this exercise is intended for you to strengthen your nested if-else concepts.

```<code>import java.util.Scanner;
</code>```

public class HelloWorld{

```<code> public static void main(String []args){
    int num=3;
    int count=1;
    Scanner ran = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int x = ran.nextInt();

    if(x>num || x<num)
    {
        System.out.println("incorrect guess");
        count++;
        System.out.println("Enter a number: ");
         x = ran.nextInt();
         if(x>num || x<num)
         {
              System.out.println("incorrect guess");
              count++;
                          System.out.println("Enter a number: ");
                           x = ran.nextInt();
                           if(x>num || x<num)
                           {
                               System.out.println("incorrect guess YOU LOSE");
                           }
                           else
                           {
                                               System.out.println("YOU WIN");
                           }
         }
         else
         {
               System.out.println("YOU WIN");
         }

    }

    if(x==num && count==1)
    {
        System.out.println("YOU WIN");
    }

    System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
 }
}
</code>```

Title: Guessing a number

Body:
I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).

I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner ran = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < 3) {
            System.out.println("Too low. Try again.");

            System.out.println("Enter a number: ");
        } else if (x > 3) {
            System.out.println("Too high. Try again");

        } else if(x == 3) {
            System.out.println("You win. Nice job.");
        } else {
            System.out.println("You lose");
        }

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}

Body:
I think the main purpose of this exercise is intended for you to strengthen your nested if-else concepts.

import java.util.Scanner;

public class HelloWorld{

 public static void main(String []args){
    int num=3;
    int count=1;
    Scanner ran = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int x = ran.nextInt();

    if(x>num || x<num)
    {
        System.out.println("incorrect guess");
        count++;
        System.out.println("Enter a number: ");
         x = ran.nextInt();
         if(x>num || x<num)
         {
              System.out.println("incorrect guess");
              count++;
                          System.out.println("Enter a number: ");
                           x = ran.nextInt();
                           if(x>num || x<num)
                           {
                               System.out.println("incorrect guess YOU LOSE");
                           }
                           else
                           {
                                               System.out.println("YOU WIN");
                           }
         }
         else
         {
               System.out.println("YOU WIN");
         }

    }

    if(x==num && count==1)
    {
        System.out.println("YOU WIN");
    }

    System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
 }
}


问:
regex how to read all the characters between the two braces
I am reading log file and have to extract all the values in a line which is like below

```<code>>    DE-055  LLL[136]
> CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)
</code>```

I am trying to use regex to extract the data between the two braces (). Please advise how can I extract so far, I have tried different methods but not able to do so

```<code>for (String s : incomingmessage) {
    // **DE-011  FXD[006]  CHR(008432)**
    pattern3 working
    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)  (\\w*)(\\()([\\w*\\s*]+)(\\))"; --> works when the value is like above,same code do not work for the below format

    //DE-055  LLL[136]  CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)

    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)(\\w*)(\\([.*?]\\))"; --> tried many times changing not able to get the regex which will work to get the values between the two braces even if it is some funny characters like the above

    Pattern p3 = Pattern.compile(pattern3);
    // Matcher m1 = p1.matcher(s);
    //Matcher m2 = p2.matcher(s);
    Matcher m3 = p3.matcher(s);

    while (m3.find()) {
        String fullvalue = m3.group(0);
        // String field = m3.group(1);
        //String length = m3.group(3);
        //String value = m3.group(7);
        System.out.println("m3.find() full value " + fullvalue);
        //System.out.println("m3.find() filed value " + field + "length " + length + "value" + value);
    }
}
</code>```

I want the output value as below which is between the two braces ()

```<code>_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..
</code>```

答:
If you don't expect nested braces, this will work:

```<code>String input = "sfasdf(sfsdfs76868)dslf()js98(sds),cn,";
String regex = "(?<=\\().*?(?=\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println("Match: " + matcher.group(0));
}
</code>```

The output will be:

```<code>Match: sfsdfs76868
Match:
Match: sds
</code>```

Body:
I am reading log file and have to extract all the values in a line which is like below

>    DE-055  LLL[136]
> CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)

I am trying to use regex to extract the data between the two braces (). Please advise how can I extract so far, I have tried different methods but not able to do so

for (String s : incomingmessage) {
    // **DE-011  FXD[006]  CHR(008432)**
    pattern3 working
    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)  (\\w*)(\\()([\\w*\\s*]+)(\\))"; --> works when the value is like above,same code do not work for the below format

    //DE-055  LLL[136]  CHR(_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..)

    String pattern3 = "(DE\\W\\d*)(\\s*\\w*\\W*)(\\d*)(\\W*\\s*)(\\w*)(\\([.*?]\\))"; --> tried many times changing not able to get the regex which will work to get the values between the two braces even if it is some funny characters like the above

    Pattern p3 = Pattern.compile(pattern3);
    // Matcher m1 = p1.matcher(s);
    //Matcher m2 = p2.matcher(s);
    Matcher m3 = p3.matcher(s);

    while (m3.find()) {
        String fullvalue = m3.group(0);
        // String field = m3.group(1);
        //String length = m3.group(3);
        //String value = m3.group(7);
        System.out.println("m3.find() full value " + fullvalue);
        //System.out.println("m3.find() filed value " + field + "length " + length + "value" + value);
    }
}

I want the output value as below which is between the two braces ()

_*.....\............B........(............................................12345678.&..g..2%.$.'...3.`(..4.....5.!.6....7.s$...A......S..

Body:
If you don't expect nested braces, this will work:

String input = "sfasdf(sfsdfs76868)dslf()js98(sds),cn,";
String regex = "(?<=\\().*?(?=\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println("Match: " + matcher.group(0));
}

The output will be:

Match: sfsdfs76868
Match:
Match: sds


问:
JPA (Hibernate) and custom table prefixes
Is it possible to override table names in JPA/Hibernate in order to add a common prefix for all project entities? For instance to be able to prefix all JBPM 5 tables by "JBPM5_" prefix.

Example for the accepted answer:

```<code>public class JBPM5NamingStrategy extends ImprovedNamingStrategy {
   public String classToTableName(String className) {
      return StringHelper.unqualify(className);
   }
   public String propertyToColumnName(String propertyName) {
      return propertyName;
   }
   public String tableName(String tableName) {
      return "JBPM5_" + tableName;
   }
   public String columnName(String columnName) {
      return columnName;
   }
   public String propertyToTableName(String className, String propertyName) {
      return "JBPM5_" + classToTableName(className) + '_'
         + propertyToColumnName(propertyName);
   }
}
</code>```

答:
Use a NamingStrategy. This previous answer of mine should provide exactly what you need.

Copied from previous answer:

Here is a sample NamingStrategy that
  builds table names of the form
  TYPE1_TYPE2 for join tables and adds a
  common prefix to all tables:

```<code>public class CustomNamingStrategy extends ImprovedNamingStrategy {

    private static final long serialVersionUID = 1L;
    private static final String PREFIX = "PFX_";

    @Override
    public String classToTableName(final String className) {
        return this.addPrefix(super.classToTableName(className));
    }

    @Override
    public String collectionTableName(final String ownerEntity,
            final String ownerEntityTable, final String associatedEntity,
            final String associatedEntityTable, final String propertyName) {
        return this.addPrefix(super.collectionTableName(ownerEntity,
                ownerEntityTable, associatedEntity, associatedEntityTable,
                propertyName));
    }

    @Override
    public String logicalCollectionTableName(final String tableName,
            final String ownerEntityTable, final String associatedEntityTable,
            final String propertyName) {
        return this.addPrefix(super.logicalCollectionTableName(tableName,
                ownerEntityTable, associatedEntityTable, propertyName));
    }

    private String addPrefix(final String composedTableName) {

        return PREFIX
                + composedTableName.toUpperCase().replace("_", "");

    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to override table names in JPA/Hibernate in order to add a common prefix for all project entities? For instance to be able to prefix all JBPM 5 tables by "JBPM5_" prefix.

Example for the accepted answer:

public class JBPM5NamingStrategy extends ImprovedNamingStrategy {
   public String classToTableName(String className) {
      return StringHelper.unqualify(className);
   }
   public String propertyToColumnName(String propertyName) {
      return propertyName;
   }
   public String tableName(String tableName) {
      return "JBPM5_" + tableName;
   }
   public String columnName(String columnName) {
      return columnName;
   }
   public String propertyToTableName(String className, String propertyName) {
      return "JBPM5_" + classToTableName(className) + '_'
         + propertyToColumnName(propertyName);
   }
}

Body:
Use a NamingStrategy. This previous answer of mine should provide exactly what you need.

Copied from previous answer:

Here is a sample NamingStrategy that
  builds table names of the form
  TYPE1_TYPE2 for join tables and adds a
  common prefix to all tables:

public class CustomNamingStrategy extends ImprovedNamingStrategy {

    private static final long serialVersionUID = 1L;
    private static final String PREFIX = "PFX_";

    @Override
    public String classToTableName(final String className) {
        return this.addPrefix(super.classToTableName(className));
    }

    @Override
    public String collectionTableName(final String ownerEntity,
            final String ownerEntityTable, final String associatedEntity,
            final String associatedEntityTable, final String propertyName) {
        return this.addPrefix(super.collectionTableName(ownerEntity,
                ownerEntityTable, associatedEntity, associatedEntityTable,
                propertyName));
    }

    @Override
    public String logicalCollectionTableName(final String tableName,
            final String ownerEntityTable, final String associatedEntityTable,
            final String propertyName) {
        return this.addPrefix(super.logicalCollectionTableName(tableName,
                ownerEntityTable, associatedEntityTable, propertyName));
    }

    private String addPrefix(final String composedTableName) {

        return PREFIX
                + composedTableName.toUpperCase().replace("_", "");

    }

}


问:
Error creating Kafka Topics- Replication factor larger than available brokers
I am trying to create topics in Kafka by following the guide on Apache Kafka website through command line.
While running the command:

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

I get the error as follows:

```<code>Error while executing topic command replication factor: 1 larger than available
brokers: 0
kafka.admin.AdminOperationException: replication factor: 1 larger than available
 brokers: 0
        at kafka.admin.AdminUtils$.assignReplicasToBrokers(AdminUtils.scala:70)
        at kafka.admin.AdminUtils$.createTopic(AdminUtils.scala:171)
        at kafka.admin.TopicCommand$.createTopic(TopicCommand.scala:93)
        at kafka.admin.TopicCommand$.main(TopicCommand.scala:55)
        at kafka.admin.TopicCommand.main(TopicCommand.scala)

[2015-10-13 14:25:38,607] INFO Processed session termination for sessionid: 0x15
06056566d0004 (org.apache.zookeeper.server.PrepRequestProcessor)
[2015-10-13 14:25:38,608] INFO Closed socket connection for client /127.0.0.1:33
391 which had sessionid 0x1506056566d0004 (org.apache.zookeeper.server.NIOServer
Cnxn)
</code>```

How can I resolve the issue? Any good documentation to get started with this?
Thanks!!

答:
I have had the same problem.I solve the problem.I think the reason for this is because there is no background start-up.
so,we neet start-up background</p>

```<code>bin/kafka-server-start.sh config/server.properties &
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test &
</code>```

Body:
I am trying to create topics in Kafka by following the guide on Apache Kafka website through command line.
While running the command:

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

I get the error as follows:

Error while executing topic command replication factor: 1 larger than available
brokers: 0
kafka.admin.AdminOperationException: replication factor: 1 larger than available
 brokers: 0
        at kafka.admin.AdminUtils$.assignReplicasToBrokers(AdminUtils.scala:70)
        at kafka.admin.AdminUtils$.createTopic(AdminUtils.scala:171)
        at kafka.admin.TopicCommand$.createTopic(TopicCommand.scala:93)
        at kafka.admin.TopicCommand$.main(TopicCommand.scala:55)
        at kafka.admin.TopicCommand.main(TopicCommand.scala)

[2015-10-13 14:25:38,607] INFO Processed session termination for sessionid: 0x15
06056566d0004 (org.apache.zookeeper.server.PrepRequestProcessor)
[2015-10-13 14:25:38,608] INFO Closed socket connection for client /127.0.0.1:33
391 which had sessionid 0x1506056566d0004 (org.apache.zookeeper.server.NIOServer
Cnxn)

How can I resolve the issue? Any good documentation to get started with this?
Thanks!!

Body:
I have had the same problem.I solve the problem.I think the reason for this is because there is no background start-up.
so,we neet start-up background

bin/kafka-server-start.sh config/server.properties &
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test &


问:
how to access specific data from JsonResponse
Supposing I have this return value

```<code>return JsonResponse( { 'message' : 'success', 'id' : newProductType.id }, safe = False )
</code>```

and I have this function on success

```<code>.then( function( rs ){
      alert(rs.id)
</code>```

Problem is, it alerts an undefined value. How do I access the id field in that object? Sorry, maybe its a very simple problem but Im a newbie so bear with me.

答:
You can use

rs.new_id

Because your response haven't id field.

Body:
Supposing I have this return value

return JsonResponse( { 'message' : 'success', 'id' : newProductType.id }, safe = False )

and I have this function on success

.then( function( rs ){
      alert(rs.id)

Problem is, it alerts an undefined value. How do I access the id field in that object? Sorry, maybe its a very simple problem but Im a newbie so bear with me.


问:
Reversing elements in Arrays
```<code>public static void main(String[] args) {

    int[] HwArray = new int[10];
    for (int i = 0; i < HwArray.length; i++) {
        HwArray[i] = i;
        }

    int count = 0;
    for (int i = 0; i < HwArray.length; i++){
    HwArray[i] = (int) (100 + Math.random() * 100);

    System.out.print("HwArray[i]=" + HwArray[i]);
            }

        }

    {
        int[] reverse(int[] HwArray); {
            int[] reversed = new int[HwArray.length];
            for (int i=0; i<HwArray.length; i++) {
                reversed[i] = HwArray[HwArray.length - 1 - i];
            }
            return reverse;
        }
    }

}
</code>```

Sorry, I'm still learning. I'm trying to reverse the order of all the elements, but I keep receiving an error. Am I doing something wrong?

答:
I think the conceptually easiest way to reverse the order of elements in an array is to swap each ith element in the first half of the array of size N with the N-ith element in the second half:

```<code>int[] reversed = new int[10];
for (int i=0; i < HwArray.length/2; ++i) {
    reversed[i] = HwArray[HwArray.length-1-i];
    reversed[HwArray.length-1-i] = HwArray[i];
}
</code>```

Demo here:

IDEOne

Title: Reversing elements in Arrays

Body:
public static void main(String[] args) {

    int[] HwArray = new int[10];
    for (int i = 0; i < HwArray.length; i++) {
        HwArray[i] = i;
        }

    int count = 0;
    for (int i = 0; i < HwArray.length; i++){
    HwArray[i] = (int) (100 + Math.random() * 100);

    System.out.print("HwArray[i]=" + HwArray[i]);
            }

        }

    {
        int[] reverse(int[] HwArray); {
            int[] reversed = new int[HwArray.length];
            for (int i=0; i<HwArray.length; i++) {
                reversed[i] = HwArray[HwArray.length - 1 - i];
            }
            return reverse;
        }
    }

}

Sorry, I'm still learning. I'm trying to reverse the order of all the elements, but I keep receiving an error. Am I doing something wrong?

Body:
I think the conceptually easiest way to reverse the order of elements in an array is to swap each ith element in the first half of the array of size N with the N-ith element in the second half:

int[] reversed = new int[10];
for (int i=0; i < HwArray.length/2; ++i) {
    reversed[i] = HwArray[HwArray.length-1-i];
    reversed[HwArray.length-1-i] = HwArray[i];
}

Demo here:

IDEOne


问:
Count how many UL have so many LI elements in jQuery
I have various UL and I need to know about all existing UL, how many UL have two LI, what I'm trying to do with a each, this will be the right way.

$(function(){

 var count = '';
 var total = 1;

 $('ul li').each(function(index, el) {
   count++;
   if(count == 12) {
    total + 1;
   }

   count = '';
  });

    console.log('We found 2 UL with 2 li');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
 <li>Item</li>
  <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul></code>```

The this code, result: We found 2 UL with 2 li.

答:
  var count = 0;
  $('ul').each(function(index, item) {
  if($(this).children('li').length == 2)
  {
  count++;
  }
  });

  if(count > 0)
  {
  console.log('We found '+ count +' UL with 2 li');
  }
  else
  {
  console.log('no such li is found')
  }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
 <li>Item</li>
  <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have various UL and I need to know about all existing UL, how many UL have two LI, what I'm trying to do with a each, this will be the right way.

$(function(){

 var count = '';
 var total = 1;

 $('ul li').each(function(index, el) {
   count++;
   if(count == 12) {
    total + 1;
   }

   count = '';
  });

    console.log('We found 2 UL with 2 li');
});

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

The this code, result: We found 2 UL with 2 li.

Body:
  var count = 0;
  $('ul').each(function(index, item) {
  if($(this).children('li').length == 2)
  {
  count++;
  }
  });

  if(count > 0)
  {
  console.log('We found '+ count +' UL with 2 li');
  }
  else
  {
  console.log('no such li is found')
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
 <li>Item</li>
  <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>


问:
How do I create a ListBox in ASP.NET MVC with single selection mode?
How do I create a ListBox in ASP.NET MVC with single selection mode?</p>

答:
Following  Code Works for me,

<%=Html.DropDownList("list1", lstItem, new {@size = 5})%>
  where lstItem represents the List of SelectListItem

OwnerDisplayName: Todd Smith


问:
Find Min Max of 2D array in scala
I have a 2D array of the form:

```<code>scala> signature_matrix
res129: Array[Array[Int]]
</code>```

How do I find the maximum element?

答:
```<code>signature_matrix.map(_.max).max
</code>```

find sub Array max firstly and map to an Array, and find max again.

Title: Find Min Max of 2D array in scala

Body:
I have a 2D array of the form:

scala> signature_matrix
res129: Array[Array[Int]]

How do I find the maximum element?

Body:
signature_matrix.map(_.max).max

find sub Array max firstly and map to an Array, and find max again.


问:
how to open dsp file in Visual studio?
I have Visual studio 2008 and I wanted to open a .dsp file in Visual Studio.
This .dsp file is one of the source code of guitarix software.
Can anybody help me to resolve this issue ?
I am getting this errorError Message</p>

答: The dsp files in guitarix are Faust (0.9.73) source files. So you could open them with any text editor. </p>

Title: how to open dsp file in Visual studio?


问:
How to simulate a django form submission with a button click on a different page?
I am running in a situation where I want to simulate a form behaviour when a button is clicked on a different page.

For example by default a url '/add_user/' has a form where a user provides his name, email address, etc. When he clicks submit button on this form it creates an entry in database using django's form.save() method. Which essentially is depended on modelform functionality.

Now I have added a new url called '/subscribe/' where one can subscribe to a newsletter of his interest. I want to add all the name, email etc details from subscribe form and save it to database table which add_user link accesses.

I am aware that I can invoke a sql statement on a button click or using python library I can get the same result, however, I am wondering if there is any other way to simulate this because I want to keep my code decoupled from underlying database. In other words if in future if someone changes the database I don't want this code to fail.

Can you advise on how to do this?

Thanks.
Have a great day.

答:
You can setup a many to one relation between users and the subscribe database entry. Then when a user logs in and presses the subscribe button send that request to a view and process the entry. </p>

<p>You can find out which user is logged in with </p>

```<code>user = request.user
</code>```

Body:
You can setup a many to one relation between users and the subscribe database entry. Then when a user logs in and presses the subscribe button send that request to a view and process the entry.

You can find out which user is logged in with

user = request.user


问:
Mysql query built my phpmyadmin doesn't work in PHP with WHERE clauses
Just trying to select all rows with no comments, or comments < 5 characters.

Starting from basics, this works:

```<code>$query= "SELECT * FROM `comments`";
$result = mysql_query($query);
</code>```

What doesn't work is:

```<code>$query = "SELECT * FROM `comments` WHERE `comment` = ''";
</code>```

or

```<code>$sql = "SELECT * from comments WHERE LENGTH(comment) < 5 LIMIT 30";
</code>```

I've put limit 5 because when I do a COUNT on the "empty" comments, it says there's 4 bytes there. The column is not NULL (don't blame me, I didn't write it!)

I've even tried using phpmyadmin to change the "empty" values to the word "chicken", then running

So, I used phpmyadmin to change all the instances of comments < 4 characters to the word "chicken".

```<code>$query = "SELECT * FROM `comments` WHERE `comment` = 'chicken'";
</code>```

As with ALL of the above errors, it spews out:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

But if I do

```<code>$emptycomment = "chicken";
$query = sprintf("SELECT * FROM `comments` WHERE `comment` = $emptycomment");
</code>```

Invalid query: Unknown column 'chicken' in 'where clause'

WTF?! But that works perfectly in phpmyadmin! (all above tested on stable and alpha versions)

I also saw where someone else put:

```<code>$query = sprintf("SELECT * FROM `comments` WHERE `comment` = 'chicken'");
</code>```

Again, no dice on any of the above.

The stupid thing is, these all work perfectly directly as a mysql query, and the above were even generated by phpmyadmin!
I've even updated php to 5.3.2, the mysql installed is 5.1.52

I've tried making it EXACTLY as per example 2 here, using variables for everything.
http://php.net/manual/en/function.mysql-query.php

I've followed the tutorial here:
http://www.devshed.com/c/a/MySQL/Null-and-Empty-Strings/3/

I've browsed about 20 articles here at Stackoverflow.

It's 11:15am. I started at 6:30. Getting a bit frustrated here. Thanks!

答:
I ran into a similar problem where an "empty" field wasn't NULL. What happens if you try the chicken with:

```<code>$query = "SELECT * FROM comments WHERE comment LIKE '%chicken%'";
</code>```

This will give you a match even if you have CR/LF and other strange "invisible"  characters involved.

Body:
Just trying to select all rows with no comments, or comments < 5 characters.

Starting from basics, this works:

$query= "SELECT * FROM `comments`";
$result = mysql_query($query);

What doesn't work is:

$query = "SELECT * FROM `comments` WHERE `comment` = ''";

or

$sql = "SELECT * from comments WHERE LENGTH(comment) < 5 LIMIT 30";

I've put limit 5 because when I do a COUNT on the "empty" comments, it says there's 4 bytes there. The column is not NULL (don't blame me, I didn't write it!)

I've even tried using phpmyadmin to change the "empty" values to the word "chicken", then running

So, I used phpmyadmin to change all the instances of comments < 4 characters to the word "chicken".

$query = "SELECT * FROM `comments` WHERE `comment` = 'chicken'";

As with ALL of the above errors, it spews out:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

But if I do

$emptycomment = "chicken";
$query = sprintf("SELECT * FROM `comments` WHERE `comment` = $emptycomment");

Invalid query: Unknown column 'chicken' in 'where clause'

WTF?! But that works perfectly in phpmyadmin! (all above tested on stable and alpha versions)

I also saw where someone else put:

$query = sprintf("SELECT * FROM `comments` WHERE `comment` = 'chicken'");

Again, no dice on any of the above.

The stupid thing is, these all work perfectly directly as a mysql query, and the above were even generated by phpmyadmin!
I've even updated php to 5.3.2, the mysql installed is 5.1.52

I've tried making it EXACTLY as per example 2 here, using variables for everything.
http://php.net/manual/en/function.mysql-query.php

I've followed the tutorial here:
http://www.devshed.com/c/a/MySQL/Null-and-Empty-Strings/3/

I've browsed about 20 articles here at Stackoverflow.

It's 11:15am. I started at 6:30. Getting a bit frustrated here. Thanks!

Body:
I ran into a similar problem where an "empty" field wasn't NULL. What happens if you try the chicken with:

$query = "SELECT * FROM comments WHERE comment LIKE '%chicken%'";

This will give you a match even if you have CR/LF and other strange "invisible"  characters involved.


问:
ERROR Unable to locate plugin type [for RollingFile and for TimeBasedTriggeringPolicy]
I'm starting to work a docker elasticsearch 5.0.1 instance following the official instructions detailed at:

https://www.elastic.co/guide/en/elasticsearch/reference/5.0/settings.html

in order to configure elasticsearch.yml and log4j2.properties files, those files are located at:

```<code>$ pwd
/system/mesos/elasticsearchf/config
$ ls
elasticsearch.yml log4j2.properties
</code>```

Contain of these configuration files:

```<code>$cat elasticsearch.yml
path:
data: /usr/share/elasticsearch/data
logs: /usr/share/elasticsearch/data
shared_data: /usr/share/elasticsearch/data
config: /usr/share/elasticsearch/config

node.add_lock_id_to_custom_path: false
index.number_of_shards: 2
cluster.name: elasticcluster
discovery.zen.ping.unicast.hosts: ["10.120.1.190", "10.120.1.191"]

$cat log4j2.properties
appender.rolling.type = RollingFile
appender.rolling.name = rolling
appender.rolling.fileName = ${sys:es.logs}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%d{ISO8601}][%-5p][%-25c] %.10000m%n
appender.rolling.filePattern = ${sys:es.logs}-%d{yyyy-MM-dd}.log
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
</code>```

And when I run command:

```<code>$ docker -D -H unix:///var/run/docker.sock run --cpu-shares 1024 --memory 2634022912 -e ES_JAVA_OPTS="-Xms2G -Xmx2G" -v /system/mesos/elasticsearchf/data:/usr/share/elasticsearch/data/:rw -v /system/mesos/elasticsearchf/config:/usr/share/elasticsearch/config/:rw --net bridge -p 9200:9200/tcp -p 9300:9300/tcp docker.elastic.co/elasticsearch/elasticsearch:5.0.1
</code>```

I got error messages related with log4j2 messages you can see below

Any help will be welcome

Kind Regards

```<code>DEBU[0001] framesize: 81
2016-12-01 10:37:15,526 main ERROR Unable to locate plugin type for RollingFile
DEBU[0001] framesize: 90
2016-12-01 10:37:15,554 main ERROR Unable to locate plugin for TimeBasedTriggeringPolicy
DEBU[0001] framesize: 2223
2016-12-01 10:37:15,555 main ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy for element Policies. java.lang.NullPointerException
        at org.apache.logging.log4j.core.config.plugins.visitors.PluginElementVisitor.visit(PluginElementVisitor.java:52)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.generateParameters(PluginBuilder.java:243)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:131)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:918)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:858)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:850)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:850)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:479)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:219)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:231)
        at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:496)
        at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:249)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:116)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:83)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:249)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:112)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:103)
        at org.elasticsearch.cli.SettingCommand.execute(SettingCommand.java:54)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:96)
        at org.elasticsearch.cli.Command.main(Command.java:62)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:80)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:73)

DEBU[0001] framesize: 76
2016-12-01 10:37:15,557 main ERROR Unable to locate plugin for RollingFile
DEBU[0001] framesize: 1974
2016-12-01 10:37:15,558 main ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.config.AppendersPlugin for element Appenders. java.lang.NullPointerException
        at org.apache.logging.log4j.core.config.plugins.visitors.PluginElementVisitor.visit(PluginElementVisitor.java:52)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.generateParameters(PluginBuilder.java:243)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:131)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:918)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:858)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:479)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:219)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:231)
        at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:496)
        at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:249)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:116)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:83)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:249)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:112)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:103)
        at org.elasticsearch.cli.SettingCommand.execute(SettingCommand.java:54)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:96)
        at org.elasticsearch.cli.Command.main(Command.java:62)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:80)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:73)

DEBU[0002] Corrupted prefix: []
DEBU[0002] [hijack] End of stdout
</code>```

答:
I encountered exactly the same error when trying to run Elasticsearch 5.3 on Docker and I was using similar properties as mentioned in the Elasticsearch logging configuration section.
It took me a while to find out why I was getting this error. It is because of a space at the end of the line when defining the type properties. There should not be any space at the end of the lines.

```<code>appender.rolling.type = RollingFile
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
</code>```

Once you remove the spaces (with the configuration mentioned above in the question) your Elasticsearch will come up but you will still get no log as it overrides the default setting for showing the error in console and the rolling appender is also not added to the root logger.
To see the log info gets generated you need the following 2 lines to be added to your log4j2.properties as well

```<code>rootLogger.level = info
rootLogger.appenderRef.rolling.ref = rolling
</code>```

Body:
I'm starting to work a docker elasticsearch 5.0.1 instance following the official instructions detailed at:

https://www.elastic.co/guide/en/elasticsearch/reference/5.0/settings.html

in order to configure elasticsearch.yml and log4j2.properties files, those files are located at:

$ pwd
/system/mesos/elasticsearchf/config
$ ls
elasticsearch.yml log4j2.properties

Contain of these configuration files:

$cat elasticsearch.yml
path:
data: /usr/share/elasticsearch/data
logs: /usr/share/elasticsearch/data
shared_data: /usr/share/elasticsearch/data
config: /usr/share/elasticsearch/config

node.add_lock_id_to_custom_path: false
index.number_of_shards: 2
cluster.name: elasticcluster
discovery.zen.ping.unicast.hosts: ["10.120.1.190", "10.120.1.191"]

$cat log4j2.properties
appender.rolling.type = RollingFile
appender.rolling.name = rolling
appender.rolling.fileName = ${sys:es.logs}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%d{ISO8601}][%-5p][%-25c] %.10000m%n
appender.rolling.filePattern = ${sys:es.logs}-%d{yyyy-MM-dd}.log
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true

And when I run command:

$ docker -D -H unix:///var/run/docker.sock run --cpu-shares 1024 --memory 2634022912 -e ES_JAVA_OPTS="-Xms2G -Xmx2G" -v /system/mesos/elasticsearchf/data:/usr/share/elasticsearch/data/:rw -v /system/mesos/elasticsearchf/config:/usr/share/elasticsearch/config/:rw --net bridge -p 9200:9200/tcp -p 9300:9300/tcp docker.elastic.co/elasticsearch/elasticsearch:5.0.1

I got error messages related with log4j2 messages you can see below

Any help will be welcome

Kind Regards

DEBU[0001] framesize: 81
2016-12-01 10:37:15,526 main ERROR Unable to locate plugin type for RollingFile
DEBU[0001] framesize: 90
2016-12-01 10:37:15,554 main ERROR Unable to locate plugin for TimeBasedTriggeringPolicy
DEBU[0001] framesize: 2223
2016-12-01 10:37:15,555 main ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy for element Policies. java.lang.NullPointerException
        at org.apache.logging.log4j.core.config.plugins.visitors.PluginElementVisitor.visit(PluginElementVisitor.java:52)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.generateParameters(PluginBuilder.java:243)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:131)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:918)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:858)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:850)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:850)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:479)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:219)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:231)
        at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:496)
        at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:249)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:116)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:83)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:249)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:112)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:103)
        at org.elasticsearch.cli.SettingCommand.execute(SettingCommand.java:54)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:96)
        at org.elasticsearch.cli.Command.main(Command.java:62)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:80)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:73)

DEBU[0001] framesize: 76
2016-12-01 10:37:15,557 main ERROR Unable to locate plugin for RollingFile
DEBU[0001] framesize: 1974
2016-12-01 10:37:15,558 main ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.config.AppendersPlugin for element Appenders. java.lang.NullPointerException
        at org.apache.logging.log4j.core.config.plugins.visitors.PluginElementVisitor.visit(PluginElementVisitor.java:52)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.generateParameters(PluginBuilder.java:243)
        at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:131)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:918)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:858)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:479)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:219)
        at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:231)
        at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:496)
        at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:249)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:116)
        at org.elasticsearch.common.logging.LogConfigurator.configure(LogConfigurator.java:83)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:249)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:112)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:103)
        at org.elasticsearch.cli.SettingCommand.execute(SettingCommand.java:54)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:96)
        at org.elasticsearch.cli.Command.main(Command.java:62)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:80)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:73)

DEBU[0002] Corrupted prefix: []
DEBU[0002] [hijack] End of stdout

Body:
I encountered exactly the same error when trying to run Elasticsearch 5.3 on Docker and I was using similar properties as mentioned in the Elasticsearch logging configuration section.
It took me a while to find out why I was getting this error. It is because of a space at the end of the line when defining the type properties. There should not be any space at the end of the lines.

appender.rolling.type = RollingFile
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy

Once you remove the spaces (with the configuration mentioned above in the question) your Elasticsearch will come up but you will still get no log as it overrides the default setting for showing the error in console and the rolling appender is also not added to the root logger.
To see the log info gets generated you need the following 2 lines to be added to your log4j2.properties as well

rootLogger.level = info
rootLogger.appenderRef.rolling.ref = rolling


问:
Set Checkmark on view did appear using will display cell not working correctly
Here is my code for the WillDisplayRow function:

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let monetaryCell = tableView.cellForRow(at: [1,0])

    //configure you cell here.
    if AppState.sharedInstance.filterPaymentMonetaryIsOn {
        monetaryCell?.accessoryType = .checkmark
        return monetaryCell!
    } else {
        monetaryCell?.accessoryType = .none
        return monetaryCell!
    }
}
</code>```

And in my DidSelectRow:

```<code> override func tableView(_ tableView: UITableView,
                        didSelectRowAt indexPath: IndexPath) {
    let monetaryCell = tableView.cellForRow(at: [1,0])
    tableView.deselectRow(at: indexPath as IndexPath, animated: true)
    if indexPath == [0,0] {
        print(indexPath)
    } else if indexPath == [1,0] {
        if AppState.sharedInstance.filterPaymentMonetaryIsOn == true {
            monetaryCell!.accessoryType = .none
            AppState.sharedInstance.filterPaymentMonetaryIsOn = false
        } else {
            monetaryCell?.accessoryType = .checkmark
            AppState.sharedInstance.filterPaymentMonetaryIsOn = true
        }
</code>```

Can someone help me out as to why this isnt working? Also, I have alot more cells and when selected each one has the same properties as above. What I'm looking for is the checkmark to be displayed when I reload the view or close and reopen the view. I hope this makes sense. I'm sorry if this is a duplicate, I looked for a few hours but couldn't find a similar situation.

Thank you in advance.

Denis Angell

答: Move your check mark display functionality from cellForRowAtIndexPath method to willDisplayCell method of UITableViewDelegate. willDisplayCell method works in such a way that whenever the cell about to appear on screen willDisplayCell method calls and desired functionality executes as expected.

Body:
Here is my code for the WillDisplayRow function:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let monetaryCell = tableView.cellForRow(at: [1,0])

    //configure you cell here.
    if AppState.sharedInstance.filterPaymentMonetaryIsOn {
        monetaryCell?.accessoryType = .checkmark
        return monetaryCell!
    } else {
        monetaryCell?.accessoryType = .none
        return monetaryCell!
    }
}

And in my DidSelectRow:

 override func tableView(_ tableView: UITableView,
                        didSelectRowAt indexPath: IndexPath) {
    let monetaryCell = tableView.cellForRow(at: [1,0])
    tableView.deselectRow(at: indexPath as IndexPath, animated: true)
    if indexPath == [0,0] {
        print(indexPath)
    } else if indexPath == [1,0] {
        if AppState.sharedInstance.filterPaymentMonetaryIsOn == true {
            monetaryCell!.accessoryType = .none
            AppState.sharedInstance.filterPaymentMonetaryIsOn = false
        } else {
            monetaryCell?.accessoryType = .checkmark
            AppState.sharedInstance.filterPaymentMonetaryIsOn = true
        }

Can someone help me out as to why this isnt working? Also, I have alot more cells and when selected each one has the same properties as above. What I'm looking for is the checkmark to be displayed when I reload the view or close and reopen the view. I hope this makes sense. I'm sorry if this is a duplicate, I looked for a few hours but couldn't find a similar situation.

Thank you in advance.

Denis Angell


问:
Why does XCTestCase override the setup method of XCTest?
I'd like to think that I understand the idea of inheritance but apparently I don't because I'm confused as to why there a setup method in XCTestCase if XCTest provides the setup method in its class?  XCTestCase is a subclass of XCTest but after reading the Apple docs, it doesn't look any different between the two.</p>

```<code>import XCTest
@testable import FirstDemo

class FirstDemoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}
</code>```

答:
XCTest is a base class, with empty setUp() and tearDown() methods.

XCTestCase inherits from XCTest, so it inherits those same methods. It doesn't have its own implementation of them. They're just do-nothing methods, anyway. They're only defined so that we can override them. This is an example of the Template Method design pattern.

Why define these methods in XCTest, or have XCTest at all? The test runner can work with anything that subclasses from XCTest, and knows nothing about XCTestCase. This potentially allows us to define new ways of defining test suites other than XCTestCase subclasses, while still integrating with the XCTest framework.

For more about xUnit architecture, see JUnit: A Cook's Tour

Body:
I'd like to think that I understand the idea of inheritance but apparently I don't because I'm confused as to why there a setup method in XCTestCase if XCTest provides the setup method in its class?  XCTestCase is a subclass of XCTest but after reading the Apple docs, it doesn't look any different between the two.

import XCTest
@testable import FirstDemo

class FirstDemoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}


问:
Why should I create function Add?
Most of expert programmer here have down voted my answer as bad answer

How to add a field to an ArrayList from a different class?

So, I wonder why do I need to create another function Add to add items to my list. While most of programming language such as Java C# and VB.NET allow us a very simple way by using Getter as a List or ArrayList that we be able to add and use many function that this class has directly as sample as bellow

C#

```<code>class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee();
        emp.lst.Add("Hello");
    }
}
class Employee
{
    private List<string> _lst = new List<string>();

    public List<string> lst
    {
        get { return _lst; }
    }
    //public void add(String item) {
    //    _lst.Add(item);
    //}
}
</code>```

Java

```<code>    public class MainApp {
        public static void main(String[] args){
            Employee emp = new Employee();
            emp.getLst().add("My String");
        }
    }

    class Employee{
       private List<String> lst = new ArrayList<String>();

       public List<String> getLst() {
            return lst;
       }
       public void setLst(List<String> lst) {
           this.lst = lst;
       }
   }
</code>```

Most of languages are allow us to do this ways. So, what is the reason I need to create function Add for on Employee?

答:
Practical reason: getList() may return either internal list or copy of that list. There is no way for consumer of the class to know what is the behavior of the method without knowing implementation of getList() (or less likely find and read documentation on that particular method of particular class). So adding to or modifying result of getList() call  in any other way may never change the original object and proving correctness will require reading all the code including (frequently private) implementation of getList().

Whether it is useful to expose separate methods to add to the list or not is personal choice based on particular code. Generally it is better to provide specific methods for all operations on the object as one can guarantee consistency of the state of the object.

For example if object is plain data transfer object having raw lists is fine there, but if it is Student exposing modifiable list of classes may easily lead to inconsistent state if for example total score class is stored independently.

Title: Why should I create function Add?

Body:
Most of expert programmer here have down voted my answer as bad answer

How to add a field to an ArrayList from a different class?

So, I wonder why do I need to create another function Add to add items to my list. While most of programming language such as Java C# and VB.NET allow us a very simple way by using Getter as a List or ArrayList that we be able to add and use many function that this class has directly as sample as bellow

C#

class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee();
        emp.lst.Add("Hello");
    }
}
class Employee
{
    private List<string> _lst = new List<string>();

    public List<string> lst
    {
        get { return _lst; }
    }
    //public void add(String item) {
    //    _lst.Add(item);
    //}
}

Java

    public class MainApp {
        public static void main(String[] args){
            Employee emp = new Employee();
            emp.getLst().add("My String");
        }
    }

    class Employee{
       private List<String> lst = new ArrayList<String>();

       public List<String> getLst() {
            return lst;
       }
       public void setLst(List<String> lst) {
           this.lst = lst;
       }
   }

Most of languages are allow us to do this ways. So, what is the reason I need to create function Add for on Employee?


问:
Datatables.js - multiple customized languages
I'm working with Datatables.js in different human languages. I'm using the language plugins provided by Datatables and they work fine. However, I would like to overwrite a few of the translations with my own translations.

How can I do this in the best way?

Here's my code:

```<code>  function getLanguage() {
    var $langMap = {
      en: 'English',
      es: 'Spanish'
    };
    var $lang = $('html').attr('lang');
    return '//cdn.datatables.net/plug-ins/1.10.13/i18n/' + $langMap[$lang] + '.json';
  }

  // Build Datatable
  $('#example').DataTable({
    language: {
      url: getLanguage() // works perfectly, but I need to overwrite with a few custom text options
    }
  });
</code>```

Say, I want to owerwrite these language options:

```<code>  en: {
    // Overwrite defaults with this string
    "lengthMenu": "Display _MENU_ records per page - custom test",
  },
  es: {
    // Overwrite Spanish defaults with this string
    "lengthMenu": "Mostrar _MENU_ registros - algo muy especial...",
  }
</code>```

JsFiddle here.

Ref: Datatables.js language options.

答:
You could expand your langMap to hold the modifications you want to add to the language struct :

var langMap = {
  en: {
    path: 'English',
    mods: {
      sLengthMenu: "Display _MENU_ records per page - custom test"
    }
  },
  es: {
    path: 'Spanish',
    mods: {
      sLengthMenu: "Mostrar _MENU_ registros - algo muy especial..."
    }
  }
};
```

<p>Notice I am using hungarian notation, <code>sLengthMenu</code> instead of <code>lengthMenu</code>. This is due to the fact that the language files still is using this format. Then load the language object through a synchronous AJAX request, modify with the <code>mods</code> and return </p>

<pre class="lang-js prettyprint-override"><code>function getLanguage() {
  var lang = $('html').attr('lang');
  var path = '//cdn.datatables.net/plug-ins/1.10.13/i18n/';
  var result = null;
  $.ajax({
    async: false,
    url: path + langMap[lang].path + '.json',
    success: function(obj) {
      result = $.extend({}, obj, langMap[lang].mods)
    }
  })
  return result
}

// Build Datatable
$('#example').DataTable({
  language: getLanguage()
});
</code>```

demo -> http://jsfiddle.net/v84wjLqe/ (with hardcoded es just for test)

Note: Instead of using async: false you could consider using a promise, jQuery deferred, q or one of the promise polyfills. But this is beyond the question.

Body:
I'm working with Datatables.js in different human languages. I'm using the language plugins provided by Datatables and they work fine. However, I would like to overwrite a few of the translations with my own translations.

How can I do this in the best way?

Here's my code:

  function getLanguage() {
    var $langMap = {
      en: 'English',
      es: 'Spanish'
    };
    var $lang = $('html').attr('lang');
    return '//cdn.datatables.net/plug-ins/1.10.13/i18n/' + $langMap[$lang] + '.json';
  }

  // Build Datatable
  $('#example').DataTable({
    language: {
      url: getLanguage() // works perfectly, but I need to overwrite with a few custom text options
    }
  });

Say, I want to owerwrite these language options:

  en: {
    // Overwrite defaults with this string
    "lengthMenu": "Display _MENU_ records per page - custom test",
  },
  es: {
    // Overwrite Spanish defaults with this string
    "lengthMenu": "Mostrar _MENU_ registros - algo muy especial...",
  }

JsFiddle here.

Ref: Datatables.js language options.

Body:
You could expand your langMap to hold the modifications you want to add to the language struct :

var langMap = {
  en: {
    path: 'English',
    mods: {
      sLengthMenu: "Display _MENU_ records per page - custom test"
    }
  },
  es: {
    path: 'Spanish',
    mods: {
      sLengthMenu: "Mostrar _MENU_ registros - algo muy especial..."
    }
  }
};

Notice I am using hungarian notation, sLengthMenu instead of lengthMenu. This is due to the fact that the language files still is using this format. Then load the language object through a synchronous AJAX request, modify with the mods and return

function getLanguage() {
  var lang = $('html').attr('lang');
  var path = '//cdn.datatables.net/plug-ins/1.10.13/i18n/';
  var result = null;
  $.ajax({
    async: false,
    url: path + langMap[lang].path + '.json',
    success: function(obj) {
      result = $.extend({}, obj, langMap[lang].mods)
    }
  })
  return result
}

// Build Datatable
$('#example').DataTable({
  language: getLanguage()
});

demo -> http://jsfiddle.net/v84wjLqe/ (with hardcoded es just for test)

Note: Instead of using async: false you could consider using a promise, jQuery deferred, q or one of the promise polyfills. But this is beyond the question.