问:
'classmethod' object is not callable inside a metaclass's method in Python 3
I am trying to implement a metaclass that initializes class variables when a first its instance is being created. I want to keep a new magic method __load__ that should be called as a classmethod (like __new__). So I implemented it like this:

```<code>class StaticLoad(type):
    __loaded_classes = set()

    def __call__(cls, *args, **kwargs):
        if cls not in cls.__loaded_classes:
            if hasattr(cls, '__load__'):
                cls.__load__()
            cls.__loaded_classes.add(cls)
        return super().__call__(*args, **kwargs)

class BaseClass(metaclass=StaticLoad):
    s = 0

class MyClass(BaseClass):
    @classmethod
    def __load__(cls):
        print("Loading", cls.__name__, "...")
        cls.s += 1

obj1 = MyClass()
obj2 = MyClass()
print(MyClass.s)
</code>```

It works fine and gives the correct result:

```<code>Loading MyClass ...
1
</code>```

Now I want to implement the method __load__ as a classmethod by default like __new__ (without the need to type @classmethod above each time). I tried this:

```<code>class StaticLoad(type):
    __loaded_classes = set()

    def __call__(cls, *args, **kwargs):
        if cls not in cls.__loaded_classes:
            if hasattr(cls, '__load__'):
                # I try to apply classmethod routine to make
                # cls.__load__ a classmethod
                classmethod(cls.__load__)()
            cls.__loaded_classes.add(cls)
        return super().__call__(*args, **kwargs)

class BaseClass(metaclass=StaticLoad):
    s = 0

class MyClass(BaseClass):
    # @classmethod line was deleted
    def __load__(cls):
        print("Loading", cls.__name__, "...")
        cls.s += 1

obj1 = MyClass()
obj2 = MyClass()
print(MyClass.s)
</code>```

I got the error:

```<code>Traceback (most recent call last):
  File "example.py", line 22, in <module>
    obj1 = MyClass()
  File "example.py", line 7, in __call__
    classmethod(cls.__load__)()
TypeError: 'classmethod' object is not callable
</code>```

It looks like classmethod routine is correctly available only inside a class definition.

How should I improve my metaclass to make it work fine? I would like to keep the content of classes BaseClass and MyClass as I wrote above, placing all magic into StaticLoad.

答:
With the help of @AnttiHaapala the solution is simple. Instead of calling

```<code>classmethod(cls.__load__)()
</code>```

I had to call

```<code>cls.__load__(cls)
</code>```

Body:
I am trying to implement a metaclass that initializes class variables when a first its instance is being created. I want to keep a new magic method __load__ that should be called as a classmethod (like __new__). So I implemented it like this:

class StaticLoad(type):
    __loaded_classes = set()

    def __call__(cls, *args, **kwargs):
        if cls not in cls.__loaded_classes:
            if hasattr(cls, '__load__'):
                cls.__load__()
            cls.__loaded_classes.add(cls)
        return super().__call__(*args, **kwargs)

class BaseClass(metaclass=StaticLoad):
    s = 0

class MyClass(BaseClass):
    @classmethod
    def __load__(cls):
        print("Loading", cls.__name__, "...")
        cls.s += 1

obj1 = MyClass()
obj2 = MyClass()
print(MyClass.s)

It works fine and gives the correct result:

Loading MyClass ...
1

Now I want to implement the method __load__ as a classmethod by default like __new__ (without the need to type @classmethod above each time). I tried this:

class StaticLoad(type):
    __loaded_classes = set()

    def __call__(cls, *args, **kwargs):
        if cls not in cls.__loaded_classes:
            if hasattr(cls, '__load__'):
                # I try to apply classmethod routine to make
                # cls.__load__ a classmethod
                classmethod(cls.__load__)()
            cls.__loaded_classes.add(cls)
        return super().__call__(*args, **kwargs)

class BaseClass(metaclass=StaticLoad):
    s = 0

class MyClass(BaseClass):
    # @classmethod line was deleted
    def __load__(cls):
        print("Loading", cls.__name__, "...")
        cls.s += 1

obj1 = MyClass()
obj2 = MyClass()
print(MyClass.s)

I got the error:

Traceback (most recent call last):
  File "example.py", line 22, in <module>
    obj1 = MyClass()
  File "example.py", line 7, in __call__
    classmethod(cls.__load__)()
TypeError: 'classmethod' object is not callable

It looks like classmethod routine is correctly available only inside a class definition.

How should I improve my metaclass to make it work fine? I would like to keep the content of classes BaseClass and MyClass as I wrote above, placing all magic into StaticLoad.

Body:
With the help of @AnttiHaapala the solution is simple. Instead of calling

classmethod(cls.__load__)()

I had to call

cls.__load__(cls)


来源: stackexchange

问:
android firebase database: how to get all nodes that are in a set of values
I am trying to retrieve a list of friends for a user so I can display them in a list view. The friends and user info is structured like this in my firebase database:

So basically, I want to take the user ids listed in the friends part and query my users data to get all the info under every node that is in that set of user ids. How can I achieve this using the android firebase database sdk querying? I would like to be able to retrieve all the users in a single database query.

Thanks.

答:
You cannot get that data in single query, you need to query your database twice. This is a common practice when it comes to Firebase. Assuming that friends and users nodes are direct childs of your Firebase root, to achieve this, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendIdRef = rootRef.child("friends").child(friendId)
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();

            DatabaseReference usersRef = rootRef.child("users").child(key);
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                        String username = dSnapshot.child("username").getValue(String.class);
                        Log.d("TAG", username);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            usersRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
friendIdRef.addListenerForSingleValueEvent(valueEventListener);
</code>```

It will print all user names of those particular users. One more thing to note, is that you don't need to add in your database those friends that have the value of false, only those with the value of true.

ContentLicense: CC BY-SA 3.0

Body:
You cannot get that data in single query, you need to query your database twice. This is a common practice when it comes to Firebase. Assuming that friends and users nodes are direct childs of your Firebase root, to achieve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendIdRef = rootRef.child("friends").child(friendId)
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();

            DatabaseReference usersRef = rootRef.child("users").child(key);
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                        String username = dSnapshot.child("username").getValue(String.class);
                        Log.d("TAG", username);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            usersRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
friendIdRef.addListenerForSingleValueEvent(valueEventListener);

It will print all user names of those particular users. One more thing to note, is that you don't need to add in your database those friends that have the value of false, only those with the value of true.


问:
Work folder in Jboss Fuse
What is the work folder in Jboss Fuse?

I had re-deployed camel blueprint project in Jboss Fuse, but new changes are not effected in Jboss Fuse.

Jboss Fuse processing with my previous project deployment.

答:
If you are facing problem with a single application you don't need to delete data folder.
Open Karaf console and logs in two tabs

Step 1 : stop bundleID{ID of bundle that you need to uninstall} (on karaf)
Step 2 : tailf fuse.log | grep -i "Application context"(You will see 2 logs )

Unpublishing application context OSGi service for bundle {bundleName}

Application context succesfully closed

Step 3 : osgi:uninstall bundleId

Still if you face issue.

Goto FUSE_HOME/data/cache and delete folder with name bunndle{ID} where ID is bundle ID that you need to uninstall.

If still issue occurs, please change the version of your bundle and then install

Title: Work folder in Jboss Fuse


问:
How to extract substring as part of dplyr::mutate piping
I have the following data frame:

library(tidyverse)

df <-  structure(list(pfc_chr = c("chr1", "chr1", "chr1", "chr1", "chr1",
"chr1", "chr1", "chr1", "chr1", "chr1"), pfc_chr_st = c(3046442L,
3119671L, 3164756L, 3167322L, 3210838L, 3212196L, 3249068L, 3268246L,
3444892L, 3451544L), peak_name = c("XXX-ad_peak_1", "XXX-ad_peak_2a",
"PMN_peak_2", "Ytb_peak_3", "PMN_peak_3", "XXX-ad_peak_6",
"XXX-ad_peak_8", "PMN_peak_5", "XXX-ad_peak_11", "XXX-ad_peak_12"
)), .Names = c("pfc_chr", "pfc_chr_st", "peak_name"), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

df
#> # A tibble: 10 x 3
#>    pfc_chr pfc_chr_st      peak_name
#>      <chr>      <int>          <chr>
#>  1    chr1    3046442  XXX-ad_peak_1
#>  2    chr1    3119671 XXX-ad_peak_2a
#>  3    chr1    3164756     PMN_peak_2
#>  4    chr1    3167322     Ytb_peak_3
#>  5    chr1    3210838     PMN_peak_3
#>  6    chr1    3212196  XXX-ad_peak_6
#>  7    chr1    3249068  XXX-ad_peak_8
#>  8    chr1    3268246     PMN_peak_5
#>  9    chr1    3444892 XXX-ad_peak_11
#> 10    chr1    3451544 XXX-ad_peak_12
```

<p>What I want to do is to extract the substring in <code>peak_name</code> as part of
dplyr pipe. The final desired result is:</p>

