问:
I/P-a string S.O/P: For each digit start from 0-9,print count of their occurrence in S.Print10 lines,each line contain 2 space separated integers
```<code>import java.util.*;
</code>```

class TestClass {
    public static void main(String args[] ) throws Exception {
        int count=0,count2=0,count3=0,count4=0,count5=0,count6=0,count7=0,count8=0,count9=0,count1=0,i;
        Scanner sc=new Scanner(System.in);

```<code>    int []a=new int[5];

    for(i=0;i<10;i++)
    {
        a[i]=sc.nextInt();
    }
    for(i=0;i<10;i++)
    {
        if(a[i]==0)
        {count++;}

        if(a[i]==1)
        {count1++;}

        if(a[i]==2)
        {count2++;}

        if(a[i]==3)
        {count3++;}

        if(a[i]==4)
        {count4++;}

        if(a[i]==5)
        {count5++;}

        if(a[i]==6)
        {count6++;}

        if(a[i]==7)
        {count7++;}

        if(a[i]==8)
        {count8++;}

        if(a[i]==9)
        {count9++;}

    }
        System.out.println("0"+count);
        System.out.println("1"+count1);
        System.out.println("2"+count2);
        System.out.println("3"+count3);
        System.out.println("4"+count4);
        System.out.println("5"+count5);
        System.out.println("6"+count6);
        System.out.println("7"+count7);
        System.out.println("8"+count8);
        System.out.println("9"+count9);

}
</code>```

}

答:
the problem is here:

```<code>  int []a=new int[5];
</code>```

you array is not enough

replace it like this:

```<code>  int []a=new int[10];
</code>```

and show something because user do not know what its happening

```<code>for(i=0;i<10;i++)
        {
            System.out.println("add number");
            a[i]=sc.nextInt();
        }
</code>```

if you change your code as me

like this:

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

public class Prueba {

