问:
How to create android button bar?
I need to create a horizontal list of buttons without a separating space like this one

each button will contain a text and an icon I know about buttonbarlayout but it didn't work for me, please can someone help me, Thanks in advance

答:
There is BottomNavigationView element for this

in your layout:

```<code> <android.support.design.widget.BottomNavigationView
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/navigation"
 android:layout_width="match_parent"
 android:layout_height="56dp"
 android:layout_gravity="start"
 app:menu="@menu/my_navigation_items" />
</code>```

res/menu/my_navigation_items.xml:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_search"
          android:title="@string/menu_search"
          android:icon="@drawable/ic_search" />
    <item android:id="@+id/action_settings"
          android:title="@string/menu_settings"
          android:icon="@drawable/ic_add" />
    <item android:id="@+id/action_navigation"
          android:title="@string/menu_navigation"
          android:icon="@drawable/ic_action_navigation_menu" />
</menu>
</code>```

Title: How to create android button bar?

Body:
There is BottomNavigationView element for this

in your layout:

 <android.support.design.widget.BottomNavigationView
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/navigation"
 android:layout_width="match_parent"
 android:layout_height="56dp"
 android:layout_gravity="start"
 app:menu="@menu/my_navigation_items" />

res/menu/my_navigation_items.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_search"
          android:title="@string/menu_search"
          android:icon="@drawable/ic_search" />
    <item android:id="@+id/action_settings"
          android:title="@string/menu_settings"
          android:icon="@drawable/ic_add" />
    <item android:id="@+id/action_navigation"
          android:title="@string/menu_navigation"
          android:icon="@drawable/ic_action_navigation_menu" />
</menu>


来源: stackexchange

问:
java username and password input validation
I am trying to prompt the user to input his or her username and password when prompted. after they input I am trying to check it against a text file I have stored with my source code.

```<code>public static void getCreds()
{
    String userName;
    String userPass;

    Scanner credsInput = new Scanner(System.in);

    System.out.print("Please enter your username: ");
        userName = credsInput.nextLine();
    System.out.print("Please enter your password: ");
        userPass = credsInput.nextLine();

    boolean found = false;
    String tempUser;
    String tempPass;
    //String fileName = "credentials.txt";

    try
    {
        // Scanner scan = new Scanner(new BufferedReader(new FileReader("credentials.txt")))
        Scanner scan = new Scanner(new File("credentials.txt"));
        scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            tempUser = scan.next();
            tempPass = scan.next();

            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
            }

        }

        scan.close();
    }

    catch (Exception e)
    {
        System.out.println("invalid");
    }

}
</code>```

and this is the contents of the text file.

```<code>user1,pass1
bob,1234
jim,1234
</code>```

I don't believe that it is actually reading from the file but I may be wrong, any help is appreciated.

edit

I forgot to put my output. when I compile and run the code it asks for the username and output successfully and regardless if I put in a correct one or not, it throws the exception and displays

```<code>invalid
</code>```

edit #2

my first issue was that I wasn't used to storing text files in java properly. After I changed the text file to the proper place. I was able to change the useDelimiter line successfully

```<code>scan.useDelimiter(",|\n");
</code>```

now it succesfuly checks both the username and password and outputs

```<code>Success
</code>```

if the input is in the text file.

答:
I would recommend using hasNextLine() and nextLine() since you know the username and password pairs are on individual lines.</p>

```<code>    Scanner scan = new Scanner(new File("credentials.txt"));

    while (scan.hasNextLine() && !found)
    {
        String[] userNpwd = scan.nextLine().split(",");
        if(userNpwd.length() == 2)
        {
            tempUser = userNpwd[0];
            tempPass = userNpwd[1];
            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
             }
         }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to prompt the user to input his or her username and password when prompted. after they input I am trying to check it against a text file I have stored with my source code.

public static void getCreds()
{
    String userName;
    String userPass;

    Scanner credsInput = new Scanner(System.in);

    System.out.print("Please enter your username: ");
        userName = credsInput.nextLine();
    System.out.print("Please enter your password: ");
        userPass = credsInput.nextLine();

    boolean found = false;
    String tempUser;
    String tempPass;
    //String fileName = "credentials.txt";

    try
    {
        // Scanner scan = new Scanner(new BufferedReader(new FileReader("credentials.txt")))
        Scanner scan = new Scanner(new File("credentials.txt"));
        scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            tempUser = scan.next();
            tempPass = scan.next();

            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
            }

        }

        scan.close();
    }

    catch (Exception e)
    {
        System.out.println("invalid");
    }

}

and this is the contents of the text file.

user1,pass1
bob,1234
jim,1234

I don't believe that it is actually reading from the file but I may be wrong, any help is appreciated.

edit

I forgot to put my output. when I compile and run the code it asks for the username and output successfully and regardless if I put in a correct one or not, it throws the exception and displays

invalid

edit #2

my first issue was that I wasn't used to storing text files in java properly. After I changed the text file to the proper place. I was able to change the useDelimiter line successfully

scan.useDelimiter(",|\n");

now it succesfuly checks both the username and password and outputs

Success

if the input is in the text file.

Body:
I would recommend using hasNextLine() and nextLine() since you know the username and password pairs are on individual lines.

    Scanner scan = new Scanner(new File("credentials.txt"));

    while (scan.hasNextLine() && !found)
    {
        String[] userNpwd = scan.nextLine().split(",");
        if(userNpwd.length() == 2)
        {
            tempUser = userNpwd[0];
            tempPass = userNpwd[1];
            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
             }
         }
    }


问:
compiler does not allow me to edit the passed string
I looked around and I could not find a solution of my problems in other question. For some reason, then I get segmentation fault when I run my program and it seems to be because i am changing the give string. I tried passing a pointer to a char pointer and edit that, but to no avail.

what I get:

before: juanpablo
Segmentation fault (core dumped)

My code:

```<code>void rm_char(char* word, int pos){

   printf("before: %s\n", word);

   int len = strlen(word);

   int i;

   i = pos;

   while(word[i+1] != '\0'){

     word[i] = word[i+1];

     i++;
   }

   word[i] = '\0';

   printf("after: %s\n", word);
}

int main(void){

   rm_char("juanpablo", 2);

}
</code>```

答:
From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

To escape the error you could call the function like

```<code>char s[] = "juanpablo";

rm_char( s, 2 );
</code>```

Take into account that it is better to use type size_t instead of the type int for the second parameter and the variable len declared like

```<code>int len = strlen(word);
</code>```

is not used in the function.

The function should be declared like

```<code>char * rm_char(char* word, size_t pos);
</code>```

Here is a demonstrative program

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

char * rm_char(char *word, size_t pos)
{
    size_t n = strlen( word );

    if ( pos < n )
    {
        //memmove( word + pos, word + pos + 1, n - pos );
        do
        {
            word[pos] = word[pos+1];
        } while ( word[pos++] );
    }

    return word;
}

int main(void)
{
    char word[] = "juanpablo";

    puts( word );
    puts( rm_char( word, 2 ) );

    return 0;
}
</code>```

Its output is

```<code>juanpablo
junpablo
</code>```

Body:
I looked around and I could not find a solution of my problems in other question. For some reason, then I get segmentation fault when I run my program and it seems to be because i am changing the give string. I tried passing a pointer to a char pointer and edit that, but to no avail.

what I get:

before: juanpablo
Segmentation fault (core dumped)

My code:

void rm_char(char* word, int pos){

   printf("before: %s\n", word);

   int len = strlen(word);

   int i;

   i = pos;

   while(word[i+1] != '\0'){

     word[i] = word[i+1];

     i++;
   }

   word[i] = '\0';

   printf("after: %s\n", word);
}

int main(void){

   rm_char("juanpablo", 2);

}

Body:
From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

To escape the error you could call the function like

char s[] = "juanpablo";

rm_char( s, 2 );

Take into account that it is better to use type size_t instead of the type int for the second parameter and the variable len declared like

int len = strlen(word);

is not used in the function.

The function should be declared like

char * rm_char(char* word, size_t pos);

Here is a demonstrative program

#include <stdio.h>
#include <string.h>

char * rm_char(char *word, size_t pos)
{
    size_t n = strlen( word );

    if ( pos < n )
    {
        //memmove( word + pos, word + pos + 1, n - pos );
        do
        {
            word[pos] = word[pos+1];
        } while ( word[pos++] );
    }

    return word;
}

int main(void)
{
    char word[] = "juanpablo";

    puts( word );
    puts( rm_char( word, 2 ) );

    return 0;
}

Its output is

juanpablo
junpablo


问:
Cannot find R.layout.activity_main in main activity.java
I am developing an app, and have started working on main screen design but I am not able to test my app. When I want to test the app it suddenly stop all the time and error showing in catlog in the line

setContentView(R.layout.activity_main)

I have attached the screenshots in this question also.

答:
try that solution:

check that the import for R class is not import com.android.R;

and you should make it import yourpackagename.R, then recompile

if it works, your answer has already been replied here.


问:
How do i use a ng-repeat with different classes with each index
I am building a timeline and i want to invert every other index in the ng-repeat. I used ng-repeat-start and ng-repeat-end on two separate divs but all they do is just repeat the same array twice.

```<code><ul class="timeline">
    <li ng-repeat-start="t in vm.patientTimeLine">
        <div class="timeline-badge" style="background-color:#f9f9f9!important;"><i class="fa fa-phone hg-blue" aria-hidden="true"></i></div>
            <div class="card-block">
                 <h4 class="card-title"> {{t.FirstName}}'s reply was: <b ng-if="t.ReplyMessage !== null" class="stop">{{t.ReplyMessage}}</b></h4>
            </div>
     </li>

     <li class="timeline-inverted" ng-repeat-end>
        <div class="timeline-badge" style="background-color:#f9f9f9!important;"><i class="fa fa-phone hg-blue" aria-hidden="true"></i></div>
           <div class="card-block">
               <h4 class="card-title"> {{t.FirstName}}'s reply was: <b ng-if="t.ReplyMessage !== null" class="stop">{{t.ReplyMessage}}</b></h4>
           </div>
     </li>