<pre class="lang-r prettyprint-override"><code>   pfc_chr pfc_chr_st      peak_name        new_col
1     chr1    3046442  XXX-ad_peak_1         XXX-ad
2     chr1    3119671 XXX-ad_peak_2a         XXX-ad
3     chr1    3164756     PMN_peak_2            PMN
4     chr1    3167322     Ytb_peak_3            Ytb
5     chr1    3210838     PMN_peak_3            PMN
6     chr1    3212196  XXX-ad_peak_6         XXX-ad
7     chr1    3249068  XXX-ad_peak_8         XXX-ad
8     chr1    3268246     PMN_peak_5            PMN
9     chr1    3444892 XXX-ad_peak_11         XXX-ad
10    chr1    3451544 XXX-ad_peak_12         XXX-ad
</code>```

I tried this but fail:

> df %>% mutate(new_col = stringr::str_match(peak_name, "^(.*?)\\_peak\\_*?"))
Error in mutate_impl(.data, dots) :
  Column `new_col` must be length 10 (the number of rows) or one, not 20
```

What's the right way to do it?

答:
I would suggest stringr::str_extract() using a lookahead:

```<code>df %>%
  mutate(new_col = stringr::str_extract(peak_name, "^.*(?=_peak)"))
</code>```

The results are shown below:

```<code>> df %>%
+   mutate(new_col = stringr::str_extract(peak_name, "^.*(?=_peak)"))
# A tibble: 10 x 4
   pfc_chr pfc_chr_st      peak_name new_col
     <chr>      <int>          <chr>   <chr>
 1    chr1    3046442  XXX-ad_peak_1  XXX-ad
 2    chr1    3119671 XXX-ad_peak_2a  XXX-ad
 3    chr1    3164756     PMN_peak_2     PMN
 4    chr1    3167322     Ytb_peak_3     Ytb
 5    chr1    3210838     PMN_peak_3     PMN
 6    chr1    3212196  XXX-ad_peak_6  XXX-ad
 7    chr1    3249068  XXX-ad_peak_8  XXX-ad
 8    chr1    3268246     PMN_peak_5     PMN
 9    chr1    3444892 XXX-ad_peak_11  XXX-ad
10    chr1    3451544 XXX-ad_peak_12  XXX-ad
</code>```

Note that data such as "_peak_8" would return an empty string; data such as "peak_8" returns NA.

Body:
I have the following data frame:

library(tidyverse)