      public static void main(String[] args){

           int count = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0, count1 = 0, i;
           Scanner sc = new Scanner(System.in);

      int []a=new int[10];

        for(i=0;i<10;i++)
        {
            System.out.println("add number");
            a[i]=sc.nextInt();
        }
        for(i=0;i<10;i++)
        {
            if(a[i]==0)
            {count++;}

            if(a[i]==1)
            {count1++;}

            if(a[i]==2)
            {count2++;}

            if(a[i]==3)
            {count3++;}

            if(a[i]==4)
            {count4++;}

            if(a[i]==5)
            {count5++;}

            if(a[i]==6)
            {count6++;}

            if(a[i]==7)
            {count7++;}

            if(a[i]==8)
            {count8++;}

            if(a[i]==9)
            {count9++;}

        }
            System.out.println("0"+count);
            System.out.println("1"+count1);
            System.out.println("2"+count2);
            System.out.println("3"+count3);
            System.out.println("4"+count4);
            System.out.println("5"+count5);
            System.out.println("6"+count6);
            System.out.println("7"+count7);
            System.out.println("8"+count8);
            System.out.println("9"+count9);

    }

}
</code>```

you will get something like this

```<code>add number
1
add number
2
add number
3
add number
4
add number
5
add number
6
add number
7
add number
8
add number
9
add number
0
01
11
21
31
41
51
61
71
81
91
</code>```

Body:
import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        int count=0,count2=0,count3=0,count4=0,count5=0,count6=0,count7=0,count8=0,count9=0,count1=0,i;
        Scanner sc=new Scanner(System.in);

    int []a=new int[5];

    for(i=0;i<10;i++)
    {
        a[i]=sc.nextInt();
    }
    for(i=0;i<10;i++)
    {
        if(a[i]==0)
        {count++;}

        if(a[i]==1)
        {count1++;}

        if(a[i]==2)
        {count2++;}

        if(a[i]==3)
        {count3++;}

        if(a[i]==4)
        {count4++;}

        if(a[i]==5)
        {count5++;}

        if(a[i]==6)
        {count6++;}

        if(a[i]==7)
        {count7++;}

        if(a[i]==8)
        {count8++;}

        if(a[i]==9)
        {count9++;}

    }
        System.out.println("0"+count);
        System.out.println("1"+count1);
        System.out.println("2"+count2);
        System.out.println("3"+count3);
        System.out.println("4"+count4);
        System.out.println("5"+count5);
        System.out.println("6"+count6);
        System.out.println("7"+count7);
        System.out.println("8"+count8);
        System.out.println("9"+count9);

}

}

Body:
the problem is here:

  int []a=new int[5];

you array is not enough

replace it like this:

  int []a=new int[10];

and show something because user do not know what its happening

for(i=0;i<10;i++)
        {
            System.out.println("add number");
            a[i]=sc.nextInt();
        }

if you change your code as me

like this:

package teteo;
import java.util.Scanner;

public class Prueba {

      public static void main(String[] args){

           int count = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0, count1 = 0, i;
           Scanner sc = new Scanner(System.in);

      int []a=new int[10];

        for(i=0;i<10;i++)
        {
            System.out.println("add number");
            a[i]=sc.nextInt();
        }
        for(i=0;i<10;i++)
        {
            if(a[i]==0)
            {count++;}

            if(a[i]==1)
            {count1++;}

            if(a[i]==2)
            {count2++;}

            if(a[i]==3)
            {count3++;}

            if(a[i]==4)
            {count4++;}

            if(a[i]==5)
            {count5++;}

            if(a[i]==6)
            {count6++;}

            if(a[i]==7)
            {count7++;}

            if(a[i]==8)
            {count8++;}

            if(a[i]==9)
            {count9++;}

        }
            System.out.println("0"+count);
            System.out.println("1"+count1);
            System.out.println("2"+count2);
            System.out.println("3"+count3);
            System.out.println("4"+count4);
            System.out.println("5"+count5);
            System.out.println("6"+count6);
            System.out.println("7"+count7);
            System.out.println("8"+count8);
            System.out.println("9"+count9);

    }

}

you will get something like this

add number
1
add number
2
add number
3
add number
4
add number
5
add number
6
add number
7
add number
8
add number
9
add number
0
01
11
21
31
41
51
61
71
81
91


来源: stackexchange

问:
Please guide a proper script to have the dynamic results by using dynamodb and nodejs
By writing this below code i am writing the script again and again to have the added records, without writing the script again and again i want added records in resulting. Using dynamodb and nodejs. Please provide the correct script.</p>

```<code>var AWS = require("aws-sdk");
var async = require("async");

AWS.config.update({
      region: "us-west-2",
      endpoint: "2345",
      accessKeyId: "A",
      secretAccessKey:"x"
    });

var db = new AWS.DynamoDB.DocumentClient()

var table = "rets_property_all";
var pstart =new Date () .getTime ();

async.parallel({
        0 : function(callback){
        db.scan ({TableName: table,
        ProjectionExpression: "#cityname,ListingKey ",
        FilterExpression: "#cityname = :v_id",
        ExpressionAttributeNames: {
        "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 2,
            Segment:  0//by the worker who has been called
        },function (err , res) {
            callback (null , res.Items);
        });
            },
            1 : function(callback){
        db.scan ({TableName: table,
          ProjectionExpression: "#cityname,ListingKey ",
          FilterExpression: "#cityname = :v_id",
          ExpressionAttributeNames: {
              "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 2,
            Segment: 1//by the worker who has been called
        }, function(err,results){
      if (err) {throw err; }
      var pend = new Date () .getTime ();

      console.log (results);
        })
</code>```

答:
Here is the code using async.parallel.

The number of segments needed to get all 3000 items in one go depends on the size of the items. You may need to calculate the size of the whole data to determine the number of segments. You can keep the maximum number for segments. If the data is not found for the particular segment scan, DynamoDB doesn't throw an error.

```<code>var scanFunctions = [];
var totalSegments = 11;
var segmentNos = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

segmentNos.forEach(function (segmentNo)  {
    console.log(segmentNo);
    var scanFunction = function (callback) {
        console.log("scanning ..." + segmentNo);
        db.scan({
            TableName: tableName,
ProjectionExpression: "#cityname,ListingKey ",
    FilterExpression: "#cityname = :v_id",
    ExpressionAttributeNames: {
    "#cityname": "CityName",
      },
      ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            Segment: segmentNo,
            TotalSegments: totalSegments
        }, function (err, res) {
            if (err) {
                console.log("Error ===>" + JSON.stringify(err));
            } else {
                console.log("SegmentNo ===>" + segmentNo + "   ;Data ===>" + JSON.stringify(res));
            }
            callback(err, res.Items);

        });

    }
    console.log('pushing scan funs to array....');
    scanFunctions.push(scanFunction);
});

async.parallel(scanFunctions, function (err, results) {
    console.log("Results ===>" + JSON.stringify(results, null, 4));
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
By writing this below code i am writing the script again and again to have the added records, without writing the script again and again i want added records in resulting. Using dynamodb and nodejs. Please provide the correct script.

var AWS = require("aws-sdk");
var async = require("async");

AWS.config.update({
      region: "us-west-2",
      endpoint: "2345",
      accessKeyId: "A",
      secretAccessKey:"x"
    });

var db = new AWS.DynamoDB.DocumentClient()

var table = "rets_property_all";
var pstart =new Date () .getTime ();

async.parallel({
        0 : function(callback){
        db.scan ({TableName: table,
        ProjectionExpression: "#cityname,ListingKey ",
        FilterExpression: "#cityname = :v_id",
        ExpressionAttributeNames: {
        "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 2,
            Segment:  0//by the worker who has been called
        },function (err , res) {
            callback (null , res.Items);
        });
            },
            1 : function(callback){
        db.scan ({TableName: table,
          ProjectionExpression: "#cityname,ListingKey ",
          FilterExpression: "#cityname = :v_id",
          ExpressionAttributeNames: {
              "#cityname": "CityName",
          },
          ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            TotalSegments: 2,
            Segment: 1//by the worker who has been called
        }, function(err,results){
      if (err) {throw err; }
      var pend = new Date () .getTime ();

      console.log (results);
        })

Body:
Here is the code using async.parallel.

The number of segments needed to get all 3000 items in one go depends on the size of the items. You may need to calculate the size of the whole data to determine the number of segments. You can keep the maximum number for segments. If the data is not found for the particular segment scan, DynamoDB doesn't throw an error.

var scanFunctions = [];
var totalSegments = 11;
var segmentNos = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

segmentNos.forEach(function (segmentNo)  {
    console.log(segmentNo);
    var scanFunction = function (callback) {
        console.log("scanning ..." + segmentNo);
        db.scan({
            TableName: tableName,
ProjectionExpression: "#cityname,ListingKey ",
    FilterExpression: "#cityname = :v_id",
    ExpressionAttributeNames: {
    "#cityname": "CityName",
      },
      ExpressionAttributeValues: {":v_id" : 'BALTIMORE'},
            Segment: segmentNo,
            TotalSegments: totalSegments
        }, function (err, res) {
            if (err) {
                console.log("Error ===>" + JSON.stringify(err));
            } else {
                console.log("SegmentNo ===>" + segmentNo + "   ;Data ===>" + JSON.stringify(res));
            }
            callback(err, res.Items);

        });

    }
    console.log('pushing scan funs to array....');
    scanFunctions.push(scanFunction);
});

async.parallel(scanFunctions, function (err, results) {
    console.log("Results ===>" + JSON.stringify(results, null, 4));
});


问:
When I insert a file in an input file it shows preview, but how to delete a selected file?
I got this javascript to show image preview when user select the file, it is working.

Case:

- If user select wrong image and delete it then preview do not refresh to 'empty'.

I have no idea how can I do this, already lookd around google and stackoverflow and nothing. Can someone give me a light please?

```<code><img id="image1" width="300px" height="300px"/>
<img id="image2" width="300px" height="300px"/>
<img id="image3" width="300px" height="300px"/>
<img id="image4" width="300px" height="300px"/>

<script>
    document.getElementById("productimage1").onchange = function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById("image1").src = e.target.result;
            };
            reader.readAsDataURL(this.files[0]);
        };
    document.getElementById("productimage2").onchange = function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById("image2").src = e.target.result;
            };
            reader.readAsDataURL(this.files[0]);
        };
    document.getElementById("productimage3").onchange = function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById("image3").src = e.target.result;
            };
            reader.readAsDataURL(this.files[0]);
        };
    document.getElementById("productimage4").onchange = function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById("image4").src = e.target.result;
            };
            reader.readAsDataURL(this.files[0]);
        };
</script>
</code>```

答:
If I get what you want correctly...

You want the image preview to be cleared when user tries to select a new image using the "open file" window. No delete button.

Here is what you should do then:

```<code>// A delete function
$("[id^='product']").on("click",function(){

  // This clears the input value.
  $(this).val("");

  // This resets the preview.
  var imageID = $(this).attr("id").substr(7);
  $("#"+imageID).attr("src","https://placehold.it/300x300");
});
</code>```

See in CodePen

---EDIT

Here is the full code optimized.

```<code>// A delete function
$("[id^='product']").on("click",function(){

  // This clears the input value.
  $(this).val("");

  // This resets the preview.
  var imageID = $(this).attr("id").substr(7);
  $("#"+imageID).attr("src","https://placehold.it/300x300");
});

// The preview function
$("[id^='product']").on("change",function(){
  var imageID = $(this).attr("id").substr(7);

  // Displays a preview im the right div
  var reader = new FileReader();
  reader.onload = function (e) {
    $("#"+imageID).attr("src",e.target.result);
  };
  reader.readAsDataURL(this.files[0]);
});
</code>```

See in CodePen - version #2

Body:
If I get what you want correctly...

You want the image preview to be cleared when user tries to select a new image using the "open file" window. No delete button.

Here is what you should do then:

// A delete function
$("[id^='product']").on("click",function(){

  // This clears the input value.
  $(this).val("");

  // This resets the preview.
  var imageID = $(this).attr("id").substr(7);
  $("#"+imageID).attr("src","https://placehold.it/300x300");
});

See in CodePen

---EDIT

Here is the full code optimized.

// A delete function
$("[id^='product']").on("click",function(){

  // This clears the input value.
  $(this).val("");

  // This resets the preview.
  var imageID = $(this).attr("id").substr(7);
  $("#"+imageID).attr("src","https://placehold.it/300x300");
});

// The preview function
$("[id^='product']").on("change",function(){
  var imageID = $(this).attr("id").substr(7);

  // Displays a preview im the right div
  var reader = new FileReader();
  reader.onload = function (e) {
    $("#"+imageID).attr("src",e.target.result);
  };
  reader.readAsDataURL(this.files[0]);
});

See in CodePen - version #2


问:
PHP code to download CSV file not working
I have the below code, where I generate random numbers and try to download them as a CSV file.

If I try the CSV code snippet alone on a different file it works, but in this code, it just does not work. I do see the random numbers echoed, but it does not download the CSV file.

```<code><?php

$dataarray=array();

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
foreach ($input_array as $line)
{
fputcsv($temp_memory, $line, $delimiter);
}

fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}

for ($i = 0; $i <= 25000; $i++)
{
  $num = (rand(50,110));

  array_push($dataarray,"$num");

  echo "Hearbeat #" .$i . "\t\t ------   " . $num;
  echo "<br>";
}

convert_to_csv($dataarray, 'data_as_csv.csv', ',');

?>
</code>```

答:
Outputting data before sending headers with header() means that header() calls will have no effect. So it is reasonable not to send anything before headers.

As another answer mentioned - second argument to fputcsv must be array, so I changed the call to fputcsv too.

If you want all values to written to csv file with comma as separator - pass $input_array directly to fputcsv.

So, your code can look like:

```<code><?php
$dataarray=array();

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');

// Option 1 - every number will be on a new line
foreach ($input_array as $line)
{
// add `array($line)` not `$line`
fputcsv($temp_memory, array($line), $delimiter);
}

// Option 2 - all numbers will be in
// one line with `$delimiter` as separator
fputcsv($temp_memory, $input_array, $delimiter);

fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}

for ($i = 0; $i <= 25000; $i++)
{
  $num = (rand(50,110));
  array_push($dataarray,"$num");

  // this two lines are nor needed
  //echo "Hearbeat #" .$i . "\t\t ------   " . $num;
  //echo "<br>";
}

convert_to_csv($dataarray, 'data_as_csv.csv', ',');
</code>```

Body:
I have the below code, where I generate random numbers and try to download them as a CSV file.

If I try the CSV code snippet alone on a different file it works, but in this code, it just does not work. I do see the random numbers echoed, but it does not download the CSV file.

<?php

$dataarray=array();

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
foreach ($input_array as $line)
{
fputcsv($temp_memory, $line, $delimiter);
}

fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}

for ($i = 0; $i <= 25000; $i++)
{
  $num = (rand(50,110));

  array_push($dataarray,"$num");

  echo "Hearbeat #" .$i . "\t\t ------   " . $num;
  echo "
";
}

convert_to_csv($dataarray, 'data_as_csv.csv', ',');

?>

Body:
Outputting data before sending headers with header() means that header() calls will have no effect. So it is reasonable not to send anything before headers.

As another answer mentioned - second argument to fputcsv must be array, so I changed the call to fputcsv too.

If you want all values to written to csv file with comma as separator - pass $input_array directly to fputcsv.

So, your code can look like:

<?php
$dataarray=array();

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');

// Option 1 - every number will be on a new line
foreach ($input_array as $line)
{
// add `array($line)` not `$line`
fputcsv($temp_memory, array($line), $delimiter);
}

// Option 2 - all numbers will be in
// one line with `$delimiter` as separator
fputcsv($temp_memory, $input_array, $delimiter);

fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}

for ($i = 0; $i <= 25000; $i++)
{
  $num = (rand(50,110));
  array_push($dataarray,"$num");

  // this two lines are nor needed
  //echo "Hearbeat #" .$i . "\t\t ------   " . $num;
  //echo "<br>";
}

convert_to_csv($dataarray, 'data_as_csv.csv', ',');


问:
Is there way to use PreferenceActivity without storing values in shared preferences
I have an android application that has uses few serializable classes
(I can store and load them in JSON format using Google Gson library and it works like a charm).

Now I want to provide way for user to edit those objects in fashion similar to PreferenceActivity - they contain few strings, ints and doubles and PreferenceScreen just seems ideal for editing them.

Is there a way to 'abuse' PreferenceActivity to provide UI for editing my objects without actually storing data in shared preferences?

For example - if there was some callback to override that is called just before saving data, I could extract data, assemble my object and somehow prevent Android from messing with preferences?

答:
SharedPreferences is an interface, so you should be able to provide your own implementation that stores data however you like.  But the PreferenceManager used by PreferenceFragment only has a setter that takes a file name, not a custom implementation of SharedPreferences.

I looked into the source and found a roundabout way to use your own implementation.  PreferenceFragment uses its hosting Activity as the Context for constructing a PreferenceManager.  PreferenceManager subsequently calls Context#getSharedPreferences(String, int) to get the SharedPreferences that it will use.  Therefore, you can override getSharedPreferences in the activity hosting your PreferenceFragment and return your custom implementation.  Implementing SharedPreferences could be rather complicated since you'll also have to implement SharedPreferences.Editor, but it's doable.  And if there's any chance of your overridden getSharedPreferences being used anywhere else, you should document that it uses a different backing store.

In the Android O preview, there's a new interface called PreferenceDataStore and a new setter in PreferenceManager that takes an instance of that interface.  PreferenceDataStore looks much simpler to implement than SharedPreferences.  But as I write this, most retailers are still selling L and M devices, so who knows when we'll see O.


问:
Grails call application.config value in javascript
How can I call a value set in application config in javascript? I tried using jquery and put below in my javascript but it doesn't work. Is it even do able without jquery? Help please</p>

```<code>console.log("${grailsApplication.config.getProperty('wipTransportUI.rtdService.url', String)}");
</code>```

答:
Your example works for me using Grails 3, I added the following to application.yml:

```<code>wipTransportUI:
    rtdService:
        url: 'aUrl'
</code>```

Then used in javascript in gsp:

```<code><script type="text/javascript">
    console.log( "${grailsApplication.config.getProperty( 'wipTransportUI.rtdService.url', String )}" );
</script>
</code>```

Console:

If you're using Grails 2 you'd access the property differently:

```<code>console.log( "${grailsApplication.config.wipTransportUI.rtdService.url}" );
</code>```

Body:
How can I call a value set in application config in javascript? I tried using jquery and put below in my javascript but it doesn't work. Is it even do able without jquery? Help please

console.log("${grailsApplication.config.getProperty('wipTransportUI.rtdService.url', String)}");

Body:
Your example works for me using Grails 3, I added the following to application.yml:

wipTransportUI:
    rtdService:
        url: 'aUrl'

Then used in javascript in gsp:

<script type="text/javascript">
    console.log( "${grailsApplication.config.getProperty( 'wipTransportUI.rtdService.url', String )}" );
</script>

Console:

If you're using Grails 2 you'd access the property differently:

console.log( "${grailsApplication.config.wipTransportUI.rtdService.url}" );


问:
Horizontal Div Scroll
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
        #container{
            max-width: 938px;
            height: 500px;
            border: 2px solid black;
            margin-left: auto;
            margin-right: auto;
            overflow: scroll;
            /*display: table;*/
        }
        .picsdiv{
            display: table-cell;
            min-width: 286px;
            padding-right: 80px;
            height: 508px;
            border: 2px solid pink;

        }

        .prev, .next {
          cursor: pointer;
          position: absolute;
          top: 250px;
          width: auto;
          margin-top: -22px;
          padding: 16px;
          color: white;
          font-weight: bold;
          font-size: 18px;
          transition: 0.6s ease;
          border-radius: 0 3px 3px 0;
            border: 2px solid pink;
        }

        .next {
          right: 170px;
          border-radius: 3px 0 0 3px;
        }
        .prev{
            left: 170px;
        }

        .prev:hover, .next:hover {
          background-color: rgba(0,0,0,0.8);
        }
    </style></code>```

       ❮
      ❯

```

答: firstly you must close script tag that include jquery file and also open another script tag for your jquery code</p>

Title: Horizontal Div Scroll

Body:
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

       ❮
      ❯


问:
Can I group by an a nested associated entity using Projections in hibernate?
If I have entities like:

```<code>@Entity
public class Person {
   public String name;
   @OneToMany
   public Location location;
}

@Entity
public class Location {
   public String address;
   public String city;
   public String state;
}
</code>```

Say I want to count all of the people in each state. Should I be able to do something like this:

```<code>Criteria criteria = session.createCriteria(Person.class);
criteria.setProjection(Projections.projectionList().
   add(Projections.groupProperty("location.state")).
   add(Projections.count("name")));
List<Object[]> result = criteria.list();
</code>```

I know that exact example won't work because I get an error saying, could not resolve property: location.state of of: Person.  Is there a way to do what I'm trying to do without resorting to HQL?  (The real version of this query is quite dynamic, so the programmatic building of the criteria is very helpful.)

答:
You can make the Location as an association for Person, and then group it there. For instance:

```<code>session.createCriteria(Person.class)
         .add(Projections.count("name"))
       .createCriteria(Location.class)
         .add(Projections.groupProperty("state"))
</code>```

Not tested, but should work :-)

ContentLicense: CC BY-SA 2.5

Body:
If I have entities like:

@Entity
public class Person {
   public String name;
   @OneToMany
   public Location location;
}

@Entity
public class Location {
   public String address;
   public String city;
   public String state;
}

Say I want to count all of the people in each state. Should I be able to do something like this:

Criteria criteria = session.createCriteria(Person.class);
criteria.setProjection(Projections.projectionList().
   add(Projections.groupProperty("location.state")).
   add(Projections.count("name")));
List<Object[]> result = criteria.list();

I know that exact example won't work because I get an error saying, could not resolve property: location.state of of: Person.  Is there a way to do what I'm trying to do without resorting to HQL?  (The real version of this query is quite dynamic, so the programmatic building of the criteria is very helpful.)

Body:
You can make the Location as an association for Person, and then group it there. For instance:

session.createCriteria(Person.class)
         .add(Projections.count("name"))
       .createCriteria(Location.class)
         .add(Projections.groupProperty("state"))

Not tested, but should work :-)


问:
CLIPS deftemplate incorrect slot type
I am very puzzled by CLIPS. I have defined in a .clp file a deftemplate and a rule.

```<code>(deftemplate basic-ch "Basic characteristics template"
    (slot ch-name
        (type SYMBOL)
        (default ?DERIVE)
    )
    (slot score
        (type INTEGER)
        (default 1)
        (range 1 5)
    )
)
(defrule make-ch
    ?get-ch <- (get-ch TRUE)
    =>
    (printout t "Enter ch name" crlf)
    (bind ?name (read))
    (printout t "Enter ch score" crlf)
    (bind ?score (read))
    (assert (basic-ch (ch-name ?name) (score ?score)))
    (retract ?get-ch)
)
</code>```

When i (assert (get-ch TRUE)) and (run), it prompts me for the ch name and score. However, if I enter a string for the score, the string score gets asserted by the rule! For example:

```<code>Enter ch name
hello
Enter ch score
hello
;(basic-ch (ch-name hello)(score hello)) get asserted?!
</code>```

How is this possible? I have defined the score to be INTEGER and even provided the range. How can I stop this?

答:
From Section 11, Constraint Attributes, of the Basic Programming Guide:

Two types of constraint checking are supported: static and dynamic.
  When static constraint checking is enabled, constraint violations are
  checked when function calls and constructs are parsed. This includes
  constraint checking between patterns on the LHS of a rule when
  variables are used in more than one slot. When dynamic constraint
  checking is enabled, newly created data objects (such as deftemplate
  facts and instances) have their slot values checked for constraint
  violations. Essentially, static constraint checking occurs when a
  CLIPS program is loaded and dynamic constraint checking occurs when a
  CLIPS program is running. By default, static constraint checking is
  enabled and dynamic constraint checking is disabled. The default
  behavior can be changed by using the set-static-constraint-checking
  and set-dynamic-constraint-checking functions.

If you enable dynamic constraint checking, you'll get an error when you run your program:

```<code>CLIPS> (set-dynamic-constraint-checking TRUE)
TRUE
CLIPS> (assert (get-ch TRUE))
<Fact-1>
CLIPS> (run)
Enter ch name
hello
Enter ch score
hello

[CSTRNCHK1] Slot value hello found in fact f-2
does not match the allowed types for slot score.
[PRCCODE4] Execution halted during the actions of defrule make-ch.
CLIPS>
</code>```

Because it generates an error, dynamic constraint checking is useful for testing, but not for validating user input while a program is executing. If you want to validate use input, define some utility methods:

```<code>CLIPS>
(defmethod get-integer ((?query STRING))
   (bind ?value FALSE)
   (while (not (integerp ?value))
      (printout t ?query " ")
      (bind ?value (read)))
   ?value)
CLIPS>
(defmethod get-integer ((?query STRING) (?lower INTEGER) (?upper INTEGER))
   (bind ?value FALSE)
   (while (or (not (integerp ?value)) (< ?value ?lower) (> ?value ?upper))
      (printout t ?query " (" ?lower " - " ?upper ") ")
      (bind ?value (read)))
   ?value)
CLIPS> (get-integer "Pick an integer:")
Pick an integer: hello
Pick an integer: 3
3
CLIPS> (get-integer "Pick an integer" 1 5)
Pick an integer (1 - 5) -1
Pick an integer (1 - 5) hello
Pick an integer (1 - 5) 8
Pick an integer (1 - 5) 4
4
CLIPS>
</code>```

Title: CLIPS deftemplate incorrect slot type

Body:
I am very puzzled by CLIPS. I have defined in a .clp file a deftemplate and a rule.

(deftemplate basic-ch "Basic characteristics template"
    (slot ch-name
        (type SYMBOL)
        (default ?DERIVE)
    )
    (slot score
        (type INTEGER)
        (default 1)
        (range 1 5)
    )
)
(defrule make-ch
    ?get-ch <- (get-ch TRUE)
    =>
    (printout t "Enter ch name" crlf)
    (bind ?name (read))
    (printout t "Enter ch score" crlf)
    (bind ?score (read))
    (assert (basic-ch (ch-name ?name) (score ?score)))
    (retract ?get-ch)
)

When i (assert (get-ch TRUE)) and (run), it prompts me for the ch name and score. However, if I enter a string for the score, the string score gets asserted by the rule! For example:

Enter ch name
hello
Enter ch score
hello
;(basic-ch (ch-name hello)(score hello)) get asserted?!

How is this possible? I have defined the score to be INTEGER and even provided the range. How can I stop this?

Body:
From Section 11, Constraint Attributes, of the Basic Programming Guide:

Two types of constraint checking are supported: static and dynamic.
  When static constraint checking is enabled, constraint violations are
  checked when function calls and constructs are parsed. This includes
  constraint checking between patterns on the LHS of a rule when
  variables are used in more than one slot. When dynamic constraint
  checking is enabled, newly created data objects (such as deftemplate
  facts and instances) have their slot values checked for constraint
  violations. Essentially, static constraint checking occurs when a
  CLIPS program is loaded and dynamic constraint checking occurs when a
  CLIPS program is running. By default, static constraint checking is
  enabled and dynamic constraint checking is disabled. The default
  behavior can be changed by using the set-static-constraint-checking
  and set-dynamic-constraint-checking functions.

If you enable dynamic constraint checking, you'll get an error when you run your program:

CLIPS> (set-dynamic-constraint-checking TRUE)
TRUE
CLIPS> (assert (get-ch TRUE))
<Fact-1>
CLIPS> (run)
Enter ch name
hello
Enter ch score
hello

[CSTRNCHK1] Slot value hello found in fact f-2
does not match the allowed types for slot score.
[PRCCODE4] Execution halted during the actions of defrule make-ch.
CLIPS>

Because it generates an error, dynamic constraint checking is useful for testing, but not for validating user input while a program is executing. If you want to validate use input, define some utility methods:

CLIPS>
(defmethod get-integer ((?query STRING))
   (bind ?value FALSE)
   (while (not (integerp ?value))
      (printout t ?query " ")
      (bind ?value (read)))
   ?value)
CLIPS>
(defmethod get-integer ((?query STRING) (?lower INTEGER) (?upper INTEGER))
   (bind ?value FALSE)
   (while (or (not (integerp ?value)) (< ?value ?lower) (> ?value ?upper))
      (printout t ?query " (" ?lower " - " ?upper ") ")
      (bind ?value (read)))
   ?value)
CLIPS> (get-integer "Pick an integer:")
Pick an integer: hello
Pick an integer: 3
3
CLIPS> (get-integer "Pick an integer" 1 5)
Pick an integer (1 - 5) -1
Pick an integer (1 - 5) hello
Pick an integer (1 - 5) 8
Pick an integer (1 - 5) 4
4
CLIPS>


问:
Combine two classes in Java?
I don't know what the right way to ask this but I have two classes I get back from the API that both have name as the thing in common but also have another field that is separate from each other. What is the best way to "combine" them where my User class can get the name but can also get their own variables.

How would my User class look? I'm looking for the User class to have name in-common, the Alien class have alienVariable and the Human class have the humanVariable

My example of two classes

Alien

```<code>@AutoValue
public abstract class Alien implements Parcelable {
    public static Alien create(String alienVariable) {
        return new AutoValue_Alien(alienVariable);
    }

    public static Alien create(String name, String alienVariable) {
        return new AutoValue_Alien(name, alienVariable);
    }

    public static TypeAdapter<Alien> typeAdapter(Gson gson) {
        return new AutoValue_Alien.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("alien_variable")
    public abstract String alienVariable();
}
</code>```

Human

```<code>@AutoValue
public abstract class Human implements Parcelable {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();
}
</code>```

User?

答:
You can do something like the following. BTW, I haven't tried to compile this it's just a scaffold of an idea </p>

```<code>public interface Species implements Parcelable {
    @SerializedName("name")
    String name();
    @Nullable
    String typeVariable();
}

public class Alien implements Species {
    @Override
    public String name() {}

    @Override
    @SerializedName("alien_variable")
    public String alienVariable() {}

    // fill in rest of class
}

public class Human implements Species {
    @Override
    public String name(){}

    @Override
    @SerializedName("human_variable")
    public String humanVariable() {}

    // fill in rest of class
}
</code>```

Title: Combine two classes in Java?

Body:
I don't know what the right way to ask this but I have two classes I get back from the API that both have name as the thing in common but also have another field that is separate from each other. What is the best way to "combine" them where my User class can get the name but can also get their own variables.

How would my User class look? I'm looking for the User class to have name in-common, the Alien class have alienVariable and the Human class have the humanVariable

My example of two classes

Alien

@AutoValue
public abstract class Alien implements Parcelable {
    public static Alien create(String alienVariable) {
        return new AutoValue_Alien(alienVariable);
    }

    public static Alien create(String name, String alienVariable) {
        return new AutoValue_Alien(name, alienVariable);
    }

    public static TypeAdapter<Alien> typeAdapter(Gson gson) {
        return new AutoValue_Alien.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("alien_variable")
    public abstract String alienVariable();
}

Human

@AutoValue
public abstract class Human implements Parcelable {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();
}

User?

Body:
You can do something like the following. BTW, I haven't tried to compile this it's just a scaffold of an idea

public interface Species implements Parcelable {
    @SerializedName("name")
    String name();
    @Nullable
    String typeVariable();
}

public class Alien implements Species {
    @Override
    public String name() {}

    @Override
    @SerializedName("alien_variable")
    public String alienVariable() {}

    // fill in rest of class
}

public class Human implements Species {
    @Override
    public String name(){}

    @Override
    @SerializedName("human_variable")
    public String humanVariable() {}

    // fill in rest of class
}


问:
Reuse connection when sending email with Javamail library
I'm trying to send a lot of email using the JavaMail API and am finding that the slowest part of my code (around 1 second per email) is the following:

```<code>long startSendTime = System.currentTimeMillis();
Transport transport = mailSession.getTransport();
transport.connect();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
long endTime = System.currentTimeMillis();
logger.info("Finished sending message, took: " + (endTime - startSendTime) + "ms");
</code>```

I am guessing this is because every email requires setting up a TCP connection. Is there a way to have a connection pool for email sending? Are there other libraries that are more performant which I could use?

答:
You can take a look at spring boot mail:

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-email.html

Here is an example:
Sending Email via Spring boot "spring-boot-starter-mail"

Body:
I'm trying to send a lot of email using the JavaMail API and am finding that the slowest part of my code (around 1 second per email) is the following:

long startSendTime = System.currentTimeMillis();
Transport transport = mailSession.getTransport();
transport.connect();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
long endTime = System.currentTimeMillis();
logger.info("Finished sending message, took: " + (endTime - startSendTime) + "ms");

I am guessing this is because every email requires setting up a TCP connection. Is there a way to have a connection pool for email sending? Are there other libraries that are more performant which I could use?


问:
Android voice command custom
My question is regarding custom voice commands for Android.

Is there a way to develop an app, not necessarily a UI app, that adds custom voice commands to any Android mobile?

For example, after installing AccuWeather on Android, every time I ask Google Now for the weather, it displays information fetched from the said app.

Did AccuWeather added new voice commands to my phone?

Can any app developed by anyone add custom voice commands to an
Android phone?

Can I write and install an app that, triggered by the voice command
"How is my portfolio?", fetches data from the stock market, returns it
and then be displayed in the same view, the Google Now view?

I Googled all of these concerns but found more questions than answers.

答:
BTW there was a possibility with an XPOSED Module to add custom commands to google search ( and so you can use the voice recognition even with a smart watch connected ), but it stopped working since they updated the google search app.

if you are just doing this for personal use u can still use it with an old version of google search app and this xposed framework module and correct hooks ( they postet the correct hooks for some updated versions of google app  later in the thread , just use the latest one...).

here you go:
https://forum.xda-developers.com/xposed/modules/mod-google-search-api-t2554173

i really hope google will bring out a better voice API than the actual is.

Title: Android voice command custom


问:
passing non tuple to (Int,Int)=>() compiles, why?
Can someone explain why the code below compiles ?

I think it should not compile.

```<code>object RandomExperiments extends App{
  def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
  takeTuple(1,3) // this should not compile !!!
  takeTuple (1,3) // this should not compile !!!
  takeTuple((1,3))
  takeTuple(((1,3)))

  def takeTwoInts(i1:Int,i2:Int)=print (s"$i1 $i2\n")

  takeTwoInts(1,2)

  // takeTwoInts((1,2)) // does not compile , this is expected

}

(1,3) 1
(1,3) 1
(1,3) 1
(1,3) 1
1 2
</code>```

答:
It's known as auto-tupling. The compiler sees that there is no overload available for takeTuple that has two Int arguments, but recognizes that if the arguments can be converted to an (Int, Int) and makes the conversion. If you compile with -Xlint:_, you will see a warning like this:

```<code>scala> takeTuple(1,3)
<console>:12: warning: Adapting argument list by creating a 2-tuple: this may not be what you want.
        signature: takeTuple(t: (Int, Int)): Unit
  given arguments: 1, 3
 after adaptation: takeTuple((1, 3): (Int, Int))
       takeTuple(1,3)
                ^
</code>```

You could use the -Yno-adapted-args flag (recommended) to disable this feature

Body:
Can someone explain why the code below compiles ?

I think it should not compile.

object RandomExperiments extends App{
  def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
  takeTuple(1,3) // this should not compile !!!
  takeTuple (1,3) // this should not compile !!!
  takeTuple((1,3))
  takeTuple(((1,3)))

  def takeTwoInts(i1:Int,i2:Int)=print (s"$i1 $i2\n")

  takeTwoInts(1,2)

  // takeTwoInts((1,2)) // does not compile , this is expected

}

(1,3) 1
(1,3) 1
(1,3) 1
(1,3) 1
1 2

Body:
It's known as auto-tupling. The compiler sees that there is no overload available for takeTuple that has two Int arguments, but recognizes that if the arguments can be converted to an (Int, Int) and makes the conversion. If you compile with -Xlint:_, you will see a warning like this:

scala> takeTuple(1,3)
<console>:12: warning: Adapting argument list by creating a 2-tuple: this may not be what you want.
        signature: takeTuple(t: (Int, Int)): Unit
  given arguments: 1, 3
 after adaptation: takeTuple((1, 3): (Int, Int))
       takeTuple(1,3)
                ^

You could use the -Yno-adapted-args flag (recommended) to disable this feature


问:
Local Variables with Pointer Casting
One of the issues I am having is attempting to cast variables into memory to be accessed at later points.

I have an example code here that works perfectly:

```<code>unsigned int *label = (unsigned int *)malloc(sizeof(unsigned int));
label = (unsigned int * ) 0xFFAAFFAA;
</code>```

Anywhere else in my code I can access this value label, and it will be pointing to 0xFFAAFFAA as its value when I try to print it.

However, if I try to assign from a variable like such:

```<code> //all of this is inside a method.. so any variables declared would be local
    unsigned int localVariable = 0xFFFFFFFF;
      unsigned int *label = (unsigned int *)malloc(sizeof(unsigned int));
      label = &localVariable;
</code>```

The result will be something crazy like: 0x7f252d6b5f00 .. which I am just assuming is some random address in memory. I know this issue is because of a local variable as that operates within a function and is not global. But I can't figure out what the syntax of this would be...

The reason I want to define the local variable is because there is other logic in the function to add and subtract from that variable.. I left it out to keep it minimal

EDIT: so I could do something like this?

```<code> unsigned int localVariable = 0xFFFFFFFF;
  unsigned int *label = (unsigned int *)malloc(sizeof(unsigned int));
  *label = localVariable;
</code>```

答:
It sounds like what you want here is to create a pointer to a variable in a function then have it accessible outside of the function.

The issue with your first example is that you allocate memory and assign its address to label, but then you overwrite the value of label causing you to loose the reference to the memory you just allocated.   You need to dereference the pointer using the * operator to write to the memory address you just allocated.

The second example won't work because you take the address of a local variable, then that variable goes out of scope when the function returns.  So the address becomes invalid.

The below example allocates space, dereferences the pointer just allocated to write to the given address, then the address is returned to the caller.

```<code>unsigned int *func()
{
    // allocate space (don't cast return value of malloc)
    unsigned int *label = malloc(sizeof(unsigned int));
    // dereference pointer and write value to allocated memory
    *label = 0xFFAAFFAA;
    // pass pointer to allocated memory to the calling function
    return label;
}
</code>```

Keep in mind that the calling function will be responsible for calling free on the memory that is returned when it is done using it to avoid a memory leak.

Title: Local Variables with Pointer Casting

Body:
One of the issues I am having is attempting to cast variables into memory to be accessed at later points.

I have an example code here that works perfectly:

unsigned int *label = (unsigned int *)malloc(sizeof(unsigned int));
label = (unsigned int * ) 0xFFAAFFAA;

Anywhere else in my code I can access this value label, and it will be pointing to 0xFFAAFFAA as its value when I try to print it.

However, if I try to assign from a variable like such:

 //all of this is inside a method.. so any variables declared would be local
    unsigned int localVariable = 0xFFFFFFFF;
      unsigned int *label = (unsigned int *)malloc(sizeof(unsigned int));
      label = &localVariable;

The result will be something crazy like: 0x7f252d6b5f00 .. which I am just assuming is some random address in memory. I know this issue is because of a local variable as that operates within a function and is not global. But I can't figure out what the syntax of this would be...

The reason I want to define the local variable is because there is other logic in the function to add and subtract from that variable.. I left it out to keep it minimal

EDIT: so I could do something like this?

 unsigned int localVariable = 0xFFFFFFFF;
  unsigned int *label = (unsigned int *)malloc(sizeof(unsigned int));
  *label = localVariable;

Body:
It sounds like what you want here is to create a pointer to a variable in a function then have it accessible outside of the function.

The issue with your first example is that you allocate memory and assign its address to label, but then you overwrite the value of label causing you to loose the reference to the memory you just allocated.   You need to dereference the pointer using the * operator to write to the memory address you just allocated.

The second example won't work because you take the address of a local variable, then that variable goes out of scope when the function returns.  So the address becomes invalid.

The below example allocates space, dereferences the pointer just allocated to write to the given address, then the address is returned to the caller.

unsigned int *func()
{
    // allocate space (don't cast return value of malloc)
    unsigned int *label = malloc(sizeof(unsigned int));
    // dereference pointer and write value to allocated memory
    *label = 0xFFAAFFAA;
    // pass pointer to allocated memory to the calling function
    return label;
}

Keep in mind that the calling function will be responsible for calling free on the memory that is returned when it is done using it to avoid a memory leak.


问:
How to compare __m128 types?
```<code>__m128 a;
__m128 b;
</code>```

How to code a != b ?

what to use: _mm_cmpneq_ps or _mm_cmpneq_ss ?

How to process the result ?

Can't find adequate docs.

答:
Peter is right!!! Tests against values that are 0.0f can fail under the previous approach.

Please consider this MACRO.
#define ISEQUAL(A, B) _mm_testz_si128(_mm_xor_si128(_mm_castps_si128(A), _mm_castps_si128(B)),

_mm_xor_si128(_mm_castps_si128(A), _mm_castps_si128(B)))

This results in 2 instructions.

Title: How to compare __m128 types?

Body:
__m128 a;
__m128 b;

How to code a != b ?

what to use: _mm_cmpneq_ps or _mm_cmpneq_ss ?

How to process the result ?

Can't find adequate docs.

ContentLicense: CC BY-SA 4.0


问:
Does multipart/x-mixed-replace wait for client requests?
I'm trying to figure out if it's possible to slow down the server when it's sending multipart/xmixed-replace responses.  I want my client to try to rate limit a motion jpeg stream.  I've found a lot of documentation about what the server sends in an HTTP response but nothing about what the client sends.

What does the client send, if anything, after each part in a multipart/x-mixed-replace response?  If it doesn't send anything, does the server just keep piling on the parts?

答:
Actually I think the multipart thing is a red herring because the concept of multipart is just to delineate content types within the same message body. So from a server perspective (in terms of the rate at which content is sent) it is not really different from sending a single big chunk of data.

So, I am wondering if you can the Range header to only request a specific range - one "part" at a time.

Start counting bytes from the end of the response headers. When you reach the end of the first part, note the number of bytes read and close the connection. Send a request for
the same document but specify the starting Range as the bytes at the end of chunk. Again, read the response, when you reach the end of the part, add the current response bytes to the previous, close the connection and repeat ad nauseam...

Haven't tried it, but sounds like it would work provided the server supported range headers and provided you were able to do some patching on the client side.

Might be easier to write a client-side proxy that rate limits by dropping packets ...

OwnerDisplayName: Anshu


问:
Trying to update a dataframe
I have a dataframe (df) which looks like:

```<code>0   1                   2                       3
0   BBG.apples.S        BBG.XNGS.bananas.S      0
1   BBG.apples.S        BBG.XNGS.oranges.S      0
2   BBG.apples.S        BBG.XNGS.pairs.S        0
3   BBG.apples.S        BBG.XNGS.mango.S        0
4   BBG.apples.S        BBG.XNYS.mango.S        0
5   BBG.XNGS.bananas.S  BBG.XNGS.oranges.S      0
6   BBG.XNGS.bananas.S  BBG.XNGS.pairs.S        0
7   BBG.XNGS.bananas.S  BBG.XNGS.kiwi.S         0
8   BBG.XNGS.oranges.S  BBG.XNGS.pairs.S        0
9   BBG.XNGS.oranges.S  BBG.XNGS.kiwi.S         0
10  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
11  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
12  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
13  BBG.XNGS.peaches.S  BBG.XNGS.kiwi.S         0
</code>```

I am trying to update a value (first row, third column) in the dataframe using:

```<code>for index, row in df.iterrows():

        status = row[3]

        if int(status) == 0:

            df[index]['3'] = 1
</code>```

but when I print the dataframe out it remains unchanged.

What am I doing wrong?

答:
Replace your last line by:

```<code>df.at[index,'3'] = 1
</code>```

Obviously as mentioned by others you're better off using a vectorized expression instead of iterating, especially for large dataframes.

Title: Trying to update a dataframe

Body:
I have a dataframe (df) which looks like:

0   1                   2                       3
0   BBG.apples.S        BBG.XNGS.bananas.S      0
1   BBG.apples.S        BBG.XNGS.oranges.S      0
2   BBG.apples.S        BBG.XNGS.pairs.S        0
3   BBG.apples.S        BBG.XNGS.mango.S        0
4   BBG.apples.S        BBG.XNYS.mango.S        0
5   BBG.XNGS.bananas.S  BBG.XNGS.oranges.S      0
6   BBG.XNGS.bananas.S  BBG.XNGS.pairs.S        0
7   BBG.XNGS.bananas.S  BBG.XNGS.kiwi.S         0
8   BBG.XNGS.oranges.S  BBG.XNGS.pairs.S        0
9   BBG.XNGS.oranges.S  BBG.XNGS.kiwi.S         0
10  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
11  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
12  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
13  BBG.XNGS.peaches.S  BBG.XNGS.kiwi.S         0

I am trying to update a value (first row, third column) in the dataframe using:

for index, row in df.iterrows():

        status = row[3]

        if int(status) == 0:

            df[index]['3'] = 1

but when I print the dataframe out it remains unchanged.

What am I doing wrong?

Body:
Replace your last line by:

df.at[index,'3'] = 1

Obviously as mentioned by others you're better off using a vectorized expression instead of iterating, especially for large dataframes.


问:
Assigning and reading multidimensional arrays in Python
I'm stumped.

```<code>for a in range(0,500): #500 is a highly variable number but using it for example purposes
    b = findall(r'<(.*?)>', d) # d will return a highly number variable number of matches could be anywhere from 45-10000
    c.append([b])
print(c[0][1])
</code>```

This returns the error because everything from 'b' goes into c[0][0].  I can understand this.  The question is how do I split 'b' apart so I can put it into c so I can

```<code>print(c[0][234])
</code>```

and get it give me back the 235, err element 234 of the 1, err 0, line?

This is a situation like I said above where the number of times going through 'b' will be variable, at least for right now until I get the entire file prepped I can only that 'b' in the end will be way north of 10,000 and probably closer to 100,000 by the time I have all the data collection finished.  The number of elements that are stored can and  will be highly variable depending on the file that they come from.  They are all coming from a csv file but I'm hoping to not to deal with adding in any 'complexity' by going out and having to deal with the csv module...since I've never used it before and that will probably just lead to more questions.

I have tried something similiar to...different variables naturally so things would be appropriately matched up

```<code>d = list(zip(*(e.split(',') for e in b)))
</code>```

all this has did is split on each and every letter versus on the comma.

答:
Your error is coming from the square brackets you have in c.append([b]). The brackets create an extra list that contains the list b. So rather than a two dimensional data structure, you're ending up with three dimensions. Your indexing fails because c[0][1] is trying to get a second value from the middle list (which only ever has one item in it).

You might get what you want with c[0][0][1] instead. But you probably don't actually want that extra level in your data structure. You can avoid creating it by using: c.append(b)

Body:
I'm stumped.

for a in range(0,500): #500 is a highly variable number but using it for example purposes
    b = findall(r'<(.*?)>', d) # d will return a highly number variable number of matches could be anywhere from 45-10000
    c.append([b])
print(c[0][1])

This returns the error because everything from 'b' goes into c[0][0].  I can understand this.  The question is how do I split 'b' apart so I can put it into c so I can

print(c[0][234])

and get it give me back the 235, err element 234 of the 1, err 0, line?

This is a situation like I said above where the number of times going through 'b' will be variable, at least for right now until I get the entire file prepped I can only that 'b' in the end will be way north of 10,000 and probably closer to 100,000 by the time I have all the data collection finished.  The number of elements that are stored can and  will be highly variable depending on the file that they come from.  They are all coming from a csv file but I'm hoping to not to deal with adding in any 'complexity' by going out and having to deal with the csv module...since I've never used it before and that will probably just lead to more questions.

I have tried something similiar to...different variables naturally so things would be appropriately matched up

d = list(zip(*(e.split(',') for e in b)))

all this has did is split on each and every letter versus on the comma.


问:
Android application makes Touchwiz crash
I have i huge problem. When i install my application in usb debugging mode on my Samsung Galaxy Tab 3 with JELLY_BEAN android versions its crash Touchwiz and i cant do anything on my device. Its strange becouse on Genymotion virtual device its behave well.

screenshot here: screenshot

This is my laucher activity:

```<code>public class ProjectActivity extends FragmentActivity {

private boolean hasTwoPanes;
private String TAG = "ProjectActivity";
private int parent_id = 0;
private long filter_id = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.acitivity_projects_list);
    getActionBar().setTitle(R.string.projects);

    if(savedInstanceState == null)
        newFragment(parent_id);
    else {
        parent_id = savedInstanceState.getInt("parent_id");
        filter_id = savedInstanceState.getLong("filter_id");
    }
}

public void newFragment(int parent_id){

    Bundle state = new Bundle();
    state.putInt("parent_id", parent_id);
    ProjectsListFragment list_fragment = new ProjectsListFragment();
    this.parent_id = parent_id;
    list_fragment.parent_id = parent_id;
    list_fragment.setArguments(state);

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.replace(R.id.list, list_fragment, "" + parent_id);
    transaction.addToBackStack("" + parent_id);
    transaction.commit();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("parent_id", parent_id);
    outState.putLong("filter_id", filter_id);
}

@Override
public void onBackPressed() {
    FragmentManager manager = getFragmentManager();

    if(manager.getBackStackEntryCount() < 2){
        finish();
        return;
    }
    manager.popBackStackImmediate();
}

@Override
protected void onResume() {
    super.onResume();

    FragmentManager manager = getFragmentManager();
    setFilter(filter_id, (ProjectsListFragment) manager.findFragmentByTag(manager.getBackStackEntryAt(manager.getBackStackEntryCount() - 1).getName()));
}

@Override
protected void onPause() {
    super.onPause();
    DatabaseHelper.getDatabase(ProjectActivity.this).close();
}

protected void setFilter(long id, ProjectsListFragment list_fragment) {

    SQLiteDatabase mDatabase = DatabaseHelper.getDatabase(ProjectActivity.this);
    ((ProjectsListAdapter)list_fragment.getListAdapter()).changeCursor(DatabaseManager.getProjectsCursor(mDatabase, list_fragment.parent_id, (int)id));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.project_action_bar, menu);

    menu.findItem(R.id.new_project).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            startActivity(new Intent(ProjectActivity.this, NewProjectActivity.class));
            return false;
        }
    });

    menu.findItem(R.id.new_sub_unit).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            if(getFragmentManager().getBackStackEntryCount() == 1)
                startActivity(new Intent(ProjectActivity.this, NewProjectActivity.class));
            else{
                Intent intent = new Intent(ProjectActivity.this, NewSubunitActivity.class);

                intent.putExtra("parent_id", parent_id);
                startActivityForResult(intent, NewSubunitActivity.ADD_SUB_UNITS);
            }
            return false;
        }
    });

    menu.findItem(R.id.menu_projects).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            startActivity(new Intent(ProjectActivity.this, ProjectActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
            return false;
        }
    });

    menu.findItem(R.id.menu_filter).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            View view = LayoutInflater.from(ProjectActivity.this).inflate(R.layout.simple_list_dialog, null);
            final ListView list = (ListView)view.findViewById(R.id.listView1);
            final SimpleDialogListAdapter adapter = new SimpleDialogListAdapter(ProjectActivity.this, DatabaseManager.getStatusCursor(DatabaseHelper.getDatabase(ProjectActivity.this)), SimpleDialogListAdapter.STATUS_FILTER);

            View header = LayoutInflater.from(ProjectActivity.this).inflate(R.layout.filter_row, null);
            ((TextView)header.findViewById(R.id.name_edit_txt)).setText("Default");
            ((TextView)header.findViewById(R.id.color_btn)).setBackgroundColor(getResources().getColor(R.color.white));
            list.addHeaderView(header);
            list.setAdapter(adapter);

            AlertDialog.Builder builder = new AlertDialog.Builder(ProjectActivity.this);
            builder.setTitle(R.string.filter);
            builder.setView(view);
            final AlertDialog filter_dialog = builder.create();

            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int position, long id) {
                    position--;

                    FragmentManager manager = getFragmentManager();
                    ProjectsListFragment list_fragment = (ProjectsListFragment) manager.findFragmentByTag(manager.getBackStackEntryAt(manager.getBackStackEntryCount() - 1).getName());

                    if(position >= 0) {
                        setFilter(filter_id = id, list_fragment);
                    }
                    else {
                        setFilter(filter_id = -1, list_fragment);
                    }

                    ((ProjectsListAdapter)list_fragment.getListAdapter()).notifyDataSetChanged();
                    filter_dialog.dismiss();
                }
            });

            filter_dialog.show();

            return false;
        }
    });
    return true;
}
</code>```

}

```<code>public class ProjectsListFragment extends ListFragment {

private String TAG = "ProjectsListFragment";
public View header;
public int parent_id = 0;

public ProjectsListFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
};

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);

    if(getArguments() != null)
        parent_id = getArguments().getInt("parent_id");

    header = LayoutInflater.from(getActivity()).inflate(R.layout.project_list_header, null);
    ((TextView)header.findViewById(R.id.header_txt)).setText(DatabaseManager.getProjectPath(DatabaseHelper.getDatabase(getActivity()), parent_id));
    setListAdapter(null);
    getListView().addHeaderView(header);

    setListAdapter(new ProjectsListAdapter(getActivity(), parent_id, 0));
}

@Override
public void onListItemClick(ListView list, View view, int position, long id) {
    super.onListItemClick(list, view, position, id);

    if(position == 0)
        return;

    Bundle state = new Bundle();
    parent_id = ((Cursor)getListAdapter().getItem(position)).getInt(0);
    state.putInt("parent_id", parent_id);
    ((ProjectActivity)getActivity()).newFragment(parent_id);
}
</code>```

}

```<code>public class ProjectsListAdapter extends CursorAdapter{

private Activity mActivity;
private LayoutInflater mInflater;
private String TAG = "ProjectsListAdapter";
private SimpleDateFormat simple_format;

public ProjectsListAdapter(Activity mContext, int parent_id, int flags) {
    super(mContext, DatabaseManager.getProjectsCursor(DatabaseHelper.getDatabase(mContext), parent_id, 0), flags);
    this.mActivity = mContext;
    mInflater = LayoutInflater.from(mContext);
    this.simple_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
}

@Override
public void bindView(final View row, final Context mContext, final Cursor mCursor){

    TextView main_txt = (TextView) row.findViewById(R.id.main_txt);
    TextView mod_txt = (TextView) row.findViewById(R.id.sub_txt);
    //TextView sub_txt = (TextView) row.findViewById(R.id.sub_txt);
    Button status_btn = (Button) row.findViewById(R.id.status_btn);
    ImageButton options_btn = (ImageButton) row.findViewById(R.id.options_btn);

    final int index = mCursor.getInt(0);

    options_btn.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(final View v) {
            row.setBackgroundColor(mContext.getResources().getColor(R.color.light_grey));
            rotate(0, 180, v);

            Point point = new Point();
            mActivity.getWindowManager().getDefaultDisplay().getSize(point);

            Dialog dialog = Dialogs.getProjectSpinnerDialog(mContext, index, point.x);
            dialog.setOnDismissListener(new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    rotate(180, 360, v);
                    changeCursor(DatabaseManager.getProjectsCursor(DatabaseHelper.getDatabase(mContext), mCursor.getInt(1), 0));
                    notifyDataSetChanged();
                    row.setBackgroundColor(Color.WHITE);
                }
            });

            dialog.show();
        }
    });

    main_txt.setText(mCursor.getString(2));

    mod_txt.setText(simple_format.format(new Date(mCursor.getLong(8))).toString());
    //sub_txt.setText(mCursor.getFloat(3) + "%");
    status_btn.setText(mCursor.getString(5));

    int color = mCursor.getInt(7);

    if(color == 0)
        color = -1;

    int gradient_start = Color.argb(133, Color.red(color), Color.green(color), Color.blue(color));
    int gradient_end = Color.argb(230, Color.red(color), Color.green(color), Color.blue(color));
    GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.BL_TR, new int[] {gradient_start, gradient_end});
    gd.setCornerRadius(0f);
    row.setBackground(gd);

}

@Override
public Object getItem(int position) {
    return super.getItem(position - 1);
}

@Override
public View newView(Context mContext, Cursor mCursor, ViewGroup mGroup) {
    View row = mInflater.inflate(R.layout.projects_row, null);
    bindView(row, mContext, mCursor);
    return row;
}

public static void rotate(float from_degree, float to_degree, View view) {
    final RotateAnimation rotateAnim = new RotateAnimation(from_degree, to_degree,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);

    rotateAnim.setDuration(500);
    rotateAnim.setFillAfter(true);
    view.startAnimation(rotateAnim);
}
</code>```

}

```<code>06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(1) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(30) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(4) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(3) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(4) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(6) returned 0
06-15 22:02:55.242: D/skia(25588): --- SkImageDecoder::Factory returned null
06-15 22:02:55.242: W/PackageManager(25588): Failure retrieving icon 0x7f02000a in package com.holubowski.projectmanager
06-15 22:02:55.242: W/PackageManager(25588): java.lang.NullPointerException
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ApplicationPackageManager.putCachedIcon(ApplicationPackageManager.java:904)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ApplicationPackageManager.getDrawable(ApplicationPackageManager.java:661)
06-15 22:02:55.242: W/PackageManager(25588):    at android.content.pm.PackageItemInfo.loadIcon(PackageItemInfo.java:151)
06-15 22:02:55.242: W/PackageManager(25588):    at android.content.pm.ComponentInfo.loadDefaultIcon(ComponentInfo.java:167)
06-15 22:02:55.242: W/PackageManager(25588):    at android.content.pm.PackageItemInfo.loadIcon(PackageItemInfo.java:156)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ApplicationPackageManager.getActivityIcon(ApplicationPackageManager.java:681)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.widget.ActionBarView.<init>(ActionBarView.java:252)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Constructor.constructNative(Native Method)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.createView(LayoutInflater.java:593)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:693)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:3298)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:3358)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:314)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.Activity.setContentView(Activity.java:1920)
06-15 22:02:55.242: W/PackageManager(25588):    at com.holubowski.activitys.ProjectActivity.onCreate(ProjectActivity.java:47)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.Activity.performCreate(Activity.java:5185)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.access$700(ActivityThread.java:146)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
06-15 22:02:55.242: W/PackageManager(25588):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 22:02:55.242: W/PackageManager(25588):    at android.os.Looper.loop(Looper.java:137)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.main(ActivityThread.java:4949)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Method.invokeNative(Native Method)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Method.invoke(Method.java:511)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
06-15 22:02:55.242: W/PackageManager(25588):    at dalvik.system.NativeStart.main(Native Method)
06-15 22:02:55.304: D/AbsListView(25588): Get MotionRecognitionManager
06-15 22:02:55.500: D/libEGL(25588): loaded /system/lib/egl/libEGL_MRVL.so
06-15 22:02:55.507: D/libEGL(25588): loaded /system/lib/egl/libGLESv1_CM_MRVL.so
06-15 22:02:55.523: D/libEGL(25588): loaded /system/lib/egl/libGLESv2_MRVL.so
06-15 22:02:55.539: D/GC(25588): <tid=25588> OES20 ===> GC Version   : GC Ver-988-JB-R4-RC2-GC20
06-15 22:02:55.562: D/OpenGLRenderer(25588): Enabling debug mode 0
06-15 22:02:55.671: D/dalvikvm(25588): GC_CONCURRENT freed 222K, 14% free 7585K/8775K, paused 12ms+2ms, total 50ms
</code>```

Found reason and fixed it!

For anyone who have similar problem, in my case the problem makes a lauch icon, I dont know why, but its seems to been corrupted and makes nullpointer exception when app starts, and then touchwiz on normal (not debugg mode) started freaking out.
To fix it just deleted this png and puts new.

答:
Add the launcher icon (png, 32bit) with appropriate size in each of the following folders:

- mdpi: 48x48

- hdpi: 72x72

- xhdpi: 96x96

- xxhdpi: 144x144

- xxxhdpi: 192x192

This stops Samsung's touchwiz home crashing

Body:
I have i huge problem. When i install my application in usb debugging mode on my Samsung Galaxy Tab 3 with JELLY_BEAN android versions its crash Touchwiz and i cant do anything on my device. Its strange becouse on Genymotion virtual device its behave well.

screenshot here: screenshot

This is my laucher activity:

public class ProjectActivity extends FragmentActivity {

private boolean hasTwoPanes;
private String TAG = "ProjectActivity";
private int parent_id = 0;
private long filter_id = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.acitivity_projects_list);
    getActionBar().setTitle(R.string.projects);

    if(savedInstanceState == null)
        newFragment(parent_id);
    else {
        parent_id = savedInstanceState.getInt("parent_id");
        filter_id = savedInstanceState.getLong("filter_id");
    }
}

public void newFragment(int parent_id){

    Bundle state = new Bundle();
    state.putInt("parent_id", parent_id);
    ProjectsListFragment list_fragment = new ProjectsListFragment();
    this.parent_id = parent_id;
    list_fragment.parent_id = parent_id;
    list_fragment.setArguments(state);

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.replace(R.id.list, list_fragment, "" + parent_id);
    transaction.addToBackStack("" + parent_id);
    transaction.commit();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("parent_id", parent_id);
    outState.putLong("filter_id", filter_id);
}

@Override
public void onBackPressed() {
    FragmentManager manager = getFragmentManager();

    if(manager.getBackStackEntryCount() < 2){
        finish();
        return;
    }
    manager.popBackStackImmediate();
}

@Override
protected void onResume() {
    super.onResume();

    FragmentManager manager = getFragmentManager();
    setFilter(filter_id, (ProjectsListFragment) manager.findFragmentByTag(manager.getBackStackEntryAt(manager.getBackStackEntryCount() - 1).getName()));
}

@Override
protected void onPause() {
    super.onPause();
    DatabaseHelper.getDatabase(ProjectActivity.this).close();
}

protected void setFilter(long id, ProjectsListFragment list_fragment) {

    SQLiteDatabase mDatabase = DatabaseHelper.getDatabase(ProjectActivity.this);
    ((ProjectsListAdapter)list_fragment.getListAdapter()).changeCursor(DatabaseManager.getProjectsCursor(mDatabase, list_fragment.parent_id, (int)id));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.project_action_bar, menu);

    menu.findItem(R.id.new_project).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            startActivity(new Intent(ProjectActivity.this, NewProjectActivity.class));
            return false;
        }
    });

    menu.findItem(R.id.new_sub_unit).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            if(getFragmentManager().getBackStackEntryCount() == 1)
                startActivity(new Intent(ProjectActivity.this, NewProjectActivity.class));
            else{
                Intent intent = new Intent(ProjectActivity.this, NewSubunitActivity.class);

                intent.putExtra("parent_id", parent_id);
                startActivityForResult(intent, NewSubunitActivity.ADD_SUB_UNITS);
            }
            return false;
        }
    });

    menu.findItem(R.id.menu_projects).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            startActivity(new Intent(ProjectActivity.this, ProjectActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
            return false;
        }
    });

    menu.findItem(R.id.menu_filter).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            View view = LayoutInflater.from(ProjectActivity.this).inflate(R.layout.simple_list_dialog, null);
            final ListView list = (ListView)view.findViewById(R.id.listView1);
            final SimpleDialogListAdapter adapter = new SimpleDialogListAdapter(ProjectActivity.this, DatabaseManager.getStatusCursor(DatabaseHelper.getDatabase(ProjectActivity.this)), SimpleDialogListAdapter.STATUS_FILTER);

            View header = LayoutInflater.from(ProjectActivity.this).inflate(R.layout.filter_row, null);
            ((TextView)header.findViewById(R.id.name_edit_txt)).setText("Default");
            ((TextView)header.findViewById(R.id.color_btn)).setBackgroundColor(getResources().getColor(R.color.white));
            list.addHeaderView(header);
            list.setAdapter(adapter);

            AlertDialog.Builder builder = new AlertDialog.Builder(ProjectActivity.this);
            builder.setTitle(R.string.filter);
            builder.setView(view);
            final AlertDialog filter_dialog = builder.create();

            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int position, long id) {
                    position--;

                    FragmentManager manager = getFragmentManager();
                    ProjectsListFragment list_fragment = (ProjectsListFragment) manager.findFragmentByTag(manager.getBackStackEntryAt(manager.getBackStackEntryCount() - 1).getName());

                    if(position >= 0) {
                        setFilter(filter_id = id, list_fragment);
                    }
                    else {
                        setFilter(filter_id = -1, list_fragment);
                    }

                    ((ProjectsListAdapter)list_fragment.getListAdapter()).notifyDataSetChanged();
                    filter_dialog.dismiss();
                }
            });

            filter_dialog.show();

            return false;
        }
    });
    return true;
}

}