</ul>
</code>```

I expect it to show the same list once but with the different css classes (timeline and timeline-inverted).

I thank you guys in advance.

答:
vicbyte's answer is correct, but I wanted to add a little more context.

ng-class can be used to conditionally apply classes with the items in ng-repeat.

```<code><li ng-repeat="i in items" ng-class="{ 'inverted': $even }"></li>
</code>```

Body:
I am building a timeline and i want to invert every other index in the ng-repeat. I used ng-repeat-start and ng-repeat-end on two separate divs but all they do is just repeat the same array twice.

 {{t.FirstName}}'s reply was: {{t.ReplyMessage}}

 {{t.FirstName}}'s reply was: {{t.ReplyMessage}}

I expect it to show the same list once but with the different css classes (timeline and timeline-inverted).

I thank you guys in advance.

Body:
vicbyte's answer is correct, but I wanted to add a little more context.

ng-class can be used to conditionally apply classes with the items in ng-repeat.

<li ng-repeat="i in items" ng-class="{ 'inverted': $even }"></li>


问:
How does eth-lighwallet store its saved passwords
I am interested in how eth-lightwallet stores user passwords to generate keys if they are for example pre deterministic where you don't need to store them somewhere or if they are encrypted and stored in some kind of location</p>

答: When you create an eth-lightwallet you have an instance that you can use. the library doesn't handle longterm storage of wallets. you have to use a storage library storj.js or serialize the wallet and make users download it as a JSON-file and upload it later.


问:
Configure message on Location Service iOS system popup
My app just been rejected because they found the location service authorization system popup was missing its description message.

But I do have configured the right variable in info.plist file:

```<code><key>NSLocationWhenInUseUsageDescription</key>
<string>Nous avons besoin de votre position GPS pour vous situer sur la carte.</string>
</code>```

(it's a french app)

Indeed, here's a screenshot of the popup the first time I launch the app:

But here is the screenshot the reviewer did take:

The second popup happen when you turned off the location service globally. To reproduce : accept the permission, go to settings, then turn off the location service, restart the app.

I cannot find a way to configure a message in this second popup. I even wonder if it is possible. Is there a way to do so, is it an error from the reviewer?!

Thank a lot.

答:
Ok. After trying to contact the Apple team with no constructive answer, I ended up by creating my own screen saying Location Services was recommended to be activated while using the app. Of course, the screen pops up if the app detects disabled location services, by checking CLLocationManager.locationServicesEnabled() method.

With this modification, the app did pass the validation process.

Body:
My app just been rejected because they found the location service authorization system popup was missing its description message.

But I do have configured the right variable in info.plist file:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Nous avons besoin de votre position GPS pour vous situer sur la carte.</string>

(it's a french app)

Indeed, here's a screenshot of the popup the first time I launch the app:

But here is the screenshot the reviewer did take:

The second popup happen when you turned off the location service globally. To reproduce : accept the permission, go to settings, then turn off the location service, restart the app.

I cannot find a way to configure a message in this second popup. I even wonder if it is possible. Is there a way to do so, is it an error from the reviewer?!

Thank a lot.


问:
Extract user information from the build
Jenkins ver. 2.73.3

I have a sample build task that is triggered by a commit to a Github repository. This is how the build information looks:

We need to write this username to a separate file and store it in a particular location. How can I achieve it?

**********Edit-1**********
Added a build step that executes a shell command to write the variable GIT_COMMITTER_NAME to a file. This fails(empty file) but if I write, say JENKINS_URL, it is written to the file:

答: Instead of echo $variable name execute env in shell, it will give you all environment variables at the time of execution and then you can pick the correct variable. (From Gitlab to Jenkins its $gitlabUserName)

Title: Extract user information from the build


问:
Preserve Line Breaks During Sort
This isn't necessarily PHP-specific, although I'm using PHP.  I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

```<code>Cookie

Apple

Banana
</code>```

I want to sort() these terms and display them after page submit, so that the results look like:

```<code>Apple

Banana

Cookie
</code>```

and not like

```<code>Apple
Banana
Cookie
</code>```

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear.  The list in the textarea is entered by a user so it may or may not already contain extra newlines.

答:
You can accomplish this by first using PHP's built in explode() function to get an array out of your string in your text area, using the 2 newline characters between the list items (one to move to new line from the line where there is actual text, and one for the blank line after) as the delimiter to explode on. Sort that array and then reconstruct your string out of it, manually adding back the new lines.

The function below demonstrates how this is achieved and MAY be DIRECTLY applicable to your needs, else guide you in the right direction:

```<code>function sort_list_with_line_breaks($list_string){

  $return_list = '';

  // Break the string on newline followed by blank line into array
  $list_array = explode("\n\n", $list_string);

  // Apply your sorting
  sort($list_array);

  // Reconstruct string
  $count = 0;
  foreach($list_array as $string){
      if($count == count($list_array)){ break; }
      if($count != 0){ $return_list .= "\n\n"; }
      $return_list .= $string;
      $count++;
  }

  return $return_list;
}
</code>```

Title: Preserve Line Breaks During Sort

Body:
This isn't necessarily PHP-specific, although I'm using PHP.  I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

Cookie

Apple

Banana

I want to sort() these terms and display them after page submit, so that the results look like:

Apple

Banana

Cookie

and not like

Apple
Banana
Cookie

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear.  The list in the textarea is entered by a user so it may or may not already contain extra newlines.

Body:
You can accomplish this by first using PHP's built in explode() function to get an array out of your string in your text area, using the 2 newline characters between the list items (one to move to new line from the line where there is actual text, and one for the blank line after) as the delimiter to explode on. Sort that array and then reconstruct your string out of it, manually adding back the new lines.

The function below demonstrates how this is achieved and MAY be DIRECTLY applicable to your needs, else guide you in the right direction:

function sort_list_with_line_breaks($list_string){

  $return_list = '';

  // Break the string on newline followed by blank line into array
  $list_array = explode("\n\n", $list_string);

  // Apply your sorting
  sort($list_array);

  // Reconstruct string
  $count = 0;
  foreach($list_array as $string){
      if($count == count($list_array)){ break; }
      if($count != 0){ $return_list .= "\n\n"; }
      $return_list .= $string;
      $count++;
  }

  return $return_list;
}


问:
Why does an HTTP header sent to my Smart Home webhook indicate API version v1, when I am using v2?
Our project was created after May 2017, therefore we believe it is using the v2 Google Assistant API, in accordance with what the documentation says here.

However, the 'Google-Assistant-API-Version' header in HTTP requests sent to our webhook contains the value 'v1'.

```<code>Google-Assistant-API-Version: v1
</code>```

All the content is using camelCase, rather than snake_case, however, so it does appear to be using v2. As far as we can tell, we are also responding using the v2 format, and this works fine.

We also include the 'Google-Assistant-API-Version' header in our responses with the value 'v2'. For testing purposes we have both removed this header entirely and changed its value to 'v1'. In both cases, the skill continues to function normally.

I have also attempted to change my action package to include the 'fulfillmentApiVersion' field (as described here), but it doesn't appear to have any effect.

```<code>{
  "actions": [{
      "name": "actions.devices",
      "deviceControl": {},
      "fulfillment": {
        "conversationName": "automation"
      }
    }
  ],
  "conversations": {
    "automation": {
      "name": "automation",
      "url": "https://**************************",
      "fulfillmentApiVersion": 2
    }
  }
}
</code>```

While we are not experiencing any problems at this time, we wonder if this is a sign of some dormant error, and were wondering if anyone could offer some clarification?

答:
The Google Assistant API version may be incorrect, or it may be referring to the API version for Smart Home. The Smart Home APIs launched publicly around May and use a different protocol for the data returned from the webhook.

If you are building a Smart Home application, please refer to the documentation above on how to write your webhook responses.

Body:
Our project was created after May 2017, therefore we believe it is using the v2 Google Assistant API, in accordance with what the documentation says here.

However, the 'Google-Assistant-API-Version' header in HTTP requests sent to our webhook contains the value 'v1'.

Google-Assistant-API-Version: v1

All the content is using camelCase, rather than snake_case, however, so it does appear to be using v2. As far as we can tell, we are also responding using the v2 format, and this works fine.

We also include the 'Google-Assistant-API-Version' header in our responses with the value 'v2'. For testing purposes we have both removed this header entirely and changed its value to 'v1'. In both cases, the skill continues to function normally.

I have also attempted to change my action package to include the 'fulfillmentApiVersion' field (as described here), but it doesn't appear to have any effect.

{
  "actions": [{
      "name": "actions.devices",
      "deviceControl": {},
      "fulfillment": {
        "conversationName": "automation"
      }
    }
  ],
  "conversations": {
    "automation": {
      "name": "automation",
      "url": "https://**************************",
      "fulfillmentApiVersion": 2
    }
  }
}

While we are not experiencing any problems at this time, we wonder if this is a sign of some dormant error, and were wondering if anyone could offer some clarification?


问:
Pentaho PDI get SQL SUM() with conditions
I'm using Pentaho PDI 7.1. I'm trying to convert data from Mysql to Mysql changing the structure of data.

I'm reading the source table (customers) and for each row I've to run another query to calculate the balance.
I was trying to use Database value lookup to accomplish it but maybe is not the best way.

I've to run a query like this to get the balance:

```<code>SELECT

 SUM(
        CASE WHEN direzione='ENTRATA' THEN -importo ELSE +importo  END
 )
   FROM Movimento WHERE contoFidelizzato_id = ?
</code>```

I should set the parameter taking it from the previous step. Some advice?

答:
The Database lookup value may be a good idea, especially if you are used to database reasoning, but it may result in many queries which may not be the most efficient.

A more PDI-ish style would be to make the query like:

```<code>SELECT contoFidelizzato_id
     , SUM(CASE WHEN direzione='ENTRATA' THEN -importo ELSE +importo END)