df <-  structure(list(pfc_chr = c("chr1", "chr1", "chr1", "chr1", "chr1",
"chr1", "chr1", "chr1", "chr1", "chr1"), pfc_chr_st = c(3046442L,
3119671L, 3164756L, 3167322L, 3210838L, 3212196L, 3249068L, 3268246L,
3444892L, 3451544L), peak_name = c("XXX-ad_peak_1", "XXX-ad_peak_2a",
"PMN_peak_2", "Ytb_peak_3", "PMN_peak_3", "XXX-ad_peak_6",
"XXX-ad_peak_8", "PMN_peak_5", "XXX-ad_peak_11", "XXX-ad_peak_12"
)), .Names = c("pfc_chr", "pfc_chr_st", "peak_name"), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

df
#> # A tibble: 10 x 3
#>    pfc_chr pfc_chr_st      peak_name
#>      <chr>      <int>          <chr>
#>  1    chr1    3046442  XXX-ad_peak_1
#>  2    chr1    3119671 XXX-ad_peak_2a
#>  3    chr1    3164756     PMN_peak_2
#>  4    chr1    3167322     Ytb_peak_3
#>  5    chr1    3210838     PMN_peak_3
#>  6    chr1    3212196  XXX-ad_peak_6
#>  7    chr1    3249068  XXX-ad_peak_8
#>  8    chr1    3268246     PMN_peak_5
#>  9    chr1    3444892 XXX-ad_peak_11
#> 10    chr1    3451544 XXX-ad_peak_12

What I want to do is to extract the substring in peak_name as part of
dplyr pipe. The final desired result is:

   pfc_chr pfc_chr_st      peak_name        new_col
1     chr1    3046442  XXX-ad_peak_1         XXX-ad
2     chr1    3119671 XXX-ad_peak_2a         XXX-ad
3     chr1    3164756     PMN_peak_2            PMN
4     chr1    3167322     Ytb_peak_3            Ytb
5     chr1    3210838     PMN_peak_3            PMN
6     chr1    3212196  XXX-ad_peak_6         XXX-ad
7     chr1    3249068  XXX-ad_peak_8         XXX-ad
8     chr1    3268246     PMN_peak_5            PMN
9     chr1    3444892 XXX-ad_peak_11         XXX-ad
10    chr1    3451544 XXX-ad_peak_12         XXX-ad

I tried this but fail:

> df %>% mutate(new_col = stringr::str_match(peak_name, "^(.*?)\\_peak\\_*?"))
Error in mutate_impl(.data, dots) :
  Column `new_col` must be length 10 (the number of rows) or one, not 20

What's the right way to do it?

Body:
I would suggest stringr::str_extract() using a lookahead:

df %>%
  mutate(new_col = stringr::str_extract(peak_name, "^.*(?=_peak)"))

The results are shown below:

> df %>%
+   mutate(new_col = stringr::str_extract(peak_name, "^.*(?=_peak)"))
# A tibble: 10 x 4
   pfc_chr pfc_chr_st      peak_name new_col
     <chr>      <int>          <chr>   <chr>
 1    chr1    3046442  XXX-ad_peak_1  XXX-ad
 2    chr1    3119671 XXX-ad_peak_2a  XXX-ad
 3    chr1    3164756     PMN_peak_2     PMN
 4    chr1    3167322     Ytb_peak_3     Ytb
 5    chr1    3210838     PMN_peak_3     PMN
 6    chr1    3212196  XXX-ad_peak_6  XXX-ad
 7    chr1    3249068  XXX-ad_peak_8  XXX-ad
 8    chr1    3268246     PMN_peak_5     PMN
 9    chr1    3444892 XXX-ad_peak_11  XXX-ad
10    chr1    3451544 XXX-ad_peak_12  XXX-ad

Note that data such as "_peak_8" would return an empty string; data such as "peak_8" returns NA.


问:
Reshaping vector to n-d matrix in row-wise order
I'm trying to convert a vector into a 3d matrix in a row-wise manner.

For example, my vector is:

```<code>a = 1:18;
</code>```

and I'd like to convert this to a 2x3x3 matrix:

```<code> b(:,:,1) = [1 2 3; 4 5 6];
 b(:,:,2) = [7 8 9; 10 11 12];
 b(:,:,3) = [13 14 15; 16 17 18];
</code>```

but the reshape function (i.e. reshape(a, 2,3,3)) arranges the elements in a column-wise fashion as:

```<code>val(:,:,1) =

     1     3     5
     2     4     6

val(:,:,2) =

     7     9    11
     8    10    12

val(:,:,3) =

    13    15    17
    14    16    18
</code>```

How can I obtain the matrix b from vector a?

Body:
I'm trying to convert a vector into a 3d matrix in a row-wise manner.

For example, my vector is:

a = 1:18;

and I'd like to convert this to a 2x3x3 matrix:

 b(:,:,1) = [1 2 3; 4 5 6];
 b(:,:,2) = [7 8 9; 10 11 12];
 b(:,:,3) = [13 14 15; 16 17 18];

but the reshape function (i.e. reshape(a, 2,3,3)) arranges the elements in a column-wise fashion as:

val(:,:,1) =

     1     3     5
     2     4     6

val(:,:,2) =

     7     9    11
     8    10    12

val(:,:,3) =

    13    15    17
    14    16    18

How can I obtain the matrix b from vector a?

Body:
Use combination of reshape and permute.

b = permute(reshape(a,3,2,3),[2 1 3]);

b(:,:,1) =

     1     2     3
     4     5     6

b(:,:,2) =

     7     8     9
    10    11    12

b(:,:,3) =

    13    14    15
    16    17    18


问:
How to use definitions (define variable) in include
I am trying to create some "config.php" where I will have defined global variables, like default path to project. How can I use this defined variable in include?

My config.php:

```<code>$path = $_SERVER['DOCUMENT_ROOT'] . "/docme/";

require_once "resources/scripts/pdo.php";

ini_set('display_errors', TRUE);
date_default_timezone_set( "Europe/Prague" );

//Nastavení konstant webu
define('DB_NAME', 'project');
define('DB_USER', 'root');
define('DB_PASSWORD', 'pswd');
define('DB_HOST', '127.0.0.1');
define('SITETITLE', 'DocMe!');
define('PATH', $path);
</code>```

And now I need to use the PATH variable in include, is it even possible?

```<code><?php
   require_once "config.php";
   include_once PATH."/index.php";
?>
</code>```

Okay sorry here is the problem I didn't realize it's actually problem somewhere else. On localhost it's working fine, at website (live) it's not working, cuz   $path = $_SERVER['DOCUMENT_ROOT'] = returns me only "/".

答:
"Yes it's working on localhost, but why it's not working the $_SERVER['DOCUMENT_ROOT'] on live website? It returns me only "/" not something like "student.sps-prosek.cz/....";, is it better to use $path = $_SERVER['HTTP_HOST''] ?"

I understand your problem, the problem is when you deploy to a server the url will change.

try this code

```<code><?php

define('PROJECT_BASE_FOLDER'    , substr($_SERVER['REQUEST_URI'], 0, 8) == '/sample/' ? '/sample/' : '');
//sample is the name of the folder. the 0 to 8 is how many char your project name has including the '/'

define('PROJECT_FOLDER'         , substr($_SERVER['REQUEST_URI'], 0, 8) == '/sample/' ? '' : '');
define('HTTP'                   , 'http://');
define('BASE_PATH'              , $_SERVER['DOCUMENT_ROOT'] . PROJECT_BASE_FOLDER . PROJECT_FOLDER);

define('SITE_URL'               , HTTP . $_SERVER['SERVER_NAME'] . str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', BASE_PATH));
// or ':8080/' is the port you are using in your local machine
define('SITE_URL'               , HTTP . $_SERVER['SERVER_NAME'] . ':8080/' . str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', BASE_PATH));
</code>```

therefore in your code you will use

```<code><?php
   require_once "config.php";
   include_once BASE_PATH ."/index.php";
?>
</code>```

This should work as I am using this logic so that I will not have to change the directory every time I need to deploy to a server.

Body:
I am trying to create some "config.php" where I will have defined global variables, like default path to project. How can I use this defined variable in include?

My config.php:

$path = $_SERVER['DOCUMENT_ROOT'] . "/docme/";

require_once "resources/scripts/pdo.php";

ini_set('display_errors', TRUE);
date_default_timezone_set( "Europe/Prague" );

//Nastavení konstant webu
define('DB_NAME', 'project');
define('DB_USER', 'root');
define('DB_PASSWORD', 'pswd');
define('DB_HOST', '127.0.0.1');
define('SITETITLE', 'DocMe!');
define('PATH', $path);

And now I need to use the PATH variable in include, is it even possible?

<?php
   require_once "config.php";
   include_once PATH."/index.php";
?>

Okay sorry here is the problem I didn't realize it's actually problem somewhere else. On localhost it's working fine, at website (live) it's not working, cuz   $path = $_SERVER['DOCUMENT_ROOT'] = returns me only "/".

Body:
"Yes it's working on localhost, but why it's not working the $_SERVER['DOCUMENT_ROOT'] on live website? It returns me only "/" not something like "student.sps-prosek.cz/....";, is it better to use $path = $_SERVER['HTTP_HOST''] ?"

I understand your problem, the problem is when you deploy to a server the url will change.

try this code

<?php

define('PROJECT_BASE_FOLDER'    , substr($_SERVER['REQUEST_URI'], 0, 8) == '/sample/' ? '/sample/' : '');
//sample is the name of the folder. the 0 to 8 is how many char your project name has including the '/'

define('PROJECT_FOLDER'         , substr($_SERVER['REQUEST_URI'], 0, 8) == '/sample/' ? '' : '');
define('HTTP'                   , 'http://');
define('BASE_PATH'              , $_SERVER['DOCUMENT_ROOT'] . PROJECT_BASE_FOLDER . PROJECT_FOLDER);

define('SITE_URL'               , HTTP . $_SERVER['SERVER_NAME'] . str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', BASE_PATH));
// or ':8080/' is the port you are using in your local machine
define('SITE_URL'               , HTTP . $_SERVER['SERVER_NAME'] . ':8080/' . str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', BASE_PATH));

therefore in your code you will use

<?php
   require_once "config.php";
   include_once BASE_PATH ."/index.php";
?>

This should work as I am using this logic so that I will not have to change the directory every time I need to deploy to a server.


问:
finding the middle index of a substring when there are duplicates in the string
I was working on a Java coding problem and encountered the following issue.

Problem:
Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one

```<code>xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBBB") → false
</code>```

My Code:

```<code>public boolean xyzMiddle(String str) {
  boolean result=false;
  if(str.length()<3)result=false;
  if(str.length()==3 && str.equals("xyz"))result=true;
  for(int j=0;j<str.length()-3;j++){
    if(str.substring(j,j+3).equals("xyz")){
       String rightSide=str.substring(j+3,str.length());
       int rightLength=rightSide.length();
       String leftSide=str.substring(0,j);
       int leftLength=leftSide.length();
       int diff=Math.abs(rightLength-leftLength);
       if(diff>=0 && diff<=1)result=true;
       else result=false;
    }
  }
  return result;
}
</code>```

Output I am getting:
Running for most of the test cases but failing for certain edge cases involving more than once occurence of "xyz" in the string

Example:

```<code>xyzMiddle("xyzxyzAxyzBxyzxyz")
</code>```

My present method is taking the "xyz" starting at the index 0. I understood the problem. I want a solution where the condition is using only string manipulation functions.

NOTE: I need to solve this using string manipulations like substrings. I am not considering using list, stringbuffer/builder etc. Would appreciate answers which can build up on my code.

答:
Managing your code, I left unchanged the cases str.lengt<3 and str.lengt==3.
Taking inspiration from @Andy's answer, I considered the pattern

prefix+'xyz'+suffix

and, while looking for matches I controlled also if they respect the rule IsMiddle, as you defined it. If a match that respect the rule is found, the loop breaks and return a success, else the loop continue.

```<code>public boolean xyzMiddle(String str) {
      boolean result=false;
      if(str.length()<3)
              result=false;
      else if(str.length()==3 && str.equals("xyz"))
              result=true;
      else{
          int preLen=-1;
          int sufLen=-2;
          int k=0;
          while(k<str.lenght){
              if(str.indexOf('xyz',k)!=-1){
                count++;
                k=str.indexOf('xyz',k);
                //check if match is in the middle
                preLen=str.substring(0,k).lenght;
                sufLen=str.substring(k+3,str.lenght-1).lenght;
                if(preLen==sufLen || preLen==sufLen-1 || preLen==sufLen+1){
                   result=true;
                   k=str.length; //breaks the while loop
                }
                else
                   result=false;
              }
              else
                k++;
          }

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

Body:
I was working on a Java coding problem and encountered the following issue.

Problem:
Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one

xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBBB") → false

My Code:

public boolean xyzMiddle(String str) {
  boolean result=false;
  if(str.length()<3)result=false;
  if(str.length()==3 && str.equals("xyz"))result=true;
  for(int j=0;j<str.length()-3;j++){
    if(str.substring(j,j+3).equals("xyz")){
       String rightSide=str.substring(j+3,str.length());
       int rightLength=rightSide.length();
       String leftSide=str.substring(0,j);
       int leftLength=leftSide.length();
       int diff=Math.abs(rightLength-leftLength);
       if(diff>=0 && diff<=1)result=true;
       else result=false;
    }
  }
  return result;
}

Output I am getting:
Running for most of the test cases but failing for certain edge cases involving more than once occurence of "xyz" in the string

Example:

xyzMiddle("xyzxyzAxyzBxyzxyz")

My present method is taking the "xyz" starting at the index 0. I understood the problem. I want a solution where the condition is using only string manipulation functions.

NOTE: I need to solve this using string manipulations like substrings. I am not considering using list, stringbuffer/builder etc. Would appreciate answers which can build up on my code.

Body:
Managing your code, I left unchanged the cases str.lengt<3 and str.lengt==3.
Taking inspiration from @Andy's answer, I considered the pattern

prefix+'xyz'+suffix

and, while looking for matches I controlled also if they respect the rule IsMiddle, as you defined it. If a match that respect the rule is found, the loop breaks and return a success, else the loop continue.

public boolean xyzMiddle(String str) {
      boolean result=false;
      if(str.length()<3)
              result=false;
      else if(str.length()==3 && str.equals("xyz"))
              result=true;
      else{
          int preLen=-1;
          int sufLen=-2;
          int k=0;
          while(k<str.lenght){
              if(str.indexOf('xyz',k)!=-1){
                count++;
                k=str.indexOf('xyz',k);
                //check if match is in the middle
                preLen=str.substring(0,k).lenght;
                sufLen=str.substring(k+3,str.lenght-1).lenght;
                if(preLen==sufLen || preLen==sufLen-1 || preLen==sufLen+1){
                   result=true;
                   k=str.length; //breaks the while loop
                }
                else
                   result=false;
              }
              else
                k++;
          }

        }
      return result;
    }


问:
How to create a "help / information bubble" with netbean
I'm trying to create a GUI with netbean, and I've created a tool bar with different icon. What I want to do is this: When you mouse over one of the button I want a little text bubble to appear with text that I will have specified.

I've been searching the web for a while, and all I could find was something about this package: "org.openide.awt" wich contains (in theory from what I've read) NotificationDisplayer.

If this thing really works with java and netbeans well, I can't get it to work. All I need to know is does this package is actually netbean/java compatible, or better, if there is a simpler way to display a text bubble.

答:
A tool tip?

The JComponent API has support for that.

Check if this is what you need:

How to Use Tool Bars

ie:

ContentLicense: CC BY-SA 2.5


问:
Convert MM:SS to HH:MM:SS (cast to time), SQL
I am attempting to convert a columns data from MM:SS to time [HH:MM:SS.NNNNNNN] so that i can aggregate the field in my cube/aggregate dimension. As the photo below [source] depicts, the data was landed into my database in the data type/format of MM:SS (varchar).

I attempted to parse out the minutes and seconds; cast the columns into datatype int; and write a case to calculate hours.

From this, i then wrote a case to get the data into the time datatype [Case Column photo]. However, when i went to cast the new calculated field as time, it came up with an error message.

How would i go about doing this?

SELECT CAST ( HRS AS VARCHAR(2) ) + ':' + CAST ( MN AS VARCHAR(2) ) + ':' + CAST (SEC  AS VARCHAR(2)) + '.' + '0000000' AS TOI
FROM  (
    SELECT CASE
    WHEN  CAST ( PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) AS INT) > 60 AND  CAST ( PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) AS INT) < 120 THEN '01'
    WHEN  CAST ( PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) AS INT) > 120 THEN '02'
    WHEN  CAST ( PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) AS INT) < 60  THEN '00'
    ELSE '00'
     END AS HRS
     , CASE
      WHEN CAST ( PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) AS INT) > 60 THEN CONCAT(0, PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) - 60)
      WHEN CAST ( PARSENAME ( REPLACE ( TOI, ':', '.'), 2 ) AS INT) > 60 THEN PARSENAME ( REPLACE ( TOI, ':', '.'), 2 )
      ELSE PARSENAME ( REPLACE ( TOI, ':', '.'), 2 )
       END AS MN
     , PARSENAME ( REPLACE ( TOI, ':', '.'), 1 ) AS SEC
    FROM LAND_HOME_GOALIES
   ) S;```

答:
In real life '61:15' is not considered to be valid MM:SS data like you are saying.But in case if it true somehow then,

```<code>declare @table table(TOI varchar(10))
insert into @table values ('241:15')
,('61:15'),('40:36')

select TOI as OLdTOI,right(('00'+ cast(([Min]/60) as varchar)),2)
+':'+right('00'+cast([Min]-([Min]/60)*60 as varchar) , 2)
+':'+ right('00'+Sec,2) NewTOI
 from
(
select TOI, substring(TOI,0,charindex(':',TOI)) [Min]
,substring(TOI,charindex(':',TOI)+1,len(TOI)) Sec
from @table
)t4
</code>```

Body:
In real life '61:15' is not considered to be valid MM:SS data like you are saying.But in case if it true somehow then,

declare @table table(TOI varchar(10))
insert into @table values ('241:15')
,('61:15'),('40:36')

select TOI as OLdTOI,right(('00'+ cast(([Min]/60) as varchar)),2)
+':'+right('00'+cast([Min]-([Min]/60)*60 as varchar) , 2)
+':'+ right('00'+Sec,2) NewTOI
 from
(
select TOI, substring(TOI,0,charindex(':',TOI)) [Min]
,substring(TOI,charindex(':',TOI)+1,len(TOI)) Sec
from @table
)t4


问:
How to check element duplicate in Map java
I have a function, which allow input key and value into Map.

here my code

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

public class MapDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            System.out.println("Key: ");
            String sKey = input.nextLine();
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
    }
}
</code>```

I don't know how to check element next, which I will input. it the same with element before, and if it same I will input again.

答:
Add a while loop :  </p>

```<code>  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Map<String, Integer> map = new HashMap<>();
    System.out.println("Elemment number: ");
    String sNum = input.nextLine();
    int iNum = Integer.parseInt(sNum);
    for (int i = 0; i < iNum; i++) {
        String sKey ;
        do {
            System.out.println("Key: ");
            sKey = input.nextLine();
        } while (map.containsKey(sKey));

        System.out.println("Value: ");
        String sValue = input.nextLine();
        int iValue = Integer.parseInt(sValue);
        map.put(sKey, iValue);
    }
 }