public class ProjectsListFragment extends ListFragment {

private String TAG = "ProjectsListFragment";
public View header;
public int parent_id = 0;

public ProjectsListFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
};

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);

    if(getArguments() != null)
        parent_id = getArguments().getInt("parent_id");

    header = LayoutInflater.from(getActivity()).inflate(R.layout.project_list_header, null);
    ((TextView)header.findViewById(R.id.header_txt)).setText(DatabaseManager.getProjectPath(DatabaseHelper.getDatabase(getActivity()), parent_id));
    setListAdapter(null);
    getListView().addHeaderView(header);

    setListAdapter(new ProjectsListAdapter(getActivity(), parent_id, 0));
}

@Override
public void onListItemClick(ListView list, View view, int position, long id) {
    super.onListItemClick(list, view, position, id);

    if(position == 0)
        return;

    Bundle state = new Bundle();
    parent_id = ((Cursor)getListAdapter().getItem(position)).getInt(0);
    state.putInt("parent_id", parent_id);
    ((ProjectActivity)getActivity()).newFragment(parent_id);
}

}

public class ProjectsListAdapter extends CursorAdapter{

private Activity mActivity;
private LayoutInflater mInflater;
private String TAG = "ProjectsListAdapter";
private SimpleDateFormat simple_format;

public ProjectsListAdapter(Activity mContext, int parent_id, int flags) {
    super(mContext, DatabaseManager.getProjectsCursor(DatabaseHelper.getDatabase(mContext), parent_id, 0), flags);
    this.mActivity = mContext;
    mInflater = LayoutInflater.from(mContext);
    this.simple_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
}

@Override
public void bindView(final View row, final Context mContext, final Cursor mCursor){

    TextView main_txt = (TextView) row.findViewById(R.id.main_txt);
    TextView mod_txt = (TextView) row.findViewById(R.id.sub_txt);
    //TextView sub_txt = (TextView) row.findViewById(R.id.sub_txt);
    Button status_btn = (Button) row.findViewById(R.id.status_btn);
    ImageButton options_btn = (ImageButton) row.findViewById(R.id.options_btn);

    final int index = mCursor.getInt(0);

    options_btn.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(final View v) {
            row.setBackgroundColor(mContext.getResources().getColor(R.color.light_grey));
            rotate(0, 180, v);

            Point point = new Point();
            mActivity.getWindowManager().getDefaultDisplay().getSize(point);

            Dialog dialog = Dialogs.getProjectSpinnerDialog(mContext, index, point.x);
            dialog.setOnDismissListener(new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    rotate(180, 360, v);
                    changeCursor(DatabaseManager.getProjectsCursor(DatabaseHelper.getDatabase(mContext), mCursor.getInt(1), 0));
                    notifyDataSetChanged();
                    row.setBackgroundColor(Color.WHITE);
                }
            });