FROM Movimento
GROUP BY contoFidelizzato_id
</code>```

and use it as the info source of a Lookup Stream Step, like this:

An even more PDI-ish style would be to divert the source table (customer) in two flows : one in which you keep the source rows, and one that you group by contoFidelizzato_id. Of course, you need a formula, or a Javascript, or to put a formula in the SQL of the Table input to change the sign when needed.

Test to know which strategy is better in your case. You'll soon discover that the PDI is very good at handling large data.

Body:
I'm using Pentaho PDI 7.1. I'm trying to convert data from Mysql to Mysql changing the structure of data.

I'm reading the source table (customers) and for each row I've to run another query to calculate the balance.
I was trying to use Database value lookup to accomplish it but maybe is not the best way.

I've to run a query like this to get the balance:

SELECT

 SUM(
        CASE WHEN direzione='ENTRATA' THEN -importo ELSE +importo  END
 )
   FROM Movimento WHERE contoFidelizzato_id = ?

I should set the parameter taking it from the previous step. Some advice?

Body:
The Database lookup value may be a good idea, especially if you are used to database reasoning, but it may result in many queries which may not be the most efficient.

A more PDI-ish style would be to make the query like:

SELECT contoFidelizzato_id
     , SUM(CASE WHEN direzione='ENTRATA' THEN -importo ELSE +importo END)
FROM Movimento
GROUP BY contoFidelizzato_id

and use it as the info source of a Lookup Stream Step, like this:

An even more PDI-ish style would be to divert the source table (customer) in two flows : one in which you keep the source rows, and one that you group by contoFidelizzato_id. Of course, you need a formula, or a Javascript, or to put a formula in the SQL of the Table input to change the sign when needed.

Test to know which strategy is better in your case. You'll soon discover that the PDI is very good at handling large data.


问:
Parse XML with comma-separated entries into table in SQL Server
I have a XML file which is something like this

```<code>    declare @X XML
     Set @X  ='<A>
        <B>
        <C>161</C>
        <D>190</D>
        <E>43 ,44 ,48 ,49</E>
        </B>
    <B>
    <C>162</C>
    <D>190</D>
    <E>100</E>
    </B>
    </A>
'
</code>```

I want to parse it into a table:

```<code>    C         D       E
    161      190     43
    161      190     48
    161      190     49
    162      190     100
</code>```

I tried using

```<code>select
    x.r.value('(A)[1]', 'int') as C,
    x.r.value('(D)[1]', 'int') as D,
    x.r.value('(E)[1]', 'varchar(max)') as E
from
    @X.nodes('/A/B') as x(r)

DECLARE @xml as xml, @str as varchar(100), @delimiter as varchar(10)

SET @str = '43,48,49'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str,@delimiter ,'</X><X>')+'</X>') as xml)
        SELECT T.N.value('.', 'int') as value FROM @xml.nodes('X') as T(N)
</code>```

for separating the comma-separated column E into table.

But I am not able to combine both these in one query i.e. parse it into the table

答:
I modified my original answer to work with your modified question where you have multiple subordinate [B] nodes. I also took the liberty of modifying the data so that the result would be obvious (all the "1"s together, etc.). I do like the other answer here from Shnugo with the XML split string version. I haven't seen that in a while but I think it's cleaner so I used it.</p>

```<code>DECLARE @builder AS TABLE
  (
       [C]   [INT]
       , [D] [INT]
       , [E] [XML]
  );
DECLARE @X XML ='<A>
    <B>
        <C>161</C>
        <D>191</D>
        <E>41 ,51 ,61 ,71</E>
    </B>
    <B>
        <C>162</C>
        <D>192</D>
        <E>102</E>
    </B>
    <B>
        <C>163</C>
        <D>193</D>
        <E>43, 53, 63</E>
    </B>
</A>';

WITH [row_builder]
     AS (SELECT t.c.query(N'.') AS [b_row]
         FROM   @X.nodes(N'/A/B') AS [t]([c]))
   , [shredder]
     AS (SELECT [b_row].value(N'(./B/C/text())[1]', N'[INT]')             AS [C]
                , [b_row].value(N'(./B/D/text())[1]', N'[INT]')           AS [D]
                , [b_row].value(N'(./B/E/text())[1]', N'[NVARCHAR](MAX)') AS [E]
         FROM   [row_builder])
   , [splitter]
     AS (SELECT [C]
                , [D]
                , cast(( '<E>' + replace([E], N',', '</E><E>') + '</E>' ) AS XML) AS [E]
         FROM   [shredder])
SELECT [C]
       , [D]
       , [column].query(N'.').value(N'(/E/text())[1]', N'[INT]') AS [E]
FROM   [splitter] AS [entry]
       CROSS APPLY [E].[nodes]('/*') AS [table] ( [column] )
ORDER  BY [C]
          , [D]
          , [E];
</code>```

Body:
I have a XML file which is something like this

    declare @X XML
     Set @X  ='

        <C>161</C>
        <D>190</D>
        <E>43 ,44 ,48 ,49</E>

    <C>162</C>
    <D>190</D>
    <E>100</E>

'

I want to parse it into a table:

    C         D       E
    161      190     43
    161      190     48
    161      190     49
    162      190     100

I tried using

select
    x.r.value('(A)[1]', 'int') as C,
    x.r.value('(D)[1]', 'int') as D,
    x.r.value('(E)[1]', 'varchar(max)') as E
from
    @X.nodes('/A/B') as x(r)

DECLARE @xml as xml, @str as varchar(100), @delimiter as varchar(10)

SET @str = '43,48,49'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str,@delimiter ,'</X><X>')+'</X>') as xml)
        SELECT T.N.value('.', 'int') as value FROM @xml.nodes('X') as T(N)

for separating the comma-separated column E into table.

But I am not able to combine both these in one query i.e. parse it into the table

Body:
I modified my original answer to work with your modified question where you have multiple subordinate [B] nodes. I also took the liberty of modifying the data so that the result would be obvious (all the "1"s together, etc.). I do like the other answer here from Shnugo with the XML split string version. I haven't seen that in a while but I think it's cleaner so I used it.

DECLARE @builder AS TABLE
  (
       [C]   [INT]
       , [D] [INT]
       , [E] [XML]
  );
DECLARE @X XML ='<A>
    <B>
        <C>161</C>
        <D>191</D>
        <E>41 ,51 ,61 ,71</E>
    </B>
    <B>
        <C>162</C>
        <D>192</D>
        <E>102</E>
    </B>
    <B>
        <C>163</C>
        <D>193</D>
        <E>43, 53, 63</E>
    </B>
</A>';

WITH [row_builder]
     AS (SELECT t.c.query(N'.') AS [b_row]
         FROM   @X.nodes(N'/A/B') AS [t]([c]))
   , [shredder]
     AS (SELECT [b_row].value(N'(./B/C/text())[1]', N'[INT]')             AS [C]
                , [b_row].value(N'(./B/D/text())[1]', N'[INT]')           AS [D]
                , [b_row].value(N'(./B/E/text())[1]', N'[NVARCHAR](MAX)') AS [E]
         FROM   [row_builder])
   , [splitter]
     AS (SELECT [C]
                , [D]
                , cast(( '<E>' + replace([E], N',', '</E><E>') + '</E>' ) AS XML) AS [E]
         FROM   [shredder])
SELECT [C]
       , [D]
       , [column].query(N'.').value(N'(/E/text())[1]', N'[INT]') AS [E]
FROM   [splitter] AS [entry]
       CROSS APPLY [E].[nodes]('/*') AS [table] ( [column] )
ORDER  BY [C]
          , [D]
          , [E];


问:
Valgrind and global variables
I'm running valgrind to look for memory leaks. I have alloc'd two global variables in the main function; then, at the end of main I free both, but Valgrind keeps writing:

```<code>==18311== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A30C: main (application.c:730)
==18311==
==18311== 16 bytes in 1 blocks are definitely lost in loss record 2 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A31D: main (application.c:731)
</code>```

Leak summary:

```<code>==18311== LEAK SUMMARY:
==18311==    definitely lost: 32 bytes in 2 blocks
==18311==    indirectly lost: 0 bytes in 0 blocks
==18311==      possibly lost: 0 bytes in 0 blocks
==18311==    still reachable: 0 bytes in 0 blocks
==18311==         suppressed: 0 bytes in 0 blocks
</code>```

Why I can't free these two variables?

Edit

```<code>someList *something; *something_else;
</code>```

The struct used has two fields of type char * and a field someList *next.
Later there's a lot of code. A few threads are going to add/edit/delete objects using this two variables.

```<code>something -> object 1 -> ... -> object n
something_else -> object 1 -> ... -> object m
</code>```

Where -> means that something->next = object 1, and object k are all instances of someList *.

Near the end of the application, I freed every field of each object k element. Then, in the last part:

```<code>free(something);
free(something_else);
</code>```

It's possible that I forgot to free a field of an object. Can this cause the behavior I'm having here?

I hope it's clearer, now.

答:
Are you sure you're deallocating all of your variables? Valgrind says you're not.

Try and make your code slim and post it here, or run some more debugging.

ContentLicense: CC BY-SA 2.5

Title: Valgrind and global variables

Body:
I'm running valgrind to look for memory leaks. I have alloc'd two global variables in the main function; then, at the end of main I free both, but Valgrind keeps writing:

==18311== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A30C: main (application.c:730)
==18311==
==18311== 16 bytes in 1 blocks are definitely lost in loss record 2 of 2
==18311==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==18311==    by 0x804A31D: main (application.c:731)

Leak summary:

==18311== LEAK SUMMARY:
==18311==    definitely lost: 32 bytes in 2 blocks
==18311==    indirectly lost: 0 bytes in 0 blocks
==18311==      possibly lost: 0 bytes in 0 blocks
==18311==    still reachable: 0 bytes in 0 blocks
==18311==         suppressed: 0 bytes in 0 blocks

Why I can't free these two variables?

Edit

someList *something; *something_else;

The struct used has two fields of type char * and a field someList *next.
Later there's a lot of code. A few threads are going to add/edit/delete objects using this two variables.

something -> object 1 -> ... -> object n
something_else -> object 1 -> ... -> object m

Where -> means that something->next = object 1, and object k are all instances of someList *.

Near the end of the application, I freed every field of each object k element. Then, in the last part:

free(something);
free(something_else);

It's possible that I forgot to free a field of an object. Can this cause the behavior I'm having here?

I hope it's clearer, now.


问:
Add new column on csv file in python pandas
import pandas as np
from pandas import Series, DataFrame

```<code>dframe_final.to_csv('C:/Program Files/source/csv_data/2015/Merged files/jjj_all_merged.csv')
</code>```

I have this part of my code and I need to add a new column at the end of this csv file and name it "New_name".
And populate it based on different criteria:

For example, if cell1 is "a" and cell2 is "b" and cell3 is "1" and cell4 is "2 or 5" then enter "OK"
If not, enter "NOT OK" or leave empty.

```<code>Column 1    Column 2    Column 3    Column 4    "New_name"
a              b           1           2            "OK"
a              b           1           5            "OK"
c              d           e           f          "NOT OK"
</code>```

PLEASE HELP!!! :)

答:
IIUC:

```<code>mask = (df['Column 1'] == 'a') & (df['Column 2'] == 'b') & (df['Column 3'] == '1') & (df['Column 4'].isin(['2','5']))
df['new_value'] = np.where(mask,'OK','NOT OK')
</code>```

Output:

```<code>  Column 1 Column 2 Column 3 Column 4 "New_name" new_value
0        a        b        1        2       "OK"        OK
1        a        b        1        5       "OK"        OK
2        c        d        e        f   "NOT OK"    NOT OK
</code>```

Body:
import pandas as np
from pandas import Series, DataFrame

dframe_final.to_csv('C:/Program Files/source/csv_data/2015/Merged files/jjj_all_merged.csv')

I have this part of my code and I need to add a new column at the end of this csv file and name it "New_name".
And populate it based on different criteria:

For example, if cell1 is "a" and cell2 is "b" and cell3 is "1" and cell4 is "2 or 5" then enter "OK"
If not, enter "NOT OK" or leave empty.

Column 1    Column 2    Column 3    Column 4    "New_name"
a              b           1           2            "OK"
a              b           1           5            "OK"
c              d           e           f          "NOT OK"

PLEASE HELP!!! :)

Body:
IIUC:

mask = (df['Column 1'] == 'a') & (df['Column 2'] == 'b') & (df['Column 3'] == '1') & (df['Column 4'].isin(['2','5']))
df['new_value'] = np.where(mask,'OK','NOT OK')

Output:

  Column 1 Column 2 Column 3 Column 4 "New_name" new_value
0        a        b        1        2       "OK"        OK
1        a        b        1        5       "OK"        OK
2        c        d        e        f   "NOT OK"    NOT OK


问:
Sklearn: .predict returns an error Python
I installed sklearn with pip and when I use the function .predict it returns me this error:

```<code>Traceback (most recent call last):
   File "C:/Users/Roberto/PycharmProjects/AI projects/New.py", line 8, in <module>