</code>```

Body:
I have a function, which allow input key and value into Map.

here my code

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MapDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            System.out.println("Key: ");
            String sKey = input.nextLine();
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
    }
}

I don't know how to check element next, which I will input. it the same with element before, and if it same I will input again.

Body:
Add a while loop :

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Map<String, Integer> map = new HashMap<>();
    System.out.println("Elemment number: ");
    String sNum = input.nextLine();
    int iNum = Integer.parseInt(sNum);
    for (int i = 0; i < iNum; i++) {
        String sKey ;
        do {
            System.out.println("Key: ");
            sKey = input.nextLine();
        } while (map.containsKey(sKey));

        System.out.println("Value: ");
        String sValue = input.nextLine();
        int iValue = Integer.parseInt(sValue);
        map.put(sKey, iValue);
    }
 }


问:
Unable to detect Zebra DS457 scanner through scanner SDK
I am developing a windows forms application, for Zebra DS457 scanner using its SDK for Windows in C#. The api calls execute with no error or exception but unable to detect a scanner which connected to the PC using serial to USB moxa switch. Thanks in advance for the help </p>

答:
In many cases, it is possible that the scanner hardware is set to HID keyboard emulation mode.

It is suggested that the scanner must be in OPOS or SNAPI communication mode around 1:58 of the video tutorial.
https://www.youtube.com/watch?v=rN5M6ATO708&list=PLrcZVTwQp0lesloWgP3gReIZZqst5Hb-z&index=8

You should be able to change the mode with a setting bar code etc.


问:
Convert short year format to full - jquery input mask
I have Jquery input mask date that has format mm/dd/yyyy. When I type 17 for a year I want to convert it to 2017 and that works good but I have the issue when I type 21 it converts to 201 not 2021.

You can here see example:
https://jsfiddle.net/u3em5bmr/1/

Body:
str = 'xx 22.07.03 yy';
str = str.replace(/(\d{2}.\d{2}).(\d{2})/g,'$1.20$2'); // $1='22.07' $2='03'
alert(str);


问:
JBOSS Application SSL Error: Alias name does not identify a key entry
I am trying to configure JBOSS application 6.0.1 using SSL with a certificate provided to me(By entrust).

I got three certificate(root,chain & server certificate) from Entrust in .CER format.

Next I created a keystore:

1.keytool -import -alias EntrustL1C -keystore EntrustL1C.mykeystore -trustcacerts -file L1Cchain.cer
Enter keystore password:
Re-enter new password:
Certificate was added to keystore

2.keytool -import -alias Root -keystore EntrustL1C.mykeystore -trustcacerts -file L1Croot.cer
Enter keystore password:

3.# keytool -import -alias myalias -keystore EntrustL1C.mykeystore -trustcacerts -file entrustcert.cer
Enter keystore password:
Certificate was added to keystore

I configured this in JBOSS's standalone.xml in the two SSL section:

Upon starting JBOSS application I got this error.

```<code>13:08:23,311 ERROR [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-3) Error initializing endpoint: java.io.IOException: Alias name test does not
identify a key entry
        at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:517) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.tomcat.util.net.jsse.JSSESocketFactory.init(JSSESocketFactory.java:452) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:168) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.tomcat.util.net.JIoEndpoint.init(JIoEndpoint.java:978) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.coyote.http11.Http11Protocol.init(Http11Protocol.java:190) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.catalina.connector.Connector.init(Connector.java:1001) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:268) [jboss-as-web-7.1.3.Final-redhat-4.jar:7.1.3.Final-redhat-4]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_22]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_22]
        at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_22]

13:08:23,320 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.web.connector.https:

org.jboss.msc.service.StartException in service jboss.web.connector.https: JBAS018007: Error starting web connector
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:272)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_22]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_22]
        at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_22]
Caused by: LifecycleException:  Protocol handler initialization failed: java.io.IOException: Alias name test does not identify a key entry
        at org.apache.catalina.connector.Connector.init(Connector.java:1003)
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:268)
    ... 5 more
</code>```

I then did a keytool -list -v -keystore EntrustL1C.mykeystore, and noticed that the alias is in all are there in lowercase.

I am wondering if I am making some fundamental error in configuring JBOOS application, or should this thing be working and I'm just making a stupid careless mistake?

Any guidance would be greatly appreciated.

答: Somewhere in your JBoss configuration you are referring to an alias with the name "test". Since your keystore does not have such alias, JBoss complains. Doing a global search for "test" (try also with included quotes) across your JBoss configuration files (XML, properties, etc. ...) may help pinpoint the problem.</p>

Body:
I am trying to configure JBOSS application 6.0.1 using SSL with a certificate provided to me(By entrust).

I got three certificate(root,chain & server certificate) from Entrust in .CER format.

Next I created a keystore:

1.keytool -import -alias EntrustL1C -keystore EntrustL1C.mykeystore -trustcacerts -file L1Cchain.cer
Enter keystore password:
Re-enter new password:
Certificate was added to keystore

2.keytool -import -alias Root -keystore EntrustL1C.mykeystore -trustcacerts -file L1Croot.cer
Enter keystore password:

3.# keytool -import -alias myalias -keystore EntrustL1C.mykeystore -trustcacerts -file entrustcert.cer
Enter keystore password:
Certificate was added to keystore

I configured this in JBOSS's standalone.xml in the two SSL section:

Upon starting JBOSS application I got this error.

13:08:23,311 ERROR [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-3) Error initializing endpoint: java.io.IOException: Alias name test does not
identify a key entry
        at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:517) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.tomcat.util.net.jsse.JSSESocketFactory.init(JSSESocketFactory.java:452) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:168) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.tomcat.util.net.JIoEndpoint.init(JIoEndpoint.java:978) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.coyote.http11.Http11Protocol.init(Http11Protocol.java:190) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.apache.catalina.connector.Connector.init(Connector.java:1001) [jbossweb-7.0.17.Final-redhat-1.jar:]
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:268) [jboss-as-web-7.1.3.Final-redhat-4.jar:7.1.3.Final-redhat-4]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_22]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_22]
        at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_22]

13:08:23,320 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.web.connector.https:

org.jboss.msc.service.StartException in service jboss.web.connector.https: JBAS018007: Error starting web connector
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:272)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA-redhat-2.jar:1.0.2.GA-redhat-2]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_22]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_22]
        at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_22]
Caused by: LifecycleException:  Protocol handler initialization failed: java.io.IOException: Alias name test does not identify a key entry
        at org.apache.catalina.connector.Connector.init(Connector.java:1003)
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:268)
    ... 5 more

I then did a keytool -list -v -keystore EntrustL1C.mykeystore, and noticed that the alias is in all are there in lowercase.

I am wondering if I am making some fundamental error in configuring JBOOS application, or should this thing be working and I'm just making a stupid careless mistake?

Any guidance would be greatly appreciated.


问:
Hibernate Search with Lucene Query for first and last name together
I have attempted this with phrase, wildcard and keyword queries but nothing really works perfectly.

```<code>  ...
    @Field(name = "firstLastName", index = org.hibernate.search.annotations.Index.YES, analyze = Analyze.NO, store = Store.NO)
    public String getFirstLastName() {
        return this.firstLastName;
    }