            dialog.show();
        }
    });

    main_txt.setText(mCursor.getString(2));

    mod_txt.setText(simple_format.format(new Date(mCursor.getLong(8))).toString());
    //sub_txt.setText(mCursor.getFloat(3) + "%");
    status_btn.setText(mCursor.getString(5));

    int color = mCursor.getInt(7);

    if(color == 0)
        color = -1;

    int gradient_start = Color.argb(133, Color.red(color), Color.green(color), Color.blue(color));
    int gradient_end = Color.argb(230, Color.red(color), Color.green(color), Color.blue(color));
    GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.BL_TR, new int[] {gradient_start, gradient_end});
    gd.setCornerRadius(0f);
    row.setBackground(gd);

}

@Override
public Object getItem(int position) {
    return super.getItem(position - 1);
}

@Override
public View newView(Context mContext, Cursor mCursor, ViewGroup mGroup) {
    View row = mInflater.inflate(R.layout.projects_row, null);
    bindView(row, mContext, mCursor);
    return row;
}

public static void rotate(float from_degree, float to_degree, View view) {
    final RotateAnimation rotateAnim = new RotateAnimation(from_degree, to_degree,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);

    rotateAnim.setDuration(500);
    rotateAnim.setFillAfter(true);
    view.startAnimation(rotateAnim);
}

}