print(clf.predict([150, 0]))
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\tree\tree.py", line 412, in predict
X = self._validate_X_predict(X, check_input)
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\tree\tree.py", line 373, in _validate_X_predict
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\utils\validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 150.    0.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code>```

And my code is:

```<code>from sklearn import tree
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(features, labels)
print(clf.predict([150, 0]))
</code>```

What's wrong with this?

答:
The hint is in the error message: "...if it contains a single sample."
The problem is that in general a list of samples to predict is expected rather than just one. The data passed to predict should be in the same format as the features passed to fit, i.e. a 2-D array. Try

```<code>clf.predict([[150, 0]])
</code>```

Body:
I installed sklearn with pip and when I use the function .predict it returns me this error:

Traceback (most recent call last):
   File "C:/Users/Roberto/PycharmProjects/AI projects/New.py", line 8, in <module>
print(clf.predict([150, 0]))
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\tree\tree.py", line 412, in predict
X = self._validate_X_predict(X, check_input)
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\tree\tree.py", line 373, in _validate_X_predict
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\utils\validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 150.    0.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

And my code is:

from sklearn import tree
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(features, labels)
print(clf.predict([150, 0]))

What's wrong with this?

Body:
The hint is in the error message: "...if it contains a single sample."
The problem is that in general a list of samples to predict is expected rather than just one. The data passed to predict should be in the same format as the features passed to fit, i.e. a 2-D array. Try

clf.predict([[150, 0]])


问:
Call Up FileMaker Record Based on Value of Javascript Variable in Web Viewer?
I am working on an app in FileMaker that includes a web map displayed through the web viewer.

I want the user to be able to select a feature within the web map and then call up the corresponding record in FileMaker. The web map features (GeoJSON) and the FileMaker records each have a corresponding ID column.

I already know how to pass the ID of a map feature to a js variable on a click event, but I do not know how to pass the value of this variable to FileMaker. Is this even possible? I hear FileMaker does not play well with others.

I have experience building interactive web maps but am relatively new to FileMaker.

Thanks!

答:
It's fairly easy to do, something like this should get you going. The file needs to be hosted on FileMaker server or have sharing enabled if it's on FileMaker Pro.

```<code><a href="fmp://hostaddress/file.fmp12?script=scriptname&param=scriptparameter">
</code>```

The script called could perform a find based on the parameter you supply or do just about anything.

And for the record, FileMaker is one of the easiest frameworks to integrate with. It can basically talk to everything.

Body:
It's fairly easy to do, something like this should get you going. The file needs to be hosted on FileMaker server or have sharing enabled if it's on FileMaker Pro.

<a href="fmp://hostaddress/file.fmp12?script=scriptname&param=scriptparameter">

The script called could perform a find based on the parameter you supply or do just about anything.

And for the record, FileMaker is one of the easiest frameworks to integrate with. It can basically talk to everything.


问:
how to access android files /data/anr/traces.txt and /data/tombstones/tombstones
I am writing an application for reporting crashes and the relevant logs.
So from my application I am trying to access traces.txt and tombstones, but I am getting an error:

```<code>03-25 09:48:46.220 W/System.err(10250): java.io.FileNotFoundException: /data/tombstone/tombstone_00 (Permission denied)
</code>```

I am able to access traces.txt, but not tombstones.

答:
You can capture a full bug report in Developer Options (see Android docs). In the bug report's ZIP file, you can find tombstones and anr folders in /FS/data.

This will work with rooted and unrooted devices.

Body:
I am writing an application for reporting crashes and the relevant logs.
So from my application I am trying to access traces.txt and tombstones, but I am getting an error:

03-25 09:48:46.220 W/System.err(10250): java.io.FileNotFoundException: /data/tombstone/tombstone_00 (Permission denied)

I am able to access traces.txt, but not tombstones.

ContentLicense: CC BY-SA 4.0


答:
You can use the $index and potentially do an

```<code>ng-class="{'timeline': $even, 'timeline-inverted': $odd}"
</code>```

The better option (in my opinion) is to use css classes "nth-child" to alter classes using css. Check out W3Schools nth-child to find it. I'm new to stack overflow so I'm not sure how to use JSFiddle but you could potentially use:

```<code>.timeline-inverted :nth-child(even) // Even Elements