...
</code>```

Now I want to query this field and return the correct results if a user types John Smith, Smith John or Smith Jo* or John Smi*....

```<code>junction = junction.should(qb.keyword().wildcard().onField("firstLastName")
                            .matching("John Smith*").createQuery());
</code>```

If I search for just Smith or John given a keyword query, I get a hit. I am not analyzing the field as I didn't think I needed to but I tried it both ways with no success...

答:
Several issues here:

You need to use an analyzer, be it only to split the strings on whitespaces. Define an analyzer and assign it to your field.

You can't use wildcard queries if you want the strings to be analyzed: wildcard queries are not analyzed. You should use an EdgeNGramFilter instead.

This answer to a very similar question will probably help: Hibernate Search: How to use wildcards correctly?

Body:
I have attempted this with phrase, wildcard and keyword queries but nothing really works perfectly.

  ...
    @Field(name = "firstLastName", index = org.hibernate.search.annotations.Index.YES, analyze = Analyze.NO, store = Store.NO)
    public String getFirstLastName() {
        return this.firstLastName;
    }
...

Now I want to query this field and return the correct results if a user types John Smith, Smith John or Smith Jo* or John Smi*....

junction = junction.should(qb.keyword().wildcard().onField("firstLastName")
                            .matching("John Smith*").createQuery());

If I search for just Smith or John given a keyword query, I get a hit. I am not analyzing the field as I didn't think I needed to but I tried it both ways with no success...


问:
import pyodbc not working in eclipse
I am new to python..
I am not able to import pyodbc
I am getting an error in eclipse (just for this import)
i install pyodbc

```<code>C:\Users\app_rahavm>pip install pyodbc
Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages
</code>```

python interpeter is also updated with the path:

and still i am getting

```<code>Unresolved import: pyodbc
</code>```

when i write this:

```<code>import pyodbc
</code>```

i also see this package under packages

click here to see

any ideas?

another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside
see image here see content of lib here

答:
Delete my old interpreter in Preferences > PyDev > Interpreters, and creating a new interpreter called "python" which had the correct paths. After quitting and reopening eclipse, pydev found all my modules.

See

Pydev say, "Unresolved import" error

Title: import pyodbc not working in eclipse

Body:
I am new to python..
I am not able to import pyodbc
I am getting an error in eclipse (just for this import)
i install pyodbc

C:\Users\app_rahavm>pip install pyodbc
Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages

python interpeter is also updated with the path:

and still i am getting

Unresolved import: pyodbc

when i write this:

import pyodbc

i also see this package under packages

click here to see

any ideas?

another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside
see image here see content of lib here


问:
Maven: unable to install 3rd party jar
trying to install a 3rd party jar into my repository (alfresco-repository.jar). I'm using the following command:

```<code>mvn install:install-file -DgroupId=alfresco -DartifactId=alfresco -Dversion=3.1 -Dpackaging=jar "-Dfile=C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar" -DgeneratePom=true -e
</code>```

and I'm getting the following exception (-e used for more information):

```<code>[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'install'.
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Invalid task '.1': you must specify a valid lifecycle phase, or a goal in
 the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.BuildFailureException: Invalid task '.1': you must specify a va
lid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:plugin
ArtifactId:pluginVersion:goal
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getMojoDescriptor
(DefaultLifecycleExecutor.java:1830)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.segmentTaskListBy
AggregationNeeds(DefaultLifecycleExecutor.java:462)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLi
fecycleExecutor.java:175)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
        at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:6
0)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
        at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
        at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)

        at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
</code>```

答:
The problem is that you are using double quotes (") in the wrong places and sometimes not at all. You should be using double quotes around all of your values of parameters. For instance...

```<code>"-Dfile=C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar"
</code>```

...should be...

```<code>-Dfile="C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar"
</code>```

...and...

```<code>-Dversion=3.1
</code>```

...should be...

```<code>-Dversion="3.1"
</code>```

Different command lines of different OS's will handle the first versions inconsistently but if you surround only the value of each parameters with double quotes, you will get the desired behavior every time. Your entire command should look like this...

```<code>mvn install:install-file -DgroupId="alfresco" -DartifactId="alfresco" -Dversion="3.1" -Dpackaging="jar" -Dfile="C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar" -DgeneratePom="true" -e
</code>```

I'll admit it is not necessary on all of them but it is a good habit to have.

Title: Maven: unable to install 3rd party jar

Body:
trying to install a 3rd party jar into my repository (alfresco-repository.jar). I'm using the following command:

mvn install:install-file -DgroupId=alfresco -DartifactId=alfresco -Dversion=3.1 -Dpackaging=jar "-Dfile=C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar" -DgeneratePom=true -e

and I'm getting the following exception (-e used for more information):

[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'install'.
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Invalid task '.1': you must specify a valid lifecycle phase, or a goal in
 the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.BuildFailureException: Invalid task '.1': you must specify a va
lid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:plugin
ArtifactId:pluginVersion:goal
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getMojoDescriptor
(DefaultLifecycleExecutor.java:1830)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.segmentTaskListBy
AggregationNeeds(DefaultLifecycleExecutor.java:462)
        at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLi
fecycleExecutor.java:175)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
        at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:6
0)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
        at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
        at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)

        at org.codehaus.classworlds.Launcher.main(Launcher.java:375)

Body:
The problem is that you are using double quotes (") in the wrong places and sometimes not at all. You should be using double quotes around all of your values of parameters. For instance...

"-Dfile=C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar"

...should be...

-Dfile="C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar"

...and...

-Dversion=3.1

...should be...

-Dversion="3.1"

Different command lines of different OS's will handle the first versions inconsistently but if you surround only the value of each parameters with double quotes, you will get the desired behavior every time. Your entire command should look like this...

mvn install:install-file -DgroupId="alfresco" -DartifactId="alfresco" -Dversion="3.1" -Dpackaging="jar" -Dfile="C:/Users/xxx/Development/WIP/Alfresco/common/jars/alfresco/3.1/lib/alfresco-repository-3.1.jar" -DgeneratePom="true" -e

I'll admit it is not necessary on all of them but it is a good habit to have.


问:
C# check if list contains a certain string (on object.Titel) but ignores the casing of the letters?
Here's my code :

```<code>string zoekstring = Request.QueryString["txt"].Replace("'", "''");
    List<IntranetDocument> result = documenten.FindAll(x => x.Titel.Contains(zoekstring));

    if(result.Any())
    {
        foreach (IntranetDocument doc in result)
        {
            ListItem li = new ListItem();
            li.Text = doc.Titel;
            li.Value = doc.Locatie;
            ListFiles.Items.Add(li);
        }
    }
    else
    {
        ListItem li = new ListItem();
        li.Text = Res.Get("Algemeen_NotFound");
        li.Value = "#";
        ListFiles.Items.Add(li);
    }