06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(1) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(30) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(4) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(3) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(4) returned 0
06-15 22:02:55.242: D/skia(25588): ---- fAsset->read(6) returned 0
06-15 22:02:55.242: D/skia(25588): --- SkImageDecoder::Factory returned null
06-15 22:02:55.242: W/PackageManager(25588): Failure retrieving icon 0x7f02000a in package com.holubowski.projectmanager
06-15 22:02:55.242: W/PackageManager(25588): java.lang.NullPointerException
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ApplicationPackageManager.putCachedIcon(ApplicationPackageManager.java:904)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ApplicationPackageManager.getDrawable(ApplicationPackageManager.java:661)
06-15 22:02:55.242: W/PackageManager(25588):    at android.content.pm.PackageItemInfo.loadIcon(PackageItemInfo.java:151)
06-15 22:02:55.242: W/PackageManager(25588):    at android.content.pm.ComponentInfo.loadDefaultIcon(ComponentInfo.java:167)
06-15 22:02:55.242: W/PackageManager(25588):    at android.content.pm.PackageItemInfo.loadIcon(PackageItemInfo.java:156)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ApplicationPackageManager.getActivityIcon(ApplicationPackageManager.java:681)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.widget.ActionBarView.<init>(ActionBarView.java:252)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Constructor.constructNative(Native Method)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.createView(LayoutInflater.java:593)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:693)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:760)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
06-15 22:02:55.242: W/PackageManager(25588):    at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:3298)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:3358)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:314)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.Activity.setContentView(Activity.java:1920)
06-15 22:02:55.242: W/PackageManager(25588):    at com.holubowski.activitys.ProjectActivity.onCreate(ProjectActivity.java:47)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.Activity.performCreate(Activity.java:5185)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.access$700(ActivityThread.java:146)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
06-15 22:02:55.242: W/PackageManager(25588):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 22:02:55.242: W/PackageManager(25588):    at android.os.Looper.loop(Looper.java:137)
06-15 22:02:55.242: W/PackageManager(25588):    at android.app.ActivityThread.main(ActivityThread.java:4949)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Method.invokeNative(Native Method)
06-15 22:02:55.242: W/PackageManager(25588):    at java.lang.reflect.Method.invoke(Method.java:511)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
06-15 22:02:55.242: W/PackageManager(25588):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
06-15 22:02:55.242: W/PackageManager(25588):    at dalvik.system.NativeStart.main(Native Method)
06-15 22:02:55.304: D/AbsListView(25588): Get MotionRecognitionManager
06-15 22:02:55.500: D/libEGL(25588): loaded /system/lib/egl/libEGL_MRVL.so
06-15 22:02:55.507: D/libEGL(25588): loaded /system/lib/egl/libGLESv1_CM_MRVL.so
06-15 22:02:55.523: D/libEGL(25588): loaded /system/lib/egl/libGLESv2_MRVL.so
06-15 22:02:55.539: D/GC(25588): <tid=25588> OES20 ===> GC Version   : GC Ver-988-JB-R4-RC2-GC20
06-15 22:02:55.562: D/OpenGLRenderer(25588): Enabling debug mode 0
06-15 22:02:55.671: D/dalvikvm(25588): GC_CONCURRENT freed 222K, 14% free 7585K/8775K, paused 12ms+2ms, total 50ms