.timeline-inverted :nth-child(odd) // Odd Elements
</code>```

I'm unsure where you want to apply the class but if you wanted to change the class of a div element with your ngRepeat, you can do the following:

```<code>.timeline-inverted div:nth-child(even)
.timeline-inverted div:nth-child(odd)
</code>```

Hopefully this answers your question.

Title: How do i use a ng-repeat with different classes with each index

Body:
I am building a timeline and i want to invert every other index in the ng-repeat. I used ng-repeat-start and ng-repeat-end on two separate divs but all they do is just repeat the same array twice.

 {{t.FirstName}}'s reply was: {{t.ReplyMessage}}

 {{t.FirstName}}'s reply was: {{t.ReplyMessage}}

I expect it to show the same list once but with the different css classes (timeline and timeline-inverted).

I thank you guys in advance.

Body:
You can use the $index and potentially do an

ng-class="{'timeline': $even, 'timeline-inverted': $odd}"

The better option (in my opinion) is to use css classes "nth-child" to alter classes using css. Check out W3Schools nth-child to find it. I'm new to stack overflow so I'm not sure how to use JSFiddle but you could potentially use:

.timeline-inverted :nth-child(even) // Even Elements

.timeline-inverted :nth-child(odd) // Odd Elements

I'm unsure where you want to apply the class but if you wanted to change the class of a div element with your ngRepeat, you can do the following:

.timeline-inverted div:nth-child(even)
.timeline-inverted div:nth-child(odd)

Hopefully this answers your question.


问:
Show specific elements in a comma- separated stringbuffer
I am working with SNMP4J and have it successfully outputting comma separated strings (from SNMP traps).

i.e.

```<code>StringBuffer msg = new StringBuffer();
msg.append(event.toString());
Vector<? extends VariableBinding> varBinds = event.getPDU().getVariableBindings();
if (varBinds != null && !varBinds.isEmpty()) {
    Iterator<? extends VariableBinding> varIter = varBinds.iterator();
    while (varIter.hasNext()) {
        VariableBinding var = varIter.next();
        msg.append(var.toString()).append(";");
    }
}
System.out.println("Message Received: " + msg.toString());
</code>```

outputs -

```<code>Message Received: CommandResponderEvent[securityModel=1, securityLevel=1, maxSizeResponsePDU=65535,  etc etc
</code>```

As well as the entire output string I need to display specific elements (in particular

```<code>peerAddress=192.168.150.210/61263
</code>```

and

```<code>VBS[1.3.6.1.4.1.332.10.14.19.11.0 = Fire]]
</code>```

but only ideally the IP address part (192.168.150.210) and the 'meaning' (Fire)

Do I use split to find specific elements and then substring those or is there a better way?

```<code>String sixth_word = msg.toString().split(",")[6];
</code>```

答:
You don’t need a StringBuffer, since you have String.join:

```<code>String msg = event + " " + String.join(";", event.getPDU().getVariableBindings());
</code>```

Personally, for a diagnostic message, I wouldn’t even bother with String.join:

```<code>String msg = event + " " + event.getPDU().getVariableBindings();
</code>```

Reading the documentation of the classes you’re using will go a long way toward showing you what is available to you.  If you read the documentation for CommandResponderEvent, you’ll see it has public methods that provide the data you desire:

```<code>String peerAddress = event.getPeerAddress().toString();
</code>```

Looking at the documentation of VariableBinding, we can see that it has a getVariable() method.  Each binding’s Variable is where the “Fire” text comes from:

```<code>List<String> variables = new ArrayList<>();
for (VariableBinding binding : event.getPDU().getVariableBindings()) {
    variables.add(String.valueOf(binding.getVariable()));
}
</code>```

Body:
I am working with SNMP4J and have it successfully outputting comma separated strings (from SNMP traps).

i.e.

StringBuffer msg = new StringBuffer();
msg.append(event.toString());
Vector<? extends VariableBinding> varBinds = event.getPDU().getVariableBindings();
if (varBinds != null && !varBinds.isEmpty()) {
    Iterator<? extends VariableBinding> varIter = varBinds.iterator();
    while (varIter.hasNext()) {
        VariableBinding var = varIter.next();
        msg.append(var.toString()).append(";");
    }
}
System.out.println("Message Received: " + msg.toString());

outputs -

Message Received: CommandResponderEvent[securityModel=1, securityLevel=1, maxSizeResponsePDU=65535,  etc etc

As well as the entire output string I need to display specific elements (in particular

peerAddress=192.168.150.210/61263

and

VBS[1.3.6.1.4.1.332.10.14.19.11.0 = Fire]]

but only ideally the IP address part (192.168.150.210) and the 'meaning' (Fire)

Do I use split to find specific elements and then substring those or is there a better way?

String sixth_word = msg.toString().split(",")[6];

Body:
You don’t need a StringBuffer, since you have String.join:

String msg = event + " " + String.join(";", event.getPDU().getVariableBindings());

Personally, for a diagnostic message, I wouldn’t even bother with String.join:

String msg = event + " " + event.getPDU().getVariableBindings();

Reading the documentation of the classes you’re using will go a long way toward showing you what is available to you.  If you read the documentation for CommandResponderEvent, you’ll see it has public methods that provide the data you desire:

String peerAddress = event.getPeerAddress().toString();

Looking at the documentation of VariableBinding, we can see that it has a getVariable() method.  Each binding’s Variable is where the “Fire” text comes from:

List<String> variables = new ArrayList<>();
for (VariableBinding binding : event.getPDU().getVariableBindings()) {
    variables.add(String.valueOf(binding.getVariable()));
}


问:
why this code doesn't work i am using python3?
I wanna delete the values of the list

```<code>lists = [12,15,15,15,3,15,1,6,4,7,888,56248]
while len(lists) is True:
    lists.pop()
print(lists)
</code>```

But i got this output :

```<code>[12, 15, 15, 15, 3, 15, 1, 6, 4, 7, 888, 56248]
</code>```

答:
The problem here is in your conditional

```<code>while len(lists) is True:
</code>```

is checks for identity, not equality.

```<code>[1, 2, 3] == [1, 2, 3]  # True
[1, 2, 3] is [1, 2, 3]  # False, they are two distinct (but equivalent) lists.
</code>```

However even equality would be incorrect here, since

```<code>42 == True           # False
2 == True            # False
any_nonzero == True  # False
# notably 1 == True
# and     0 == False
# but still (1 is True) == False!
</code>```

You can coerce an integer into a boolean

```<code>bool(42) == True           # True
bool(2) == True            # True
bool(any_nonzero) == True  # True
</code>```

But it's usually better to just leave the coercion to Python

```<code>while lists:
    lists.pop()
# or more simply:
# lists = []
</code>```

Body:
I wanna delete the values of the list

lists = [12,15,15,15,3,15,1,6,4,7,888,56248]
while len(lists) is True:
    lists.pop()
print(lists)

But i got this output :

[12, 15, 15, 15, 3, 15, 1, 6, 4, 7, 888, 56248]

Body:
The problem here is in your conditional

while len(lists) is True:

is checks for identity, not equality.

[1, 2, 3] == [1, 2, 3]  # True
[1, 2, 3] is [1, 2, 3]  # False, they are two distinct (but equivalent) lists.

However even equality would be incorrect here, since

42 == True           # False
2 == True            # False
any_nonzero == True  # False
# notably 1 == True
# and     0 == False
# but still (1 is True) == False!

You can coerce an integer into a boolean

bool(42) == True           # True
bool(2) == True            # True
bool(any_nonzero) == True  # True

But it's usually better to just leave the coercion to Python

while lists:
    lists.pop()
# or more simply:
# lists = []


问:
Getting one element to match the scrolling of another
I have two tall and narrow elements of equal height that are next to each other. When I scroll one of these two elements, I want the other to scroll with it.

How can I do this using jQuery? I've tried the ScrollTo plugin but the documentation is so bad I can't figure out how to use it.

答: Please go through this tutorial and change the code like what you want


问:
Cannot find R.layout.activity_main in main activity.java
I am developing an app, and have started working on main screen design but I am not able to test my app. When I want to test the app it suddenly stop all the time and error showing in catlog in the line

setContentView(R.layout.activity_main)

I have attached the screenshots in this question also.

答:
I invite to you to clean project and rebuild again, you have the how to here.

And remove those imports that contains R in your project.

import vibhor.dev.eat24.R;

import vibhor.dev.eat24.R.layout;

I see you have this :

```<code>dependencies {
   classpath 'com.android.tools.build:gradle:3.0.1'
   classpath 'com.google.gms:google-services:3.1.0'
}
</code>```

Change it to :

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
}
</code>```

This is problem of your library, take a look on this answer, try it, if it does not work.. just change the library.

Body:
I invite to you to clean project and rebuild again, you have the how to here.

And remove those imports that contains R in your project.

import vibhor.dev.eat24.R;

import vibhor.dev.eat24.R.layout;

I see you have this :

dependencies {
   classpath 'com.android.tools.build:gradle:3.0.1'
   classpath 'com.google.gms:google-services:3.1.0'
}

Change it to :

dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
}

This is problem of your library, take a look on this answer, try it, if it does not work.. just change the library.


问:
java | Return a reversed array by FOR loop
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

```<code>    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

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

But it is throwing out three exact same numbers.

答:
From a first look, your code should be more like this:</p>

```<code>public int[] reverse3(int[] nums)
{

  // initialize a second array with the same length
  int[] nums2 = new int[nums.length];
  // initialize the nums2 index
  int index = 0;

  // you only need one loop for this (since we'll be incrementing the index of nums2)
  for (int i = nums.length - 1; i >= 0; i--) {
     nums2[index] = nums[i];
     index++;
  }

  return nums2;
}
</code>```

Body:
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}

But it is throwing out three exact same numbers.

Body:
From a first look, your code should be more like this:

public int[] reverse3(int[] nums)
{

  // initialize a second array with the same length
  int[] nums2 = new int[nums.length];
  // initialize the nums2 index
  int index = 0;

  // you only need one loop for this (since we'll be incrementing the index of nums2)
  for (int i = nums.length - 1; i >= 0; i--) {
     nums2[index] = nums[i];
     index++;
  }

  return nums2;
}


答:
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:</p>

```<code>public int[] reverse(int[] nums) {
    int len = nums.length;
    int[] result = new int[len];
    for (int i = 0; i < len; ++i) {
        result[len - i - 1] = nums[i];
    }
}
</code>```

Title: java | Return a reversed array by FOR loop

Body:
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:

public int[] reverse(int[] nums) {
    int len = nums.length;
    int[] result = new int[len];
    for (int i = 0; i < len; ++i) {
        result[len - i - 1] = nums[i];
    }
}


问:
DataTable - Invalid JSON response when retrieved from PHP
I know that it's a common question, but I have a different problem.

When I retrieve a Json response from PHP, it throws this alert warning and don't load the data into the datatable.

When I load the generated Json (retrieved from PHP) directly from file, the datatable loads the data correctly.

I have the following jquery configuration for my datatable:

```<code>$( document ).ready(function() {
$('#example').dataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
        },
        "bProcessing": true,
               "sAjaxSource": "response.php",
        "aoColumns": [
              { mData: 'id' } ,
              { mData: 'name' },
              { mData: 'description' }
              //{ mData: 'img', render: getImg },
        ]
      });
});
</code>```

The generated json from php (that works if loaded directly from file):

```<code>{
    "sEcho": 1,
    "iTotalRecords": 10,
    "iTotalDisplayRecords": 10,
    "aaData": [{
        "id": "1",
        "name": "Salsa estilo Casino",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "2",
        "name": "Salsa estilo Son",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "3",
        "name": "Salsa LA",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "4",
        "name": "Salsa NY",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "5",
        "name": "Bachata",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "6",
        "name": "Reggaeton",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "7",
        "name": "Chachacha",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "8",
        "name": "Rumba",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "9",
        "name": "Pachanga",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "10",
        "name": "Ritmos tradicionais cubanos",
        "description": "Descri\u00e7\u00e3o ..."
    }]
}
</code>```

My PHP response.php file:

```<code><?php
// my database classe with CRUDed POJOs.
include_once '../admin/db.php';

// That was from a sample code that worked fine.
$data = array(
array('Name'=>'Descrição ...', 'Empid'=>11, 'Salary'=>101, 'img' => '../img/lais.jpg'),
array('Name'=>'alam', 'Empid'=>1, 'Salary'=>102, 'img' => '../img/lais.jpg'),
array('Name'=>'phpflow', 'Empid'=>21, 'Salary'=>103, 'img' => '../img/lais.jpg')
);