</code>```

This will do a FindAll on all my documents (that I've previously loaded in via an SQL query) and checks on the document Titel. So if I search for "report" it will give me back all documents where Titel contains "report" for example for quarterly finance reports.

Now I'd also want documents returned where Titel contains "Report" with an uppercase R. Or even "rePort" or "ReporT" or "REPORT"... you get the idea. i want the FindAll ... Titel.Contains(zoekstring) to not only return the document where titel contains LITERALLY "zoekstring" but also a potential uppercase/lowercase...

How can I achieve this?

答:
Use  String.IndexOf with StringComparison.CurrentCultureIgnoreCase instead of Contains:

```<code>List<IntranetDocument> result = documenten.FindAll(x => x.Titel.IndexOf(zoekstring, StringComparison.CurrentCultureIgnoreCase) >= 0);
</code>```

Body:
Here's my code :

string zoekstring = Request.QueryString["txt"].Replace("'", "''");
    List<IntranetDocument> result = documenten.FindAll(x => x.Titel.Contains(zoekstring));

    if(result.Any())
    {
        foreach (IntranetDocument doc in result)
        {
            ListItem li = new ListItem();
            li.Text = doc.Titel;
            li.Value = doc.Locatie;
            ListFiles.Items.Add(li);
        }
    }
    else
    {
        ListItem li = new ListItem();
        li.Text = Res.Get("Algemeen_NotFound");
        li.Value = "#";
        ListFiles.Items.Add(li);
    }

This will do a FindAll on all my documents (that I've previously loaded in via an SQL query) and checks on the document Titel. So if I search for "report" it will give me back all documents where Titel contains "report" for example for quarterly finance reports.

Now I'd also want documents returned where Titel contains "Report" with an uppercase R. Or even "rePort" or "ReporT" or "REPORT"... you get the idea. i want the FindAll ... Titel.Contains(zoekstring) to not only return the document where titel contains LITERALLY "zoekstring" but also a potential uppercase/lowercase...

How can I achieve this?

Body:
Use  String.IndexOf with StringComparison.CurrentCultureIgnoreCase instead of Contains:

List<IntranetDocument> result = documenten.FindAll(x => x.Titel.IndexOf(zoekstring, StringComparison.CurrentCultureIgnoreCase) >= 0);


问:
How to use an array element value if the array name is extracted later (in Python)?
eg:

CASE 1:

```<code>arr1 = [1, 2, 3, 4, 5]

print('arr1[0]')
</code>```

Output is:

1

CASE 2: (in the same program, after finding out name of array)

```<code>new = 'arr1'

print('new[0]')
</code>```

Output is :

a

In case 1, we are accessing list elements but in case 2, we are accessing string elements.
The problem is that I want that the computer should understand that this is the same arr1 defined in Case 1.

答:
Here is your solution:

```<code>arr1 = [1, 2, 3, 4, 5]

print('arr1[0]')

new = 'arr1'

print(eval(new)[0])
</code>```

This will first evaluate value of the variable new and then get the index element.

Body:
eg:

CASE 1:

arr1 = [1, 2, 3, 4, 5]

print('arr1[0]')

Output is:

1

CASE 2: (in the same program, after finding out name of array)

new = 'arr1'

print('new[0]')

Output is :

a

In case 1, we are accessing list elements but in case 2, we are accessing string elements.
The problem is that I want that the computer should understand that this is the same arr1 defined in Case 1.

Body:
Here is your solution:

arr1 = [1, 2, 3, 4, 5]

print('arr1[0]')

new = 'arr1'

print(eval(new)[0])

This will first evaluate value of the variable new and then get the index element.


问:
Drawing a grid using SVG markup
I'm seeking to draw a grid onto which i will be adding a number of simple rectangles, again using SVG. The grid should fit on a single page when viewed in a browser. Suspect i'm missing something very simple but do i code the SVG (viewport and grid) for this outcome; namely a grid?
I've read advice to specify a viewbox that defines the internal coordinate system of the document's canvas; also that it's possible to set height and width attributes as percentages (?). Ideally final result (ultimately a map) is to have gridlines.  </p>

答:
Use a pattern on a fully wide and high rectangle.

<svg width="800" height="600">
<defs>
 <pattern id="tenthGrid" width="10" height="10" patternUnits="userSpaceOnUse">
  <path d="M 10 0 L 0 0 0 10" fill="none" stroke="silver" stroke-width="0.5"/>
 </pattern>
 <pattern id="grid" width="100" height="100" patternUnits="userSpaceOnUse">
  <rect width="100" height="100" fill="url(#tenthGrid)"/>
  <path d="M 100 0 L 0 0 0 100" fill="none" stroke="gray" stroke-width="1"/>
 </pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)"/>
</svg>```

Title: Drawing a grid using SVG markup


问:
How can I output to the user additional information associated with the greatest value in an array?
I'm trying to get my code to output to the user the most popular sauce sold (numbers sold is based on user input), the sauce's name and its price. I can get it to display the greatest value but I cannot figure out how to also output the name and price in the same writeline. Here's what I have so far:</p>

```<code>class MainClass
{
    public static void Main (string[] args)
    {
        string[] names;
        names = new string[5];

        names [0] = "Eastern Carolina";
        names [1] = "Western Carolina";
        names [2] = "Kansas City";
        names [3] = "SC Mustard";
        names [4] = "Texas";

        int[] quantity;
        quantity = new int[5];

        double[] prices;
        prices = new double[5];

        for(int i=0; i < 5; i++)
        {
            Console.Write ("Enter how many bottles of " + names[i] + " sold: ");
            quantity [i] = Convert.ToInt32(Console.ReadLine ());

            Console.Write ("Enter the price of " + names[i] + ": ");
            prices [i] = Convert.ToDouble (Console.ReadLine ());

        }

        for(int i=0; i < 5; i++)
        {
            Console.WriteLine (names[i] +  " sauce $" + prices[i] + ", bottles sold: " + quantity [i]);
        }

        List<string> myList = new List<string> ();
        for(int i=0; i < 5; i++)
            myList.Add (names[i] + " " + prices[i] + " " + quantity[i]);

        foreach (string name in myList)
            Console.WriteLine (name);

        if (quantity.Length > 0)
        {
            int large = quantity[0];
            for (int i = 0; i < quantity.Length; i++)
            {
                if (large < quantity[i])
                {
                    large = quantity[i];
                    quantity[i] = large;
                }
            }
            Console.WriteLine("The most bottles sold is {0}", large);
        }
</code>```

答:
Since the common attribute between you arrays is the index you should "save" that in your search.
So instead of

```<code>int large = quantity[0];
</code>```

write

```<code>int large = 0;
</code>```

and search by the index like this

```<code>if (quantity[large] < quantity[i])
{
    large = i;
}
</code>```

I have no idea why you would set the quantity to large again, you don't need to do that. Afterwards you can access all the other arrays with array[large].
You should consider using a class "Sauce" with attributes name, price and quatity instead of three arrays to keep your code structured.

Body:
I'm trying to get my code to output to the user the most popular sauce sold (numbers sold is based on user input), the sauce's name and its price. I can get it to display the greatest value but I cannot figure out how to also output the name and price in the same writeline. Here's what I have so far:

class MainClass
{
    public static void Main (string[] args)
    {
        string[] names;
        names = new string[5];

        names [0] = "Eastern Carolina";
        names [1] = "Western Carolina";
        names [2] = "Kansas City";
        names [3] = "SC Mustard";
        names [4] = "Texas";

        int[] quantity;
        quantity = new int[5];

        double[] prices;
        prices = new double[5];

        for(int i=0; i < 5; i++)
        {
            Console.Write ("Enter how many bottles of " + names[i] + " sold: ");
            quantity [i] = Convert.ToInt32(Console.ReadLine ());

            Console.Write ("Enter the price of " + names[i] + ": ");
            prices [i] = Convert.ToDouble (Console.ReadLine ());

        }

        for(int i=0; i < 5; i++)
        {
            Console.WriteLine (names[i] +  " sauce $" + prices[i] + ", bottles sold: " + quantity [i]);
        }

        List<string> myList = new List<string> ();
        for(int i=0; i < 5; i++)
            myList.Add (names[i] + " " + prices[i] + " " + quantity[i]);

        foreach (string name in myList)
            Console.WriteLine (name);

        if (quantity.Length > 0)
        {
            int large = quantity[0];
            for (int i = 0; i < quantity.Length; i++)
            {
                if (large < quantity[i])
                {
                    large = quantity[i];
                    quantity[i] = large;
                }
            }
            Console.WriteLine("The most bottles sold is {0}", large);
        }

Body:
Since the common attribute between you arrays is the index you should "save" that in your search.
So instead of

int large = quantity[0];

write

int large = 0;

and search by the index like this

if (quantity[large] < quantity[i])
{
    large = i;
}

I have no idea why you would set the quantity to large again, you don't need to do that. Afterwards you can access all the other arrays with array[large].
You should consider using a class "Sauce" with attributes name, price and quatity instead of three arrays to keep your code structured.


问:
Best way to load distant data
I'm currently developping an iPhone app and need your opinion.

First, I am developping it for a Football (soccer) Club. It contains many tabs (at least these ones) :

News (Where I am displaying last news posted, obviously)

Shop (Where the user can buy stadium seats, and maybe various goodies)

Don't know yet exactly (But it will be related to Facebook/Twitter or stuff like that)

For every of theses tabs, I need to download XML data (using initWithContentOfURL). Right. But, that's where my problem is. Should I :

Load every needed xml pages at application start-up, and display a nice loading screen ?

Load every needed xml pages at the exact instant the user needs it in the application ?

In the first case, I get a slower application startup, but then, a faster navigation between tabs.

In the second case, my application starts relatively faster (still needs to load News XML, that's the welcome tab), but switching between tabs won't be as fluent as the first case (only the first time the tab is opened, of course).

Any advice?

答:
Load only what you need when you need it.

Furthermore, I wouldn't use initWithContentsOfUrl. It's a synchronous call, and it will lock your app. Instead, use an NSURLConnection to get the data asynchronously.

Title: Best way to load distant data


问:
Amazon Lex UnknownHostException: runtime.lex.eu-west-1.amazonaws.com
I wrote a simple Program to Test if I can talk to my Bot using the Amazon Lex Java API. When I run it, I get a
UnknownHostException: runtime.lex.eu-west-1.amazonaws.com

```<code>> Exception in thread "main" com.amazonaws.SdkClientException: Unable to execute HTTP request: runtime.lex.eu-west-1.amazonaws.com
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleRetryableException(AmazonHttpClient.java:1114)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1064)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.doInvoke(AmazonLexRuntimeClient.java:531)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.invoke(AmazonLexRuntimeClient.java:507)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.executePostText(AmazonLexRuntimeClient.java:471)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.postText(AmazonLexRuntimeClient.java:447)
    at ChatBot.ChatbotMain.main(ChatbotMain.java:17)
Caused by: java.net.UnknownHostException: runtime.lex.eu-west-1.amazonaws.com
    at java.net.InetAddress.getAllByName0(InetAddress.java:1280)
    at java.net.InetAddress.getAllByName(InetAddress.java:1192)
    at java.net.InetAddress.getAllByName(InetAddress.java:1126)
    at com.amazonaws.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:27)
    at com.amazonaws.http.DelegatingDnsResolver.resolve(DelegatingDnsResolver.java:38)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:111)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
    at com.amazonaws.http.conn.$Proxy8.connect(Unknown Source)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1236)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    ... 11 more
</code>```

Does anybody now how to solve this?
Is it possible that I can't send the HTTP-Request out of my Companys Network?

Heres the Code:

```<code>package ChatBot;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.lexruntime.AmazonLexRuntime;
import com.amazonaws.services.lexruntime.AmazonLexRuntimeClientBuilder;
import com.amazonaws.services.lexruntime.model.PostTextRequest;
import com.amazonaws.services.lexruntime.model.PostTextResult;

public class ChatbotMain {
    public static void main(String[]args){
        AmazonLexRuntime client = AmazonLexRuntimeClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
        PostTextRequest textRequest= new PostTextRequest();
        textRequest.setBotName("BookTrip");
        textRequest.setBotAlias("BookTripBot");
        textRequest.setUserId("christester");
        textRequest.setInputText("someText");
        PostTextResult result = client.postText(textRequest);
        System.out.println(result.getDialogState());
    }
}
</code>```

Thanks alot,

Chris

答: the problem was that my companys network doesn't allow to communicate with external webservices. I have to use a proxy or a Gateway to do so</p>

Body:
I wrote a simple Program to Test if I can talk to my Bot using the Amazon Lex Java API. When I run it, I get a
UnknownHostException: runtime.lex.eu-west-1.amazonaws.com

> Exception in thread "main" com.amazonaws.SdkClientException: Unable to execute HTTP request: runtime.lex.eu-west-1.amazonaws.com
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleRetryableException(AmazonHttpClient.java:1114)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1064)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.doInvoke(AmazonLexRuntimeClient.java:531)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.invoke(AmazonLexRuntimeClient.java:507)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.executePostText(AmazonLexRuntimeClient.java:471)
    at com.amazonaws.services.lexruntime.AmazonLexRuntimeClient.postText(AmazonLexRuntimeClient.java:447)
    at ChatBot.ChatbotMain.main(ChatbotMain.java:17)
Caused by: java.net.UnknownHostException: runtime.lex.eu-west-1.amazonaws.com
    at java.net.InetAddress.getAllByName0(InetAddress.java:1280)
    at java.net.InetAddress.getAllByName(InetAddress.java:1192)
    at java.net.InetAddress.getAllByName(InetAddress.java:1126)
    at com.amazonaws.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:27)
    at com.amazonaws.http.DelegatingDnsResolver.resolve(DelegatingDnsResolver.java:38)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:111)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
    at com.amazonaws.http.conn.$Proxy8.connect(Unknown Source)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1236)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    ... 11 more

Does anybody now how to solve this?
Is it possible that I can't send the HTTP-Request out of my Companys Network?

Heres the Code:

package ChatBot;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.lexruntime.AmazonLexRuntime;
import com.amazonaws.services.lexruntime.AmazonLexRuntimeClientBuilder;
import com.amazonaws.services.lexruntime.model.PostTextRequest;
import com.amazonaws.services.lexruntime.model.PostTextResult;

public class ChatbotMain {
    public static void main(String[]args){
        AmazonLexRuntime client = AmazonLexRuntimeClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
        PostTextRequest textRequest= new PostTextRequest();
        textRequest.setBotName("BookTrip");
        textRequest.setBotAlias("BookTripBot");
        textRequest.setUserId("christester");
        textRequest.setInputText("someText");
        PostTextResult result = client.postText(textRequest);
        System.out.println(result.getDialogState());
    }
}

Thanks alot,

Chris


问:
Why use setters in java instead of constructors?
Setters serve only a single function of constructors in java i.e assigning value to instance variables. Why do we need them? Can you explain with an example?
I understand the question I asked was rudimentary and I am sorry for that. I am new to programming and as soon as I found stackoverflow, I asked this question which has been bugging me for quite a time. I tried deleting, but that was not allowed. </p>

答:
Because you can change the value later for the same instance. For example, let's assume a person with the following class:

```<code>public class Person {
  String firstName;
  String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}
</code>```

Imagine there is a woman named "Linda Croft" which is now single.

```<code>Person linda = new Person("Linda", "Croft");
</code>```

Then, after a couple of years, he marry a man named "John Wick". Then "Linda" want to change her name to his husband name after marriage. If we don't have a setter, we need to create another "Linda", which is obviously another person:

```<code>Person anotherLinda = new Person("Linda", "Wick");
</code>```

with the setter, we can update her name with:

```<code>linda.setLastName("Wick");
</code>```

Now Linda name is "Linda Wick".

Body:
Because you can change the value later for the same instance. For example, let's assume a person with the following class:

public class Person {
  String firstName;
  String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}

Imagine there is a woman named "Linda Croft" which is now single.

Person linda = new Person("Linda", "Croft");

Then, after a couple of years, he marry a man named "John Wick". Then "Linda" want to change her name to his husband name after marriage. If we don't have a setter, we need to create another "Linda", which is obviously another person:

Person anotherLinda = new Person("Linda", "Wick");

with the setter, we can update her name with:

linda.setLastName("Wick");

Now Linda name is "Linda Wick".


问:
Extract Formula From lm with Coefficients (R)
I have an lm object and want to get the formula extracted with coefficients. I know how to extract the formula without coefficients, and how to get the coefficients without the formula, but not how to get eg. y ~ 10 + 1.25b as opposed to y~b or a table of what intercept, b etc. equal

This is the code I'm working with currently:

```<code>a = c(1, 2, 5)
b = c(12, 15, 20)

model = lm(a~b)
summary(model)
formula = formula(model)
formula
coefficients(model)
</code>```

What I'd like to get from the above is y ~ -5.326 + .51b

Thanks

Edit: In my actual code I'm working with over 63 predictors and 18 different models, so I'd like something that can scale up without too much work.

答:
I figured out a versatile way of creating the model formula with coefficients using substitution. It's a lot more versatile than manually building a string with paste0.

e.g.

I have a model that already has the optimized coefficients:

```<code>> model
Nonlinear regression model
  model: players ~ pop * (decay^days_from_start) + ycept
   data: data
      pop     decay     ycept
6.896e+06 2.633e-01 4.300e+05
 residual sum-of-squares: 1.64e+08

Number of iterations to convergence: 12
Achieved convergence tolerance: 1.49e-08
</code>```

These were the coefficients:

```<code>> coef(model)
         pop        decay        ycept
6.896421e+06 2.632545e-01 4.300453e+05
</code>```

Putting it all together:

```<code>> newFormula = as.formula(substituteDirect(formula(model), as.list(coef(model))))
> newFormula
players ~ 6896421.4399627 * (0.263254460933212^days_from_start) + 430045.26142703
</code>```

Body:
I have an lm object and want to get the formula extracted with coefficients. I know how to extract the formula without coefficients, and how to get the coefficients without the formula, but not how to get eg. y ~ 10 + 1.25b as opposed to y~b or a table of what intercept, b etc. equal

This is the code I'm working with currently:

a = c(1, 2, 5)
b = c(12, 15, 20)

model = lm(a~b)
summary(model)
formula = formula(model)
formula
coefficients(model)

What I'd like to get from the above is y ~ -5.326 + .51b

Thanks

Edit: In my actual code I'm working with over 63 predictors and 18 different models, so I'd like something that can scale up without too much work.

Body:
I figured out a versatile way of creating the model formula with coefficients using substitution. It's a lot more versatile than manually building a string with paste0.

e.g.

I have a model that already has the optimized coefficients:

> model
Nonlinear regression model
  model: players ~ pop * (decay^days_from_start) + ycept
   data: data
      pop     decay     ycept
6.896e+06 2.633e-01 4.300e+05
 residual sum-of-squares: 1.64e+08

Number of iterations to convergence: 12
Achieved convergence tolerance: 1.49e-08

These were the coefficients:

> coef(model)
         pop        decay        ycept
6.896421e+06 2.632545e-01 4.300453e+05

Putting it all together:

> newFormula = as.formula(substituteDirect(formula(model), as.list(coef(model))))
> newFormula
players ~ 6896421.4399627 * (0.263254460933212^days_from_start) + 430045.26142703