Found reason and fixed it!

For anyone who have similar problem, in my case the problem makes a lauch icon, I dont know why, but its seems to been corrupted and makes nullpointer exception when app starts, and then touchwiz on normal (not debugg mode) started freaking out.
To fix it just deleted this png and puts new.


问:
unexpected symbol near '<='
It would be so wonderful if it would tell me what the unexpected symbol is but alas it doesn't. Can someone please advice me what is wrong with this:

```<code>for i = 1, 100 do
if i <= 3 then
local rowMenu = 1
elseif <= 6 then
local rowMenu = 2
elseif <= 9 then
local rowMenu = 3
elseif <= 12 then
local rowMenu = 4
elseif <= 15 then
local rowMenu = 5
elseif <= 18 then
local rowMenu = 6
elseif <= 21 then
local rowMenu = 7
elseif <= 24 then
local rowMenu = 8
end
end
</code>```

I plan on calculated the placement of objects within the loop - its not complete - but I don't understand why this shouldnt work.

Thank you.

答:
The complier is telling you that after seeing elseif it expected something that starts an expression but it found <=, which doesn't.

You need to mention i explicitly in all tests:

```<code>elseif i <= 6 then
</code>```

Note that these chains of ifs can be replaced by

```<code>rowMenu = 3*math.ceil(i/3)
</code>```