/* Query the database and retrive in $data2[0] the total number of rows
and $data2[1] an array of arrays with  the following format (as described above):
array(
    array('id' => '1', 'name' => 'name', 'description' => 'Desc ...'),
    ...
)
*/
$data2 = Turma::fetchAllAssoc();
$results = array(
        "sEcho" => 1,
    "iTotalRecords" => 10,
    "iTotalDisplayRecords" => 10,
      "aaData"=>$data2[1]);

header('Content-Type: application/json');
echo json_encode($results);

?>
</code>```

What am I doing wrong? It seems a bug form me.

答:
Solved my problem.

In PHP, the response.php was returning only the json content that was shwon in the browser.

The error was: there was some html commented content that seems hidden in `include_once '../admin/db.php';, even the commented html tags.

When I added the line header('Content-Type: application/json'); everything that seems missing was shown in the browser.

Erased everything, even commented html tags to output (echo) only json_encode($results);. Then, everything worked smoothy.

Body:
I know that it's a common question, but I have a different problem.

When I retrieve a Json response from PHP, it throws this alert warning and don't load the data into the datatable.

When I load the generated Json (retrieved from PHP) directly from file, the datatable loads the data correctly.

I have the following jquery configuration for my datatable:

$( document ).ready(function() {
$('#example').dataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
        },
        "bProcessing": true,
               "sAjaxSource": "response.php",
        "aoColumns": [
              { mData: 'id' } ,
              { mData: 'name' },
              { mData: 'description' }
              //{ mData: 'img', render: getImg },
        ]
      });
});

The generated json from php (that works if loaded directly from file):

{
    "sEcho": 1,
    "iTotalRecords": 10,
    "iTotalDisplayRecords": 10,
    "aaData": [{
        "id": "1",
        "name": "Salsa estilo Casino",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "2",
        "name": "Salsa estilo Son",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "3",
        "name": "Salsa LA",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "4",
        "name": "Salsa NY",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "5",
        "name": "Bachata",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "6",
        "name": "Reggaeton",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "7",
        "name": "Chachacha",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "8",
        "name": "Rumba",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "9",
        "name": "Pachanga",
        "description": "Descri\u00e7\u00e3o ..."
    }, {
        "id": "10",
        "name": "Ritmos tradicionais cubanos",
        "description": "Descri\u00e7\u00e3o ..."
    }]
}

My PHP response.php file:

<?php
// my database classe with CRUDed POJOs.
include_once '../admin/db.php';

// That was from a sample code that worked fine.
$data = array(
array('Name'=>'Descrição ...', 'Empid'=>11, 'Salary'=>101, 'img' => '../img/lais.jpg'),
array('Name'=>'alam', 'Empid'=>1, 'Salary'=>102, 'img' => '../img/lais.jpg'),
array('Name'=>'phpflow', 'Empid'=>21, 'Salary'=>103, 'img' => '../img/lais.jpg')
);

/* Query the database and retrive in $data2[0] the total number of rows
and $data2[1] an array of arrays with  the following format (as described above):
array(
    array('id' => '1', 'name' => 'name', 'description' => 'Desc ...'),
    ...
)
*/
$data2 = Turma::fetchAllAssoc();
$results = array(
        "sEcho" => 1,
    "iTotalRecords" => 10,
    "iTotalDisplayRecords" => 10,
      "aaData"=>$data2[1]);

header('Content-Type: application/json');
echo json_encode($results);

?>

What am I doing wrong? It seems a bug form me.


问:
bash: terraform: command not found, export $PATH unresolved
All my efforts to run terraform(exe) from command line in Ubuntu are unsuccessful

```<code>~/tectonic_1.7.9-tectonic.2$ terraform init ./platforms/metal
terraform: command not found
</code>```

I changed ~/.profile file

```<code>PATH="$HOME/bin:$HOME/.local/bin:$HOME/bin/tectonic_1.7.9-tectonic.2:$PATH"
</code>```

and latter sym link

```<code>/usr/bin# ls -l terraform
lrwxrwxrwx 1 root root 39 dec  6 16:29 terraform -> /home/milenko/tectonic_1.7.9-tectonic.2
</code>```

I don't understand what is wrong.If I try what Asere suggested

```<code>ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
ln: failed to create symbolic link '/usr/bin/terraform/terraform': File exists
</code>```

答:
First the fix, and then the explanation:

```<code>ln -snf /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
# or equivalently:
#rm /usr/bin/terraform
#ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
</code>```

Currently you have /usr/bin/terraform pointing to /home/milenko/tectonic_1.7.9-tectonic.2.

Which is not correct, because the terraform binary is in /home/milenko/tectonic_1.7.9-tectonic.2/terraform.

You need to make /usr/bin/terraform point to /home/milenko/tectonic_1.7.9-tectonic.2/terraform.

Let's understand what's happening here:

```<code>ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
ln: failed to create symbolic link '/usr/bin/terraform/terraform': File exists
</code>```

Why does the command fail?
Since /usr/bin/terraform exists,
and it points to /home/milenko/tectonic_1.7.9-tectonic.2,
the above comment will not try to replace /usr/bin/terraform,
but try to create /usr/bin/terraform/terraform.
And since /usr/bin/terraform points to /home/milenko/tectonic_1.7.9-tectonic.2, /usr/bin/terraform/terraform already exists, it's actually the same thing as /home/milenko/tectonic_1.7.9-tectonic.2/terraform.
And so the file exists, and the command fails.

One solution is to remove the incorrect symlink /usr/bin/terraform and then re-run ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform.

Another solution is to add the -f and -n flags to ln,
to force replace the symlink:

```<code>ln -snf /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
</code>```

Body:
All my efforts to run terraform(exe) from command line in Ubuntu are unsuccessful

~/tectonic_1.7.9-tectonic.2$ terraform init ./platforms/metal
terraform: command not found

I changed ~/.profile file

PATH="$HOME/bin:$HOME/.local/bin:$HOME/bin/tectonic_1.7.9-tectonic.2:$PATH"

and latter sym link

/usr/bin# ls -l terraform
lrwxrwxrwx 1 root root 39 dec  6 16:29 terraform -> /home/milenko/tectonic_1.7.9-tectonic.2

I don't understand what is wrong.If I try what Asere suggested

ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
ln: failed to create symbolic link '/usr/bin/terraform/terraform': File exists

Body:
First the fix, and then the explanation:

ln -snf /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
# or equivalently:
#rm /usr/bin/terraform
#ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform

Currently you have /usr/bin/terraform pointing to /home/milenko/tectonic_1.7.9-tectonic.2.

Which is not correct, because the terraform binary is in /home/milenko/tectonic_1.7.9-tectonic.2/terraform.

You need to make /usr/bin/terraform point to /home/milenko/tectonic_1.7.9-tectonic.2/terraform.

Let's understand what's happening here:

ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform
ln: failed to create symbolic link '/usr/bin/terraform/terraform': File exists

Why does the command fail?
Since /usr/bin/terraform exists,
and it points to /home/milenko/tectonic_1.7.9-tectonic.2,
the above comment will not try to replace /usr/bin/terraform,
but try to create /usr/bin/terraform/terraform.
And since /usr/bin/terraform points to /home/milenko/tectonic_1.7.9-tectonic.2, /usr/bin/terraform/terraform already exists, it's actually the same thing as /home/milenko/tectonic_1.7.9-tectonic.2/terraform.
And so the file exists, and the command fails.

One solution is to remove the incorrect symlink /usr/bin/terraform and then re-run ln -s /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform.

Another solution is to add the -f and -n flags to ln,
to force replace the symlink:

ln -snf /home/milenko/tectonic_1.7.9-tectonic.2/terraform /usr/bin/terraform


问:
`position:absolute` with `bottom:0` is not working with parent having display:flex?
I want to fix div with class sidebar to the bottom of the container, but position: absolute with bottom:0 is not working with a container having display: flex.

how to solve that problem?

code: https://jsfiddle.net/zgmg48z1/1/