问:
how to get the index of the end string in a list
```<code>for root, subdirs, files in os.walk(dir):
    for i in range(0, files.index(files[-1]) + 1):
</code>```

files.index(files[-1]) here is the end index of item in files, and I got it.

But I want to know is there a simple way to get it?
I know if I got the end item, say, like "d", after typing in files.index("d"), I would have gotten the index.

答:
You can find the last letter (starting from the last letter):

```<code>s = 'acbc'
print(s.find(s[-1], -1))
</code>```

gives you 3, which is the index of the last letter.
The same you can use for your case.

Body:
for root, subdirs, files in os.walk(dir):
    for i in range(0, files.index(files[-1]) + 1):

files.index(files[-1]) here is the end index of item in files, and I got it.

But I want to know is there a simple way to get it?
I know if I got the end item, say, like "d", after typing in files.index("d"), I would have gotten the index.

Body:
You can find the last letter (starting from the last letter):

s = 'acbc'
print(s.find(s[-1], -1))

gives you 3, which is the index of the last letter.
The same you can use for your case.


问:
Google Maps - Pass map id and marker longlat to a hidden input element
Goal: I have several maps on a same template. Everytime a map is clicked, I would like to add markers and pass their longlat and corresponding map id to hidden input elements.

Problem: Map id passed to input name onclick is undefined like below (it's supposed to be something like 'map'+int).

```<code><input value="(35.69906406361917, 139.81689870357513)" name="undefined" type="hidden">
</code>```

I checked Get marker id in google maps but the onclick functions is slightly different.

Code:

```<code>var maps = [];

for (i = 1; i <= 10; i++) {
    var myOptions = {
        #settings
    };

    maps[i] = new google.maps.Map(document.getElementById('map'+i), myOptions);

    var currentMap = maps[i];

    (function(currentMap) {
        currentMap.addListener('click', function(e) {
            var marker = new google.maps.Marker({
                position: e.latLng,
                map: currentMap
            });

            var data = document.createElement('input');
            data.name = currentMap.id;
            data.type = 'hidden';
            data.value = e.latLng;
            document.forms[0].appendChild(data);
        });
    })(currentMap);
}
</code>```

答:
Upon checking your code and analyzing what you are trying to achieve, I found out that there's a better way to implement it. Instead of creating a new hidden input on every click, let's just store the coordinates and mapId in an array. Btw, the reason you are having this undefined is because the id you are referencing is a non-existing property.

For example, you have 3 maps on your page, the ids are: map1, map2, and map3.

In your existing implementation, var map = []; is already an array. This is correct. We just need to add 2 more arrays: the marker array and the coords array.

```<code>var marker = [];
var coords = [];
</code>```

Now, let's first create a function currentMap() that accepts two arguments: mapObject and mapId. These two arguments are essential for adding an event and for storing mapIds into our coords array. The first argument, mapObject, is the one will be using the .addListener method. The idea is to add a marker, on every map click and store the acquired coordinates to the array of objects together with the mapId that is being supplied by the second argument. The array object properties: mapId, lat, and lng.

The currentMap() function and definition:

```<code>  function currentMap(mapObject, mapId) {
    mapObject.addListener('click', function(e){
        var marker = new google.maps.Marker({
            position: e.latLng,
            map: mapObject
        });
      coords.push({
        mapId: mapId,
        lat: e.latLng.lat(),
        lng: e.latLng.lng()
      });
      //console.log(coords);
    });
  }
</code>```

The array object:

```<code>{
 lat:-27.059125784374057
 lng:122.080078125
 mapId:"map1"
}
</code>```

On the other hand, the initMap() function, we can use the for loop that you already created. Everything seems fine in your current initMap() implementation, we just simply remove unnecessary lines which we will no longer needed. And also, inside the loop, call the currentMap() function we recently created and then supply the necessary arguments.

```<code>  function initMap() {
    var myLatLng = {lat: -25.363, lng: 131.044};
    for ( var i = 1; i <= 3; i++ ) {
      map[i] = new google.maps.Map(document.getElementById('map'+i), {
        zoom: 4,
        center: myLatLng
      });
      currentMap(map[i], 'map'+i);
    }
  }
</code>```

Whole code below:

      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map = [];
      var marker = [];
      var coords = [];
      function initMap() {
        var myLatLng = {lat: -25.363, lng: 131.044};
        for ( var i = 1; i <= 3; i++ ) {
          map[i] = new google.maps.Map(document.getElementById('map'+i), {
            zoom: 4,
            center: myLatLng
          });
          currentMap(map[i], 'map'+i);
        }
      }
      function currentMap(mapObject, mapId) {
        mapObject.addListener('click', function(e){
            var marker = new google.maps.Marker({
                position: e.latLng,
                map: mapObject
            });
          coords.push({
            mapId: mapId,
            lat: e.latLng.lat(),
            lng: e.latLng.lng()
          });
          //console.log(coords);
        });
      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      .map {
        height: 200px;
        padding:10px 0;
        display:block;
        margin:10px 0;
        width:100%;
        float:left;
        overflow:hidden;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }</code>```

    ```

And that's it! Your coordinates + mapId are stored in coords array.

Hope this helps and happy coding!

Body:
Goal: I have several maps on a same template. Everytime a map is clicked, I would like to add markers and pass their longlat and corresponding map id to hidden input elements.

Problem: Map id passed to input name onclick is undefined like below (it's supposed to be something like 'map'+int).

<input value="(35.69906406361917, 139.81689870357513)" name="undefined" type="hidden">

I checked Get marker id in google maps but the onclick functions is slightly different.

Code:

var maps = [];

for (i = 1; i <= 10; i++) {
    var myOptions = {
        #settings
    };

    maps[i] = new google.maps.Map(document.getElementById('map'+i), myOptions);

    var currentMap = maps[i];

    (function(currentMap) {
        currentMap.addListener('click', function(e) {
            var marker = new google.maps.Marker({
                position: e.latLng,
                map: currentMap
            });

            var data = document.createElement('input');
            data.name = currentMap.id;
            data.type = 'hidden';
            data.value = e.latLng;
            document.forms[0].appendChild(data);
        });
    })(currentMap);
}

Body:
Upon checking your code and analyzing what you are trying to achieve, I found out that there's a better way to implement it. Instead of creating a new hidden input on every click, let's just store the coordinates and mapId in an array. Btw, the reason you are having this undefined is because the id you are referencing is a non-existing property.

For example, you have 3 maps on your page, the ids are: map1, map2, and map3.

In your existing implementation, var map = []; is already an array. This is correct. We just need to add 2 more arrays: the marker array and the coords array.

var marker = [];
var coords = [];

Now, let's first create a function currentMap() that accepts two arguments: mapObject and mapId. These two arguments are essential for adding an event and for storing mapIds into our coords array. The first argument, mapObject, is the one will be using the .addListener method. The idea is to add a marker, on every map click and store the acquired coordinates to the array of objects together with the mapId that is being supplied by the second argument. The array object properties: mapId, lat, and lng.

The currentMap() function and definition:

  function currentMap(mapObject, mapId) {
    mapObject.addListener('click', function(e){
        var marker = new google.maps.Marker({
            position: e.latLng,
            map: mapObject
        });
      coords.push({
        mapId: mapId,
        lat: e.latLng.lat(),
        lng: e.latLng.lng()
      });
      //console.log(coords);
    });
  }

The array object:

{
 lat:-27.059125784374057
 lng:122.080078125
 mapId:"map1"
}

On the other hand, the initMap() function, we can use the for loop that you already created. Everything seems fine in your current initMap() implementation, we just simply remove unnecessary lines which we will no longer needed. And also, inside the loop, call the currentMap() function we recently created and then supply the necessary arguments.

  function initMap() {
    var myLatLng = {lat: -25.363, lng: 131.044};
    for ( var i = 1; i <= 3; i++ ) {
      map[i] = new google.maps.Map(document.getElementById('map'+i), {
        zoom: 4,
        center: myLatLng
      });
      currentMap(map[i], 'map'+i);
    }
  }

Whole code below:

      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map = [];
      var marker = [];
      var coords = [];
      function initMap() {
        var myLatLng = {lat: -25.363, lng: 131.044};
        for ( var i = 1; i <= 3; i++ ) {
          map[i] = new google.maps.Map(document.getElementById('map'+i), {
            zoom: 4,
            center: myLatLng
          });
          currentMap(map[i], 'map'+i);
        }
      }
      function currentMap(mapObject, mapId) {
        mapObject.addListener('click', function(e){
            var marker = new google.maps.Marker({
                position: e.latLng,
                map: mapObject
            });
          coords.push({
            mapId: mapId,
            lat: e.latLng.lat(),
            lng: e.latLng.lng()
          });
          //console.log(coords);
        });
      }

      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      .map {
        height: 200px;
        padding:10px 0;
        display:block;
        margin:10px 0;
        width:100%;
        float:left;
        overflow:hidden;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

    <div id="map1" class="map"></div>
    <div id="map2" class="map"></div>
    <div id="map3" class="map"></div>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap">
    </script>

And that's it! Your coordinates + mapId are stored in coords array.

Hope this helps and happy coding!