or

```<code>rowMenu = 3*((i//3)+(i*i)%3)
</code>```

Title: unexpected symbol near '<='

Body:
It would be so wonderful if it would tell me what the unexpected symbol is but alas it doesn't. Can someone please advice me what is wrong with this:

for i = 1, 100 do
if i <= 3 then
local rowMenu = 1
elseif <= 6 then
local rowMenu = 2
elseif <= 9 then
local rowMenu = 3
elseif <= 12 then
local rowMenu = 4
elseif <= 15 then
local rowMenu = 5
elseif <= 18 then
local rowMenu = 6
elseif <= 21 then
local rowMenu = 7
elseif <= 24 then
local rowMenu = 8
end
end

I plan on calculated the placement of objects within the loop - its not complete - but I don't understand why this shouldnt work.

Thank you.

Body:
The complier is telling you that after seeing elseif it expected something that starts an expression but it found <=, which doesn't.

You need to mention i explicitly in all tests:

elseif i <= 6 then

Note that these chains of ifs can be replaced by

rowMenu = 3*math.ceil(i/3)

or

rowMenu = 3*((i//3)+(i*i)%3)


问:
Rails Order Model By Nested Attributes in JSONB field
I have a Campaign model that has a conversion rate listed like this:

campaign.quota_data["raw_quota_data"][0]["Conversion"] = 33

I'd like to do something like

```<code>Campaign.all.order(quota_data["raw_quota_data"][0]["Conversion"])
</code>```

What's the best way to accomplish this?

Edit: example of what the quota_data data structure looks like:

```<code>{"raw_quota_data"=>
  [
    {"QuotaCPI"=>1.5, "Questions"=>nil, "Conversion"=>0, "SurveyQuotaID"=>4205891, "SurveyQuotaType"=>"Total", "OverQuotaThreshold"=>true}
  ],
  "available_quotas"=>[{"id"=>4205891, "cpi"=>1.0499999999999998, "name"=>"Total", "traits"=>{}, "available"=>400, "conversion"=>0}],
  "rejectable_trait_groups"=>[]
}
</code>```

答:
You are basically trying to do a in memory sort after fetching data from database. You could just use array.sort or array.sort_by

```<code>Campaign.all.sort_by {|c| c.quota_data["raw_quota_data"][0]["Conversion"]}}
</code>```

Body:
I have a Campaign model that has a conversion rate listed like this:

campaign.quota_data["raw_quota_data"][0]["Conversion"] = 33

I'd like to do something like

Campaign.all.order(quota_data["raw_quota_data"][0]["Conversion"])

What's the best way to accomplish this?

Edit: example of what the quota_data data structure looks like:

{"raw_quota_data"=>
  [
    {"QuotaCPI"=>1.5, "Questions"=>nil, "Conversion"=>0, "SurveyQuotaID"=>4205891, "SurveyQuotaType"=>"Total", "OverQuotaThreshold"=>true}
  ],
  "available_quotas"=>[{"id"=>4205891, "cpi"=>1.0499999999999998, "name"=>"Total", "traits"=>{}, "available"=>400, "conversion"=>0}],
  "rejectable_trait_groups"=>[]
}

Body:
You are basically trying to do a in memory sort after fetching data from database. You could just use array.sort or array.sort_by

Campaign.all.sort_by {|c| c.quota_data["raw_quota_data"][0]["Conversion"]}}


答:
If you are trying to update the third column for all rows based on the row having a certain value, as shown in your example code, then it would be much easier use the where method on the dataframe:

```<code>df.loc[:,'3'] = df['3'].where(df['3']!=0, 1)
</code>```

Title: Trying to update a dataframe

Body:
If you are trying to update the third column for all rows based on the row having a certain value, as shown in your example code, then it would be much easier use the where method on the dataframe:

df.loc[:,'3'] = df['3'].where(df['3']!=0, 1)