/*******************page layout**************************/
.container{
  width: 100%;
  background-color: #d5d5d5;
  display: flex;
  align-items: flex-start;
}
.sidebarcontainer{
  width: 250PX;
  /*height: 6000px;*/
  display: inline-block;
  box-sizing: border-box;
  padding: 5px;
  padding-right: 2px;
}
.innersidebarcontainer{
  position: relative;
      width: 100%;
    height: 100%;
}
.sidebar{
  width: 243px;
  background-color: white;
  height: 500px;
  /*top: 1px;*/
  /*bottom: 0;*/
  /*position: absolute;*/
}
.mainpage{
  width: calc(100% - 250px);
  padding: 5px;
  padding-left: 2px;
  height: 600px;
  display: inline-block;
  box-sizing: border-box;
}
.page{
  width: 100%;
  height: 100%;
  background-color: white;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: baseline;
  align-content: flex-start;
}
.footer{
  height: 500px;
  width: 100%;
  margin: 0 auto;
  background-color: #031003;
}
/***************end of pagelayout******************/
.card{
  width: 250px;
  /*height: 400px;*/
  align-self: flex-start;
  margin: 10px;
  display: inline-block;
}
.image{
  width: 200px;
  margin: 0 auto;
  height: 250px;
}
.image img{
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
        <div class="sidebarcontainer">
            <div class="innersidebarcontainer">
                    <div class="sidebar">
                </div>
            </div>
        </div><!--
    --><div class="mainpage">
        <div class="page">
        <h1>something in the page</h1>
        </div>
    </div>
    </div>
    <div class="footer"></div></code>```

答: This exact same problem happened to me recently. In my case it wasn't the fault of flex or even the positioning at all in the end, turns out I had another class that was cascading down and also effecting the element's absolute position making it look like my new values weren't working.</p>

Body:
I want to fix div with class sidebar to the bottom of the container, but position: absolute with bottom:0 is not working with a container having display: flex.

how to solve that problem?

code: https://jsfiddle.net/zgmg48z1/1/

/*******************page layout**************************/
.container{
  width: 100%;
  background-color: #d5d5d5;
  display: flex;
  align-items: flex-start;
}
.sidebarcontainer{
  width: 250PX;
  /*height: 6000px;*/
  display: inline-block;
  box-sizing: border-box;
  padding: 5px;
  padding-right: 2px;
}
.innersidebarcontainer{
  position: relative;
      width: 100%;
    height: 100%;
}
.sidebar{
  width: 243px;
  background-color: white;
  height: 500px;
  /*top: 1px;*/
  /*bottom: 0;*/
  /*position: absolute;*/
}
.mainpage{
  width: calc(100% - 250px);
  padding: 5px;
  padding-left: 2px;
  height: 600px;
  display: inline-block;
  box-sizing: border-box;
}
.page{
  width: 100%;
  height: 100%;
  background-color: white;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: baseline;
  align-content: flex-start;
}
.footer{
  height: 500px;
  width: 100%;
  margin: 0 auto;
  background-color: #031003;
}
/***************end of pagelayout******************/
.card{
  width: 250px;
  /*height: 400px;*/
  align-self: flex-start;
  margin: 10px;
  display: inline-block;
}
.image{
  width: 200px;
  margin: 0 auto;
  height: 250px;
}
.image img{
  width: 100%;
  height: 100%;
}

something in the page


问:
query not called when props are changed in Apollo client with react js
I need a query to be called when props are updated in redux store. But it is not happening like that, query is called only once when component is loaded.

My code is like this - -

```<code>  const sampleData = compose(graphql(ITEMS_BY_CATEGORY, {name:"itemByCategory", options: (props) => ({variables: {_id:props.user._id,searchstring:"", start:0,limit:10, itemype:"created",categoryid:props.categoryid}})}))(samplePage)

export default connect(
  (state) => ({user: state.user.user,categoryid: state.item.categoryid}),
  {}
)(sampleData);
</code>```

I tried refetch method after props are updated. Like  - this.props.data.refetch(). But it also didn't work.

答:
Add componentWillReceiveProps() and call the query there. It will run whenever the component receives new props. If you need to re-run the render function with the results of the query, you may need to call forceUpdate();

```<code>componentWillReceiveProps(nextProps) {
       const localThis = this;
       this.client.query({
            query: MY_QUERY,
            variables: {myVar: theVar},
        }).then((result) => {
            localThis.setState({myStateVar: result.data.relevantData});
            localThis.forceUpdate();
        });
  }
</code>```

Body:
I need a query to be called when props are updated in redux store. But it is not happening like that, query is called only once when component is loaded.

My code is like this - -

  const sampleData = compose(graphql(ITEMS_BY_CATEGORY, {name:"itemByCategory", options: (props) => ({variables: {_id:props.user._id,searchstring:"", start:0,limit:10, itemype:"created",categoryid:props.categoryid}})}))(samplePage)

export default connect(
  (state) => ({user: state.user.user,categoryid: state.item.categoryid}),
  {}
)(sampleData);

I tried refetch method after props are updated. Like  - this.props.data.refetch(). But it also didn't work.

Body:
Add componentWillReceiveProps() and call the query there. It will run whenever the component receives new props. If you need to re-run the render function with the results of the query, you may need to call forceUpdate();

componentWillReceiveProps(nextProps) {
       const localThis = this;
       this.client.query({
            query: MY_QUERY,
            variables: {myVar: theVar},
        }).then((result) => {
            localThis.setState({myStateVar: result.data.relevantData});
            localThis.forceUpdate();
        });
  }


问:
java username and password input validation
I am trying to prompt the user to input his or her username and password when prompted. after they input I am trying to check it against a text file I have stored with my source code.

```<code>public static void getCreds()
{
    String userName;
    String userPass;

    Scanner credsInput = new Scanner(System.in);

    System.out.print("Please enter your username: ");
        userName = credsInput.nextLine();
    System.out.print("Please enter your password: ");
        userPass = credsInput.nextLine();

    boolean found = false;
    String tempUser;
    String tempPass;
    //String fileName = "credentials.txt";

    try
    {
        // Scanner scan = new Scanner(new BufferedReader(new FileReader("credentials.txt")))
        Scanner scan = new Scanner(new File("credentials.txt"));
        scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            tempUser = scan.next();
            tempPass = scan.next();

            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
            }

        }

        scan.close();
    }

    catch (Exception e)
    {
        System.out.println("invalid");
    }

}
</code>```

and this is the contents of the text file.

```<code>user1,pass1
bob,1234
jim,1234
</code>```

I don't believe that it is actually reading from the file but I may be wrong, any help is appreciated.

edit

I forgot to put my output. when I compile and run the code it asks for the username and output successfully and regardless if I put in a correct one or not, it throws the exception and displays

```<code>invalid
</code>```

edit #2

my first issue was that I wasn't used to storing text files in java properly. After I changed the text file to the proper place. I was able to change the useDelimiter line successfully

```<code>scan.useDelimiter(",|\n");
</code>```

now it succesfuly checks both the username and password and outputs

```<code>Success
</code>```

if the input is in the text file.

答:
Remove the coma used as a delimeter because it will take for example 1234appended to the carriage return \nas a token , I tried on my IDE like this:

```<code>   //scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            String line  = scan.nextLine();
            tempUser = line.split(",")[0];
            tempPass = line.split(",")[1];
            //..... complete the logic as it was

          }
         .....
</code>```

Body:
I am trying to prompt the user to input his or her username and password when prompted. after they input I am trying to check it against a text file I have stored with my source code.

public static void getCreds()
{
    String userName;
    String userPass;

    Scanner credsInput = new Scanner(System.in);

    System.out.print("Please enter your username: ");
        userName = credsInput.nextLine();
    System.out.print("Please enter your password: ");
        userPass = credsInput.nextLine();

    boolean found = false;
    String tempUser;
    String tempPass;
    //String fileName = "credentials.txt";

    try
    {
        // Scanner scan = new Scanner(new BufferedReader(new FileReader("credentials.txt")))
        Scanner scan = new Scanner(new File("credentials.txt"));
        scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            tempUser = scan.next();
            tempPass = scan.next();

            if(tempUser.trim().equals(userName.trim()) && tempPass.trim().equals(userPass.trim()))
            {
                found = true;
                System.out.println("success");
            }

        }

        scan.close();
    }

    catch (Exception e)
    {
        System.out.println("invalid");
    }

}

and this is the contents of the text file.

user1,pass1
bob,1234
jim,1234

I don't believe that it is actually reading from the file but I may be wrong, any help is appreciated.

edit

I forgot to put my output. when I compile and run the code it asks for the username and output successfully and regardless if I put in a correct one or not, it throws the exception and displays

invalid

edit #2

my first issue was that I wasn't used to storing text files in java properly. After I changed the text file to the proper place. I was able to change the useDelimiter line successfully

scan.useDelimiter(",|\n");

now it succesfuly checks both the username and password and outputs

Success

if the input is in the text file.

Body:
Remove the coma used as a delimeter because it will take for example 1234appended to the carriage return \nas a token , I tried on my IDE like this:

   //scan.useDelimiter(",");

        while (scan.hasNext() && !found)
        {
            String line  = scan.nextLine();
            tempUser = line.split(",")[0];
            tempPass = line.split(",")[1];
            //..... complete the logic as it was

          }
         .....


问:
Returning probabilities in a classification prediction in Keras?
I am trying to make a simple proof-of-concept where I can see the probabilities of different classes for a given prediction.

However, everything I try seems to only output the predicted class, even though I am using a softmax activation. I am new to machine learning, so I'm not sure if I am making a simple mistake or if this is a feature not available in Keras.

I'm using Keras + TensorFlow. I have adapted one of the basic examples given by Keras for classifying the MNIST dataset.

My code below is exactly the same as the example, except for a few (commented) extra lines that exports the model to a local file.

```<code>'''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''

from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

import h5py # added import because it is required for model.save
model_filepath = 'test_model.h5' # added filepath config

batch_size = 128
num_classes = 10
epochs = 20

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

model.summary()

model.compile(loss='categorical_crossentropy',
          optimizer=RMSprop(),
          metrics=['accuracy'])

history = model.fit(x_train, y_train,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

model.save(model_filepath) # added saving model
print('Model saved') # added log
</code>```

Then the second part of this is a simple script that should import the model, predict the class for some given data, and print out the probabilities for each class. (I am using the same mnist class included with the Keras codebase to make an example as simple as possible).

```<code>import keras
from keras.datasets import mnist
from keras.models import Sequential
import keras.backend as K

import numpy

# loading model saved locally in test_model.h5
model_filepath = 'test_model.h5'
prev_model = keras.models.load_model(model_filepath)

# these lines are copied from the example for loading MNIST data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)

# for this example, I am only taking the first 10 images
x_slice = x_train[slice(1, 11, 1)]

# making the prediction
prediction = prev_model.predict(x_slice)

# logging each on a separate line
for single_prediction in prediction:
    print(single_prediction)
</code>```

If I run the first script to export the model, then the second script to classify some examples, I get the following output:

```<code>[ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
[ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
</code>```

This is great for seeing which class each is predicted to be, but what if I want to see the relative probabilities of each class for each example? I am looking for something more like this:

```<code>[ 0.94 0.01 0.02 0. 0. 0.01 0. 0.01 0.01 0.]
[ 0. 0. 0. 0. 0.51 0. 0. 0. 0.49 0.]
...
</code>```

In other words, I need to know how sure each prediction is, not just the prediction itself. I thought seeing the relative probabilities was a part of using a softmax activation in the model, but I can't seem to find anything in the Keras documentation that would give me probabilities instead of the predicted answer. Am I making some kind of silly mistake, or is this feature not available?

答:
So it turns out that the problem was I was not fully normalizing the data in the prediction script.

My prediction script should have had the following lines:

```<code># these lines are copied from the example for loading MNIST data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_train = x_train.astype('float32') # this line was missing
x_train /= 255 # this line was missing too
</code>```

Because the data was not cast to float, and divided by 255 (so it would be between 0 and 1), it was just showing up as 1s and 0s.

Body:
I am trying to make a simple proof-of-concept where I can see the probabilities of different classes for a given prediction.

However, everything I try seems to only output the predicted class, even though I am using a softmax activation. I am new to machine learning, so I'm not sure if I am making a simple mistake or if this is a feature not available in Keras.

I'm using Keras + TensorFlow. I have adapted one of the basic examples given by Keras for classifying the MNIST dataset.

My code below is exactly the same as the example, except for a few (commented) extra lines that exports the model to a local file.

'''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''

from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

import h5py # added import because it is required for model.save
model_filepath = 'test_model.h5' # added filepath config

batch_size = 128
num_classes = 10
epochs = 20

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

model.summary()

model.compile(loss='categorical_crossentropy',
          optimizer=RMSprop(),
          metrics=['accuracy'])

history = model.fit(x_train, y_train,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

model.save(model_filepath) # added saving model
print('Model saved') # added log

Then the second part of this is a simple script that should import the model, predict the class for some given data, and print out the probabilities for each class. (I am using the same mnist class included with the Keras codebase to make an example as simple as possible).

import keras
from keras.datasets import mnist
from keras.models import Sequential
import keras.backend as K

import numpy

# loading model saved locally in test_model.h5
model_filepath = 'test_model.h5'
prev_model = keras.models.load_model(model_filepath)

# these lines are copied from the example for loading MNIST data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)

# for this example, I am only taking the first 10 images
x_slice = x_train[slice(1, 11, 1)]

# making the prediction
prediction = prev_model.predict(x_slice)

# logging each on a separate line
for single_prediction in prediction:
    print(single_prediction)

If I run the first script to export the model, then the second script to classify some examples, I get the following output:

[ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
[ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]

This is great for seeing which class each is predicted to be, but what if I want to see the relative probabilities of each class for each example? I am looking for something more like this:

[ 0.94 0.01 0.02 0. 0. 0.01 0. 0.01 0.01 0.]
[ 0. 0. 0. 0. 0.51 0. 0. 0. 0.49 0.]
...

In other words, I need to know how sure each prediction is, not just the prediction itself. I thought seeing the relative probabilities was a part of using a softmax activation in the model, but I can't seem to find anything in the Keras documentation that would give me probabilities instead of the predicted answer. Am I making some kind of silly mistake, or is this feature not available?

Body:
So it turns out that the problem was I was not fully normalizing the data in the prediction script.

My prediction script should have had the following lines:

# these lines are copied from the example for loading MNIST data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_train = x_train.astype('float32') # this line was missing
x_train /= 255 # this line was missing too

Because the data was not cast to float, and divided by 255 (so it would be between 0 and 1), it was just showing up as 1s and 0s.


问:
Java to XML conversions?
What are different approaches to convert Java Objects to XML, I know one option is JAXB but would like to know what are the other approaches/tools available  for the same ?

Note: I do not have further requirements and so I cannot add more meat to the question but at this point of time it would be really great if I can get an idea of what different approaches are available for converting Java to XML ?

Update: Different suggested approaches are:

javax.xml.bind.Marshaller and javax.xml.bind.Unmarshaller

XStream

XMLBean

JAXB

Castor

JIBX

Apache Digester

Now among all the suggested approaches what is the BEST approach to go convert Java Objects to XML and XML to Java Objects ?

答:
Castor allows generation of Java classes(decent implementations) straight from XSD schema (use case #1 above).
Just be sure, in Android 2.1, not to use default android SAXParser. You'll get namespace errors. You do this by defining the parser to be, for example, Xerces (and the you add the required JARS), in core.properties . In android 2.2 it may be ok. Note that if you create an xmlcontext for the unmarsheler with xerces, it still won't work, as the mapping itself would be parsed with android's SAX. It must be done at core (top level properties file) so that even the mapping is parsed by xerces. finally - performance is as slow as you can expect... :( Good luck SM</p>

Title: Java to XML conversions?


问:
implementing linked list using arrays

I am trying to implement a linked list in java using arrays as the underlying structure. However, I am not sure how to do insert an element in the array after an element and shift the array down by one

```<code>    class linkedList{
    char data[];
    int next;
    //constructor
    public linkedList(int MAX){
        data = new char[MAX];
    }

    public void insertFirst(char d){
        if(data[next]==0){
        data[next] = d;
        next++;
        }
        else{
            System.out.println("list is full");
        }
    }

    public void insertAfter (char after ,char value){
        next=0;
        while(data[next] !=after){
            next++;
        }
        char temp = data[next+1];
        data[next+1] = value;

    }

    public void printList(){
        for(int i=0;i<data.length;i++){
            System.out.print(data[i]);
        }
    }
}

public class myLinkedList {

    public static void main(String args[]) {
        linkedList list = new linkedList(9);
        list.insertFirst('T');
        list.insertFirst('H');
        list.insertFirst('L');
        list.insertAfter('H', 'z');
        list.printList();
    }

}
</code>```

Also would this be considered a linked list?

答:
This is not a linked list. What you have is similar to an ArrayList, in that an array is used as the underlying data structure. A linked list is composed of a series of nodes, with each node linked to the next. The linked list is traversed by calling something like node.next() on the current node until the target or the end of the list is reached.

If you want to insert another element into your list structure after reaching the size limit, you will need to create a new array, copy the contents of the old array over, and insert the new element into the array. You can use System.arraycopy() to perform the copying or to shift items within the array.

Title: implementing linked list using arrays

Body:
I am trying to implement a linked list in java using arrays as the underlying structure. However, I am not sure how to do insert an element in the array after an element and shift the array down by one

    class linkedList{
    char data[];
    int next;
    //constructor
    public linkedList(int MAX){
        data = new char[MAX];
    }

    public void insertFirst(char d){
        if(data[next]==0){
        data[next] = d;
        next++;
        }
        else{
            System.out.println("list is full");
        }
    }

    public void insertAfter (char after ,char value){
        next=0;
        while(data[next] !=after){
            next++;
        }
        char temp = data[next+1];
        data[next+1] = value;

    }

    public void printList(){
        for(int i=0;i<data.length;i++){
            System.out.print(data[i]);
        }
    }
}

public class myLinkedList {

    public static void main(String args[]) {
        linkedList list = new linkedList(9);
        list.insertFirst('T');
        list.insertFirst('H');
        list.insertFirst('L');
        list.insertAfter('H', 'z');
        list.printList();
    }

}

Also would this be considered a linked list?


问:
How to send a SMS with Twilio behind a proxy?
I am trying to send SMS with the Twilio API and I receive the following error: System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.

I think this happens because the application is run behind a proxy.

How to make the Twilio API call with the proxy configured?

答:
I did not found a way to do it using the Twilio API.

Here is my solution:

```<code>using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        ["From"] = _twilioFromPhone,
        ["To"] = phoneNumber,
        ["Body"] = body
    };

    var encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(_accountSid + ":" + _authToken));
    client.Headers.Add("Authorization", "Basic " + encoded);

    client.Proxy = new WebProxy("[proxy address, not http in front]", proxy port number);

    var url = string.Format("https://api.twilio.com/2010-04-01/Accounts/{0}/Messages", _accountSid);
    var response = client.UploadValues(url, values);

    var responseString = Encoding.Default.GetString(response);
}
</code>```

Body:
I did not found a way to do it using the Twilio API.

Here is my solution:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        ["From"] = _twilioFromPhone,
        ["To"] = phoneNumber,
        ["Body"] = body
    };

    var encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(_accountSid + ":" + _authToken));
    client.Headers.Add("Authorization", "Basic " + encoded);

    client.Proxy = new WebProxy("[proxy address, not http in front]", proxy port number);

    var url = string.Format("https://api.twilio.com/2010-04-01/Accounts/{0}/Messages", _accountSid);
    var response = client.UploadValues(url, values);

    var responseString = Encoding.Default.GetString(response);
}


问:
How do you add a Dictionary of items into another Dictionary
Arrays in Swift support the += operator to add the contents of one Array to another. Is there an easy way to do that for a dictionary?

eg:

```<code>var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = ... (some way of combining dict1 & dict2 without looping)
</code>```

答:
In Swift 4, one should use merging(_:uniquingKeysWith:):

Example:

let dictA = ["x" : 1, "y": 2, "z": 3]
let dictB = ["x" : 11, "y": 22, "w": 0]

let resultA = dictA.merging(dictB, uniquingKeysWith: { (first, _) in first })
let resultB = dictA.merging(dictB, uniquingKeysWith: { (_, last) in last })

print(resultA) // ["x": 1, "y": 2, "z": 3, "w": 0]
print(resultB) // ["x": 11, "y": 22, "z": 3, "w": 0]
```

Body:
Arrays in Swift support the += operator to add the contents of one Array to another. Is there an easy way to do that for a dictionary?

eg:

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = ... (some way of combining dict1 & dict2 without looping)


问:
mySQL query -- if value in string
I have a string of IDs separated with comma

```<code>$myIDs = 22,23,45,895;
</code>```

How do I write a query to return records for values that correspond to the IDs in my string?
This does not seem to be right:

```<code>SELECT *
FROM t1
WHERE itemID IN ($myIDs)
</code>```

I guess I'm trying PHP array function here, hah? Is there something like this in mySQL?

Appreciate any suggestions. Thanks.

答:
```<code>$IDs = array(1,2,3,4,5);
// alternatively, you can write it like this...
// $IDs = "1,2,3,4,5";

if(is_array($IDs))
    $IDs = implode(",",$IDs);

$query = "SELECT * FROM t1 WHERE itemID IN ($IDs)";
echo $query;
</code>```

Title: mySQL query -- if value in string

Body:
I have a string of IDs separated with comma

$myIDs = 22,23,45,895;

How do I write a query to return records for values that correspond to the IDs in my string?
This does not seem to be right:

SELECT *
FROM t1
WHERE itemID IN ($myIDs)

I guess I'm trying PHP array function here, hah? Is there something like this in mySQL?

Appreciate any suggestions. Thanks.