答:
You can't use either case classes or StructType schema unfortunately! The reason is that scala does not support tuples with more than 22 parts, and both these methods make use of tuples behind the scenes. Since you have more than 22 columns, the approach doesn't work.

However, you can still do it, it's just not as nice :) What you need to do is convert it to a single column dataframe, and call the column something meaningful like "raw"

```<code>val df = rdd.toDF("raw")
</code>```

Next, you need to define a function to extract the column you want for any given column:

```<code>val extractData(idx: Long) = udf[String, String, Int](raw => ???)
</code>```

Now, you need to append each column you want using this function.

```<code>val columns = yourColumnNamesList.zipWithIndex

val df2 = columns.foldLeft(df){case (acc,(cname,cid)) => acc.withColumn(cname, extractData(cid)($"raw")}
</code>```

Although it looks a bit horrendous doing the foldLeft, if you look at plan created by the execution planner, spark is clever enough to flatten all of this into a single map step, and the throughput is better than you'd expect.

Finally, you can drop the raw data since it isn't needed any more.

```<code>df2.drop("raw")
</code>```

Alternatively!

If you're data is in a delimited format on the file system, you should look at the DataBricks csv parser, which works in 1.6 also :-)

Title: Spark convert rdd to dataframe using a class

Body:
I'm using Spark 1.6 with Scala.
i was looking here but i didnt find a clear answer
I have a big file, after filtering the first lines that contain some copyrights I want to take the header (104 fields) and convert it to StructType schema.
I was thinking to use a class extends Product trait to define the schema of the Dataframe and then convert it to Dataframe according to that schema.

What is the best way to do it.

This is a sample from my file:

   text  (06.07.03.216)  COPYRIGHT © skdjh 2000-2016
    text  160614_54554.vf Database    53643_csc   Interface   574 zn  65
    Start   Date    14/06/2016  00:00:00:000
    End Date    14/06/2016  00:14:59:999
    State   "s23"

        cin. Nb      Start     End        Event       Con. Duration  IMSI
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx

T want to convert it to SparkSQL like this schema

    ----------------------------------------------------------------------------------------
  |    cin_Nb |  Start            |   End          |      Event   |   Con_Duration  | IMSI  |
  | ----------------------------------------------------------------------------------------|
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   20556800 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
    ----------------------------------------------------------------------------------------

Body:
You can't use either case classes or StructType schema unfortunately! The reason is that scala does not support tuples with more than 22 parts, and both these methods make use of tuples behind the scenes. Since you have more than 22 columns, the approach doesn't work.

However, you can still do it, it's just not as nice :) What you need to do is convert it to a single column dataframe, and call the column something meaningful like "raw"

val df = rdd.toDF("raw")

Next, you need to define a function to extract the column you want for any given column:

val extractData(idx: Long) = udf[String, String, Int](raw => ???)

Now, you need to append each column you want using this function.

val columns = yourColumnNamesList.zipWithIndex

val df2 = columns.foldLeft(df){case (acc,(cname,cid)) => acc.withColumn(cname, extractData(cid)($"raw")}

Although it looks a bit horrendous doing the foldLeft, if you look at plan created by the execution planner, spark is clever enough to flatten all of this into a single map step, and the throughput is better than you'd expect.

Finally, you can drop the raw data since it isn't needed any more.

df2.drop("raw")

Alternatively!

If you're data is in a delimited format on the file system, you should look at the DataBricks csv parser, which works in 1.6 also :-)


来源: stackexchange

问:
Memory keeps allocated after method ends
I'm developing a Windows Service with C# and .NET Framework 4.6.2 and Entity Framework 6.1.3.

I have a Web API interface on that service and in one Controller's method I create a Dictionary with more than one million strings:

```<code>Dictionary<string, List<string>> codes;
</code>```

This Dictionary is created inside another method:

```<code>codes = GetCodesAsDictionary(connectionString, productionId);
</code>```

I pass this variable to a static method from a static class.

One Visual Studio 2015's memory profiler I see how memory grows to 1,1Gb when I call this method, but when the method ends, the memory keep as 1,1Gb.

If I call the method again, memory grows again to 2Gb, and after method finishes, memory goes to 1,1Gb again.

I have tried to pass the codes variable as reference, but I get the same memory allocation. I have to stop the service and re-run it again to release that 1,1Gb. By the way, I pass it by reference because I don't want that the static method makes a copy of it.

Do you know why it doesn't release such amount of memory after method ends?

UPDATE:

I have changed the static class with an instance class (copying the method from static class) and I get the same result (1,1Gb memory allocated).

SECOND UPDATE:

I have also changed how the dictionary is created:

```<code>Dictionary<string, List<string>> codes = null;
GetCodesAsDictionary(connectionString, productionId, out codes);
</code>```

And I get the same result: 1,1Gb memory allocated.

THIRD UPDATE:

I have changed the Dictionary with a KeyValuePair<byte, string[]>[] and I get the same result, 1,1Gb allocated. Now, instead of using a string as key, I'm using byte.

答:
are you sure the dictionary is created and used only in that method?

If nothing else helps, you could try to use GC.Collect(), but this should be only used as a last resort.

https://msdn.microsoft.com/en-us/library/system.gc.collect(v=vs.110).aspx

EDIT: You can try to use GC.AddMemoryPressure method instead of what I recommended earlier. You need to pass the amount of the Memory to make the GC aware of the fact that there is some memory that could be collected.

https://msdn.microsoft.com/en-us/library/system.gc.addmemorypressure(v=vs.110).aspx

Try if the following works for you:

```<code>Dictionary<string, List<string>> codes = new Dictionary<string, List<string>>();
long bytesBefore = GC.GetTotalMemory(true);

// Code that adds items to your dictionary comes here

long bytesAfter = GC.GetTotalMemory(true);

// After your method ends:
GC.AddMemoryPressure((long) (bytesAfter - bytesBefore));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm developing a Windows Service with C# and .NET Framework 4.6.2 and Entity Framework 6.1.3.

I have a Web API interface on that service and in one Controller's method I create a Dictionary with more than one million strings:

Dictionary<string, List<string>> codes;

This Dictionary is created inside another method:

codes = GetCodesAsDictionary(connectionString, productionId);

I pass this variable to a static method from a static class.

One Visual Studio 2015's memory profiler I see how memory grows to 1,1Gb when I call this method, but when the method ends, the memory keep as 1,1Gb.

If I call the method again, memory grows again to 2Gb, and after method finishes, memory goes to 1,1Gb again.

I have tried to pass the codes variable as reference, but I get the same memory allocation. I have to stop the service and re-run it again to release that 1,1Gb. By the way, I pass it by reference because I don't want that the static method makes a copy of it.

Do you know why it doesn't release such amount of memory after method ends?

UPDATE:

I have changed the static class with an instance class (copying the method from static class) and I get the same result (1,1Gb memory allocated).

SECOND UPDATE:

I have also changed how the dictionary is created:

Dictionary<string, List<string>> codes = null;
GetCodesAsDictionary(connectionString, productionId, out codes);

And I get the same result: 1,1Gb memory allocated.

THIRD UPDATE:

I have changed the Dictionary with a KeyValuePair<byte, string[]>[] and I get the same result, 1,1Gb allocated. Now, instead of using a string as key, I'm using byte.

Body:
are you sure the dictionary is created and used only in that method?

If nothing else helps, you could try to use GC.Collect(), but this should be only used as a last resort.

https://msdn.microsoft.com/en-us/library/system.gc.collect(v=vs.110).aspx

EDIT: You can try to use GC.AddMemoryPressure method instead of what I recommended earlier. You need to pass the amount of the Memory to make the GC aware of the fact that there is some memory that could be collected.

https://msdn.microsoft.com/en-us/library/system.gc.addmemorypressure(v=vs.110).aspx

Try if the following works for you:

Dictionary<string, List<string>> codes = new Dictionary<string, List<string>>();
long bytesBefore = GC.GetTotalMemory(true);

// Code that adds items to your dictionary comes here

long bytesAfter = GC.GetTotalMemory(true);

// After your method ends:
GC.AddMemoryPressure((long) (bytesAfter - bytesBefore));


问:
datatable plugin not display elements after clicking again on link to show
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid text-center">
      <div class="row content">
       <div class="col-lg-2 sidenav">
      <a href="#" id="link3" class="list-group-item">Vertical link #3</a>
        </div>
        <div class="col-lg-10 text-left">
          <div class="row">
            <div class="col-lg-12" id="content"></div>
          </div>
        </div>
      </div>
    </div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- link3 -->
<script src="link3.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
</html>
</code>```

link3.js

```<code>$(document).ready(function(){
var table = $('<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Note</th></tr></thead><tbody></tbody></table>').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("<tr><td>"+id+"</td><td>"+id2+"</td><td>"+id3+"</td><td>"+id4+"</td></tr>");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});
</code>```

test.json

```<code>[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]
</code>```

答:
You can bind your json from url directly to datatable using url and datasource attribute, refer

You can write your code

```<code>$('#myTable').DataTable( {
    ajax: {
        url: 'test.json',
        dataSrc: ''
    },
    "columns": [
        { "data": "name" },
        { "data": "age" },
        { "data": "position" },
        { "data": "note" }
    ]
} );
</code>```

Body:
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

<!DOCTYPE html>

  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">

      Vertical link #3

link3.js

$(document).ready(function(){
var table = $('

Name	Age	Position	Note

').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("
"+id+"	"+id2+"	"+id3+"	"+id4+"
");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});

test.json

[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]

Body:
You can bind your json from url directly to datatable using url and datasource attribute, refer

You can write your code

$('#myTable').DataTable( {
    ajax: {
        url: 'test.json',
        dataSrc: ''
    },
    "columns": [
        { "data": "name" },
        { "data": "age" },
        { "data": "position" },
        { "data": "note" }
    ]
} );


问:
Android checkbox and text box on top of the other
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>
</code>```

I would be happy if someone can help me to fix this problem. Thanks.

答:
Try

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false">

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_gravity="bottom"
    android:background="@android:color/darker_gray" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="left|center_vertical"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/CheckBox"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.1"
        android:checked="true" />

    <TextView
        android:id="@+id/title_text_view"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.9"
        android:allowUndo="true"
        android:elevation="0dp"
        android:gravity="center_vertical"
        android:text="Aaadfdsaf"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|center_vertical"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    tools:text="Button" />
</code>```

Change the gravity and position where you want, I don't have design so can't make how you need it

Body:
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>

I would be happy if someone can help me to fix this problem. Thanks.

Body:
Try

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false">

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_gravity="bottom"
    android:background="@android:color/darker_gray" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="left|center_vertical"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/CheckBox"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.1"
        android:checked="true" />

    <TextView
        android:id="@+id/title_text_view"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.9"
        android:allowUndo="true"
        android:elevation="0dp"
        android:gravity="center_vertical"
        android:text="Aaadfdsaf"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|center_vertical"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    tools:text="Button" />

Change the gravity and position where you want, I don't have design so can't make how you need it


问:
Core Reporting API v3 - Data sampled from specific date, but not before that date
I have a Google Analytics account, with a view that was created on 2015-07-29.

Making a request to the core reporting api with 2015-07-29 as the start-date:

https://www.googleapis.com/analytics/v3/data/ga?ids=<my-ga-id>&dimensions=ga:medium,ga:year,ga:month,ga:channelGrouping&metrics=ga:transactions&start-date=2015-07-29&end-date=2017-03-30&max-results=10000

I get the following response:

```<code>{
...
  "containsSampledData": true,
  "sampleSize": "498617",
  "sampleSpace": "1022430",
...
}
</code>```

Which makes perfect sense - it is sampling the data, because of the number of sessions.

However, if I change my request to the core reporting api, so that now 2015-07-28 is the start-date:

https://www.googleapis.com/analytics/v3/data/ga?ids=<my-ga-id>&dimensions=ga:medium,ga:year,ga:month,ga:channelGrouping&metrics=ga:transactions&start-date=2015-07-28&end-date=2017-03-30&max-results=10000

I get the following response:

```<code>{
...
   "containsSampledData": false
...
}
</code>```

The data is no longer sampled, and yields the correct values (compared to Google Analytics Web UI).

If then add the metric ga:sessions to the request with start-date=2015-07-28, I get sampled data.

My question is:

Why is the data sampled if the start-date is equal to or later than the date, the Google Analytics view was created? - If it is before that date, the data is no longer sampled? - But it is sampled as soon as I put in the metric ga:sessions?

答:
In data analysis, sampling is the practice of analyzing a subset of
  all the data in order to uncover the meaningful information in the
  larger data set. For example, during an election cycle, you hear lots
  of news about what percent of voters prefer one candidate over
  another, or are for or against a certain issue. Because there can be
  tens to hundreds of millions of voters in an election, and because the
  companies conducting the surveys want to get their information out to
  the public as soon as possible, trying to question every voter for
  every new survey would be extraordinarily expensive and take too much
  time. To solve those problems, surveyors use what they conclude is a
  representative sample of the overall voter population, often just 1000
  voters from the millions who are eligible.

Basically data is sampled when the amount of data returned is to large.  How Google calculates / determines when a request should be sampled is something that only Google can answer.   I believe this question is primary opinion based and this is my opinion.

Google guestimates the number of rows returned by your request, divides it by the number of days in the request giving you Y.  If Y is greater than X they sample.  By adding the date before you actually started recording any data you are tricking the system into reducing the size of Y and there by not sampling.

Again this is a wild guess on my part.   I may test it sounds like a fun way to trick the system.

Body:
I have a Google Analytics account, with a view that was created on 2015-07-29.

Making a request to the core reporting api with 2015-07-29 as the start-date:

https://www.googleapis.com/analytics/v3/data/ga?ids=<my-ga-id>&dimensions=ga:medium,ga:year,ga:month,ga:channelGrouping&metrics=ga:transactions&start-date=2015-07-29&end-date=2017-03-30&max-results=10000

I get the following response:

{
...
  "containsSampledData": true,
  "sampleSize": "498617",
  "sampleSpace": "1022430",
...
}

Which makes perfect sense - it is sampling the data, because of the number of sessions.

However, if I change my request to the core reporting api, so that now 2015-07-28 is the start-date:

https://www.googleapis.com/analytics/v3/data/ga?ids=<my-ga-id>&dimensions=ga:medium,ga:year,ga:month,ga:channelGrouping&metrics=ga:transactions&start-date=2015-07-28&end-date=2017-03-30&max-results=10000

I get the following response:

{
...
   "containsSampledData": false
...
}

The data is no longer sampled, and yields the correct values (compared to Google Analytics Web UI).

If then add the metric ga:sessions to the request with start-date=2015-07-28, I get sampled data.

My question is:

Why is the data sampled if the start-date is equal to or later than the date, the Google Analytics view was created? - If it is before that date, the data is no longer sampled? - But it is sampled as soon as I put in the metric ga:sessions?


问:
Files in folders not found in iOS app using C++
I'm trying to read files stored in assets folder and its subfolders using std::ifstream in an iOS app written mostly in C++ (The same code is also used in other, non-iOS projects), but they're not found. Example: there is a file assets/shaders/ortho2d.vert and I'm trying to load it like this:

```<code>std::ifstream vertFStream( vertFile ); // vertFile's contents is "assets/shaders/ortho2d.vert"
if (!vertFStream) {
    std::cerr << vertFile << " missing!" << std::endl;
    exit( 1 );
}
</code>```

I've added the assets folder to the XCode project as a blue folder and it shows up in Targets->Copy Bundle Resources.

答:
You may need to check the relative path from where the application is running and probably use a full path to ensure the file is found.

The fact that the open failed does not necessarily mean the file is not found, it just might not be readable at this moment. (Incorrect permissions or file locked).

exit(1) is rather drastic.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to read files stored in assets folder and its subfolders using std::ifstream in an iOS app written mostly in C++ (The same code is also used in other, non-iOS projects), but they're not found. Example: there is a file assets/shaders/ortho2d.vert and I'm trying to load it like this:

std::ifstream vertFStream( vertFile ); // vertFile's contents is "assets/shaders/ortho2d.vert"
if (!vertFStream) {
    std::cerr << vertFile << " missing!" << std::endl;
    exit( 1 );
}

I've added the assets folder to the XCode project as a blue folder and it shows up in Targets->Copy Bundle Resources.


问:
android:contentInsetLeft="0dp" vs app:contentInsetLeft="0dp"
I am trying to remove left space of toolbar. I see this https://stackoverflow.com/a/32320632/2455259 which seems working for me. I am unable to understand what is the meaning to add android and app namespace for same attribute.

Is there any difference between them ? android:contentInsetLeft="0dp" vs app:contentInsetLeft="0dp"

答: android:contentInsetLeft should be used with the native Toolbar android.widget.ToolBar while app:contentInsetLeft has to be used with the Toolbar from the support library android.support.v7.widget.Toolbar. As rule of thumb, res-auto namespace is used with the support-library


问:
How to convert a string into condition in the IF statement
Let say I have a string stored in the $condition variable:

```<code>$condition = '2 == 2'; // returns TRUE
</code>```

or

```<code>$condition = 'my_own_function()'; // which also returns TRUE
</code>```

How can I convert them into a condition in an IF statement? Say:

```<code>if (some_magic_converter_function($condition)){
    // execute something
}
</code>```

it will be the same as if I execute

```<code>if (my_own_function()){
    // execute something
}
</code>```

Is there any other ways I can safely evaluate the string into a condition of an IF statement? How?

答:
I found out that we can fully make use of preg_match to accomplish the above task:

```<code>/**
 * Function parse_condition
 * @param string $condition
 * @return bool
 */
function parse_condition($condition){
    // match {a} {condition} {b}
    preg_match('/.*(.*?)\s(.*?)\s(.*?)/sU', $condition, $condition_matches);

    // condition_matches[1] will be a, remove $, () and leading/tailing spaces
    $a = trim(str_replace(array('$','()'),'',$condition_matches[1]));

    // condition_matches[2] will be the operator
    $operator = $condition_matches[2];

    // condition_matches[3] will be b, remove $, () and leading/tailing spaces
    $b = trim(str_replace(array('$','()'),'',$condition_matches[3]));

    // It is advisable to pass variables into array or a "hive"
    // but in this example, let's just use global

    // Make variable's variable $$a accessible
    global $$a;
    // And for $$b too
    global $$b;

    $cmp1 = isset($$a)?($$a):($a);

    $cmp2 = isset($$b)?($$b):($b);

    switch($operator){
        case '==':
            return($cmp1 == $cmp2);
            break;
        case '!=':
            return($cmp1 != $cmp2);
            break;
        case '===':
            return($cmp1 === $cmp2);
            break;
        case '!==':
            return($cmp1 !== $cmp2);
            break;
        default:
            return false;
            break;
    }
}
</code>```

so I can use it like this:

```<code>// TESTCASES
$var_a = 100;
$var_b = 100;
$var_c = 110;
$var_d = (double) 100;

if(parse_condition('$var_a == $var_b')){ // TRUE
    echo 'Yeah I am Good!' . PHP_EOL;
}

if(parse_condition('$var_a != $var_c')){ // TRUE
    echo 'Good for this one too!' . PHP_EOL;
}

if(parse_condition('$var_b == $var_c')){ // FALSE
    echo 'Yeah I am Good!' . PHP_EOL;
}else{
    echo 'But I am not with this one :(' . PHP_EOL;
}

if(parse_condition('$var_a != 110')){ // TRUE
    echo 'I can compare values too' . PHP_EOL;
}

if(parse_condition('$var_a === $var_d')){ // FALSE
    //
}else{
    echo 'Or even tell the difference between data types' . PHP_EOL;
}
</code>```

Body:
Let say I have a string stored in the $condition variable:

$condition = '2 == 2'; // returns TRUE

or

$condition = 'my_own_function()'; // which also returns TRUE

How can I convert them into a condition in an IF statement? Say:

if (some_magic_converter_function($condition)){
    // execute something
}

it will be the same as if I execute

if (my_own_function()){
    // execute something
}

Is there any other ways I can safely evaluate the string into a condition of an IF statement? How?

Body:
I found out that we can fully make use of preg_match to accomplish the above task:

/**
 * Function parse_condition
 * @param string $condition
 * @return bool
 */
function parse_condition($condition){
    // match {a} {condition} {b}
    preg_match('/.*(.*?)\s(.*?)\s(.*?)/sU', $condition, $condition_matches);

    // condition_matches[1] will be a, remove $, () and leading/tailing spaces
    $a = trim(str_replace(array('$','()'),'',$condition_matches[1]));

    // condition_matches[2] will be the operator
    $operator = $condition_matches[2];

    // condition_matches[3] will be b, remove $, () and leading/tailing spaces
    $b = trim(str_replace(array('$','()'),'',$condition_matches[3]));

    // It is advisable to pass variables into array or a "hive"
    // but in this example, let's just use global

    // Make variable's variable $$a accessible
    global $$a;
    // And for $$b too
    global $$b;

    $cmp1 = isset($$a)?($$a):($a);

    $cmp2 = isset($$b)?($$b):($b);

    switch($operator){
        case '==':
            return($cmp1 == $cmp2);
            break;
        case '!=':
            return($cmp1 != $cmp2);
            break;
        case '===':
            return($cmp1 === $cmp2);
            break;
        case '!==':
            return($cmp1 !== $cmp2);
            break;
        default:
            return false;
            break;
    }
}

so I can use it like this:

// TESTCASES
$var_a = 100;
$var_b = 100;
$var_c = 110;
$var_d = (double) 100;

if(parse_condition('$var_a == $var_b')){ // TRUE
    echo 'Yeah I am Good!' . PHP_EOL;
}

if(parse_condition('$var_a != $var_c')){ // TRUE
    echo 'Good for this one too!' . PHP_EOL;
}

if(parse_condition('$var_b == $var_c')){ // FALSE
    echo 'Yeah I am Good!' . PHP_EOL;
}else{
    echo 'But I am not with this one :(' . PHP_EOL;
}

if(parse_condition('$var_a != 110')){ // TRUE
    echo 'I can compare values too' . PHP_EOL;
}

if(parse_condition('$var_a === $var_d')){ // FALSE
    //
}else{
    echo 'Or even tell the difference between data types' . PHP_EOL;
}

ContentLicense: CC BY-SA 4.0


问:
Show active navigation for current page
i'm having some problems with my html, php code. With this code, my nav will show the active li but the other pages which are not active won't have style or links. </p>

```<code>    <!--/. PHP "active" -->
    <?php
    $current_url = basename($_SERVER['PHP_SELF']);
    $active = "class=\"active-menu\"";
    ?>
    <!--/. PHP "active" -->

    <nav class="navbar-default navbar-side" role="navigation">
        <div class="sidebar-collapse">
            <ul class="nav" id="main-menu">
                <li>
                    <?php if ($current_url == "home.php") { ?>
                    <a <?php echo $active;?> href="home.php"><?php } ?><i class="fa fa-dashboard"></i> Dashboard</a>
                </li>
                <li>
                    <?php if ($current_url == "new.php") { ?>
                    <a <?php echo $active;?> href="new.php"><?php } ?><i class="fa fa-qrcode"></i> Nieuw item toevoegen</a>
                </li>
                <li>
                    <?php if ($current_url == "show.php") { ?>
                    <a <?php echo $active;?> href="show.php"><?php } ?><i class="fa fa-qrcode"></i> Bekijk inventaris</a>
                </li>
                <li>
                    <?php if ($current_url == "profile.php") { ?>
                    <a <?php echo $active;?> href="profile.php"><?php } ?><i class="fa fa-user"></i> Gebruikersprofiel</a>
                </li>
                <li>
                    <a href="#"><i class="fa fa-sitemap"></i> Gebruikers<span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="#">Beheerders</a>
                        </li>
                        <li>
                            <a href="#">ICT - Verantwoordelijken</a>
                        </li>
                        <li>
                            <a href="#">Raadplegers</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <?php if ($current_url == "empty.php") { ?>
                    <a <?php echo $active;?> href="empty.php"><?php } ?><i class="fa fa-fw fa-file"></i> Lege pagina</a>
                </li>
            </ul>

        </div>

    </nav>
</code>```

<p>the pages with no styling will also not have a link. The active-menu class has the styling. </p>

答:
```<code><li>
     <a href="new.php" <?php if ($current_url == "new.php") {echo $active;}?>>
     <i class="fa fa-qrcode"></i> Nieuw item toevoegen
     </a>
</li>
</code>```

<p>Put your list like this </p>

Title: Show active navigation for current page

Body:
i'm having some problems with my html, php code. With this code, my nav will show the active li but the other pages which are not active won't have style or links.

    <?php
    $current_url = basename($_SERVER['PHP_SELF']);
    $active = "class=\"active-menu\"";
    ?>

                    <?php if ($current_url == "home.php") { ?>
                    <a <?php echo $active;?> href="home.php"><?php } ?> Dashboard

                    <?php if ($current_url == "new.php") { ?>
                    <a <?php echo $active;?> href="new.php"><?php } ?> Nieuw item toevoegen

                    <?php if ($current_url == "show.php") { ?>
                    <a <?php echo $active;?> href="show.php"><?php } ?> Bekijk inventaris

                    <?php if ($current_url == "profile.php") { ?>
                    <a <?php echo $active;?> href="profile.php"><?php } ?> Gebruikersprofiel

                     Gebruikers

                            Beheerders

                            ICT - Verantwoordelijken

                            Raadplegers

                    <?php if ($current_url == "empty.php") { ?>
                    <a <?php echo $active;?> href="empty.php"><?php } ?> Lege pagina

the pages with no styling will also not have a link. The active-menu class has the styling.

Body:
<li>
     <a href="new.php" <?php if ($current_url == "new.php") {echo $active;}?>>
     <i class="fa fa-qrcode"></i> Nieuw item toevoegen
     </a>
</li>

Put your list like this


问:
UIALertView customization
I am developing an iPhone application, in which I want to use customized alert sheet. The customization is required since I want to set image for Alert-Sheet buttons, change the size of these button etc.

I have done the following things:

Created UIView with customized controls that I wanted.

Created and displayed UIAlertView

In the delegate method of UIAlertView (UIAlertViewDelegate) i.e

```<code>- (void)willPresentAlertView:(UIAlertView *)alertView
</code>```

I am removing all the subviews of UIAlertView and adding my customized view as subview.

Everything works fine till here. Since I have used customized buttons, I need to remove the alert sheet explicitly in the Action Method of the button by calling dismissWithClickedButtonIndex:animated: on UIAlertView.
Even though the UIALertView gets dismissed, it takes around 0.5 second to get dismissed.
Can someone help me out to solve the problem of this delay in dismissing OR some other way of customization of Alert View buttons.

Thanks and Regards,
Deepa

答:
Here is the library which can solve your UIAlertView Customisation issue. It can also work as UIActionSheet. It has very good customisation options.

https://github.com/Codigami/CFAlertViewController

Title: UIALertView customization

Body:
I am developing an iPhone application, in which I want to use customized alert sheet. The customization is required since I want to set image for Alert-Sheet buttons, change the size of these button etc.

I have done the following things:

Created UIView with customized controls that I wanted.

Created and displayed UIAlertView

In the delegate method of UIAlertView (UIAlertViewDelegate) i.e

- (void)willPresentAlertView:(UIAlertView *)alertView

I am removing all the subviews of UIAlertView and adding my customized view as subview.

Everything works fine till here. Since I have used customized buttons, I need to remove the alert sheet explicitly in the Action Method of the button by calling dismissWithClickedButtonIndex:animated: on UIAlertView.
Even though the UIALertView gets dismissed, it takes around 0.5 second to get dismissed.
Can someone help me out to solve the problem of this delay in dismissing OR some other way of customization of Alert View buttons.

Thanks and Regards,
Deepa


答:
android namespace is reserved for views that are in the Android Framework.

On the other hand, app namespace is for views from support library.

So, in this case android will be applied to Toolbar that is shipped within Android SDK - android.widget.ToolBar. And app
will be applied to the Toolbar that comes with support libraries.

Obviously, there's no need to apply both android and app to the same view, because it is either from Android SDK or from support library.

Body:
I am trying to remove left space of toolbar. I see this https://stackoverflow.com/a/32320632/2455259 which seems working for me. I am unable to understand what is the meaning to add android and app namespace for same attribute.

Is there any difference between them ? android:contentInsetLeft="0dp" vs app:contentInsetLeft="0dp"


问:
Register user name with apostrophe (') Android
I have an app in Android where users have to register, and they have to intruduce a name. The problem is that when a user introduce the apostrophe (') in his name (eg Satck'developers). Then in the app I have problems with the database SQLite.

UPDATE user SET name='othername' WHERE name='Stack'developers'`)

This causes a SQLiteException.

How  can I manage this situation in Android? How can I not to allow user to put apostrophe (')?

Thank you very much.

答:
If you dont want to allow ' then you need to validate you input before storing in db. Something like </p>

```<code>if(editText.getText().toString.contains("'")){
// show invalid error message
} else{
// store to db
}
</code>```

Body:
If you dont want to allow ' then you need to validate you input before storing in db. Something like

if(editText.getText().toString.contains("'")){
// show invalid error message
} else{
// store to db
}


问:
wso2 das event indexing delay
When I send events to a stream receiver the following occurs:

I can see the events in the data explorer

If I try to filter the results by query, theorically matching results are not shown

Those matching results appear after some time has passed

I suppose the issue is due to a delay in the indexing of the data. How can I get events to be indexed in real time?

答: I was overriding the _timestamp parameter, but I noticed that the timestamp shown in the data explorer was "in the future"...it was a _timestamp problem!</p>

Title: wso2 das event indexing delay


问:
Cordova installation issues
I have followed all the procedure which is mentioned in cordova tutorial point, i'm stuck in building the app for the specified platform where we can run it on mobile device or emulator, it showing failed to run javac -version.</p>

答: The first thing that come in mind is that you don't have the jre/jdk installed</p>

Title: Cordova installation issues


问:
Django: How to limit_choices_to when using custom intermediate table
Let me start by saying that I am working with a legacy database so avoiding the custom intermediate table is not an option.

I'm looking for an alternative way to get the limit_choices_to functionality as I need to only present the options flagged by the sample_option boolean in the Sampletype Model in my ModelForm:

```<code>class PlanetForm(ModelForm):
    class Meta:
        model = Planet
        fields = ['name', 'samples']
</code>```

Here is a simplified view of my models

```<code>class Planet(models.Model):
    name= models.CharField(unique=True, max_length=256)
    samples = models.ManyToManyField('Sampletype', through='Sample')

class Sample(models.Model):
    planet = models.ForeignKey(Planet, models.DO_NOTHING)
    sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING)

class Sampletype(models.Model):
    name = models.CharField(unique=True, max_length=256)
    sample_option = models.BooleanField(default=True)
</code>```

Sample is the intermediate table.
Normally, if the project had been started with Django in the first place, I could just define the ManyToManyField declaration as:

```<code>samples = models.ManyToManyField('Sampletype', limit_choices_to={'sample_option'=True})
</code>```

But this is not an option.. So how do I get this functionality ?
Django clearly states in their documentation that:

limit_choices_to has no effect when used on a ManyToManyField with a
  custom intermediate table specified using the through parameter.

But they offer no information on how to get that limit in place when you DO have a custom intermediate table.

I tried setting the limit_choices_to option on the ForeignKey in the Sample Model like so:

```<code>sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING, limit_choices_to={'sample_option': True})
</code>```

but that had no effect.

Strangely, I find no answer to this on the web and clearly other people must have to do this in their projects so I'm guessing the solution is really simple but I cannot figure it out.

Thanks in advance for any help or suggestions.

答:
You could set the choices in the __init__ method of the form:

```<code>class PlanetForm(ModelForm):

    class Meta:
        model = Planet
        fields = ['name', 'samples']

    def __init__(self, *args, **kwargs):
         super(PlanetForm, self).__init__(*args, **kwargs)

         sample_choices = list(
             Sampletype.objects.filter(sample_option=True).values_list('id', 'name')
         )
         # set these choices on the 'samples' field.
         self.fields['samples'].choices = sample_choices
</code>```

Body:
Let me start by saying that I am working with a legacy database so avoiding the custom intermediate table is not an option.

I'm looking for an alternative way to get the limit_choices_to functionality as I need to only present the options flagged by the sample_option boolean in the Sampletype Model in my ModelForm:

class PlanetForm(ModelForm):
    class Meta:
        model = Planet
        fields = ['name', 'samples']

Here is a simplified view of my models

class Planet(models.Model):
    name= models.CharField(unique=True, max_length=256)
    samples = models.ManyToManyField('Sampletype', through='Sample')

class Sample(models.Model):
    planet = models.ForeignKey(Planet, models.DO_NOTHING)
    sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING)

class Sampletype(models.Model):
    name = models.CharField(unique=True, max_length=256)
    sample_option = models.BooleanField(default=True)

Sample is the intermediate table.
Normally, if the project had been started with Django in the first place, I could just define the ManyToManyField declaration as:

samples = models.ManyToManyField('Sampletype', limit_choices_to={'sample_option'=True})

But this is not an option.. So how do I get this functionality ?
Django clearly states in their documentation that:

limit_choices_to has no effect when used on a ManyToManyField with a
  custom intermediate table specified using the through parameter.

But they offer no information on how to get that limit in place when you DO have a custom intermediate table.

I tried setting the limit_choices_to option on the ForeignKey in the Sample Model like so:

sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING, limit_choices_to={'sample_option': True})

but that had no effect.

Strangely, I find no answer to this on the web and clearly other people must have to do this in their projects so I'm guessing the solution is really simple but I cannot figure it out.

Thanks in advance for any help or suggestions.

Body:
You could set the choices in the __init__ method of the form:

class PlanetForm(ModelForm):

    class Meta:
        model = Planet
        fields = ['name', 'samples']

    def __init__(self, *args, **kwargs):
         super(PlanetForm, self).__init__(*args, **kwargs)

         sample_choices = list(
             Sampletype.objects.filter(sample_option=True).values_list('id', 'name')
         )
         # set these choices on the 'samples' field.
         self.fields['samples'].choices = sample_choices


问:
SQL GROUP BY explanation
So I have been playing around with SQL for a while now, and i can't seem to get the group by function down. For example, I have been using the w3schools online database with SQL, and experimenting with it.
One problem I can't seem to crack is to update the prices of products from the same supplier, and that their sum is some number.

Here is the link to the database: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

So what I came up with was this:

```<code>    UPDATE Products
    SET Price=Price*100
    WHERE 47=(SELECT SUM(p.Price) FROM Products p GROUP BY p.SupplierID)
</code>```

It seems to update the whole database. I expected it only to update the prices of the products that belong to the first supplier, as the sum of their prices is 47. I guess I'm making some rookie mistake, but I just can't seem to get it right.

Edit:
My expected result would be that all rows from table Products who have supplierID=1 would update the price(Although it's not that I'm just aiming at the 1st supplier, but any supplier who's products prices sum up to 47), but what happens is that all the prices get updated, regardless of the supplier or the sum of their prices. But when I change the number from 47, nothing seems to happen.

答:
Your existing query will effectively resolve to

```<code>UPDATE Products SET Price = Price*100 WHERE 47 = 47
</code>```

47 happens, coincidentally, to be the result of the first row of the subquery. Since 47 = 47 is always true, then all rows will be updated. What you actually want to do is find the SupplierID where the SUM of all the products is 47, and use that in the WHERE clause.

This will do what you want, I think:

```<code>UPDATE Products
SET Price = Price*100
WHERE SupplierID IN
  (SELECT SupplierID
  FROM Products
  GROUP BY SupplierID
  HAVING SUM(Price) = 47)
</code>```

It will update the the price of all rows where the SupplierID matches a SupplierID where the total price of all that supplier's products is equal 47. This could in theory update more than one supplier's prices, if there are two where the total price of their products is 47.

Title: SQL GROUP BY explanation

Body:
So I have been playing around with SQL for a while now, and i can't seem to get the group by function down. For example, I have been using the w3schools online database with SQL, and experimenting with it.
One problem I can't seem to crack is to update the prices of products from the same supplier, and that their sum is some number.

Here is the link to the database: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

So what I came up with was this:

    UPDATE Products
    SET Price=Price*100
    WHERE 47=(SELECT SUM(p.Price) FROM Products p GROUP BY p.SupplierID)

It seems to update the whole database. I expected it only to update the prices of the products that belong to the first supplier, as the sum of their prices is 47. I guess I'm making some rookie mistake, but I just can't seem to get it right.

Edit:
My expected result would be that all rows from table Products who have supplierID=1 would update the price(Although it's not that I'm just aiming at the 1st supplier, but any supplier who's products prices sum up to 47), but what happens is that all the prices get updated, regardless of the supplier or the sum of their prices. But when I change the number from 47, nothing seems to happen.

Body:
Your existing query will effectively resolve to

UPDATE Products SET Price = Price*100 WHERE 47 = 47

47 happens, coincidentally, to be the result of the first row of the subquery. Since 47 = 47 is always true, then all rows will be updated. What you actually want to do is find the SupplierID where the SUM of all the products is 47, and use that in the WHERE clause.

This will do what you want, I think:

UPDATE Products
SET Price = Price*100
WHERE SupplierID IN
  (SELECT SupplierID
  FROM Products
  GROUP BY SupplierID
  HAVING SUM(Price) = 47)

It will update the the price of all rows where the SupplierID matches a SupplierID where the total price of all that supplier's products is equal 47. This could in theory update more than one supplier's prices, if there are two where the total price of their products is 47.


问:
which method is better to store meta-data (keywords and description) in Mysql (Laravel)?
There are "Articles", "News" tables. I want to allow admin to add meta tags like keywords and description when creating new articles or news. I have used laravel Polymorphic Relations and have two methods in mind to implement :

Method 1

meta_data Table:

```<code>id   metable_type   metable_id    meta_type      meta_content

1    news           4             description    php is a good...
2    articles       7             keywords       laravel,relation,tag
3    articles       2             keywords       php,developer,html
</code>```

.

Method 2

meta_data Table:

```<code>id   metable_type   metable_id    meta_type      meta_content

1    news           4             description    php is a good...
2    articles       7             keyword        laravel
2    articles       7             keyword        relation
2    articles       7             keyword        tag
3    articles       2             keyword       php
3    articles       2             keyword       developer
3    articles       2             keyword       html
</code>```

My Questions:

Is there a better approach than these two methods ?
Which method is better?

User should be able to edit kewwords and descriptions for and article or news.

答:
Putting the table name in a column will not allow you to create a foreign key relationship, and this will screw everything. Create a news_attributes and an article_attributes table with proper foreign keys.

meta_type should not be a string. If you have one of several types of attributes, store the types in a separate table, and link them with an integer foreign key. These are likely to be constants, hardcoded in your php code anyway, so why use a slower string?

Now, the second method is normalized and SQL-friendly, since adding/removing keywords is easily done using INSERT and DELETE. This is really the way to go.

The only advantage of storing comma-separated keywords in a column is to be able to put a FULLTEXT index on it. This is the ONLY acceptable scenario.

Body:
There are "Articles", "News" tables. I want to allow admin to add meta tags like keywords and description when creating new articles or news. I have used laravel Polymorphic Relations and have two methods in mind to implement :

Method 1

meta_data Table:

id   metable_type   metable_id    meta_type      meta_content

1    news           4             description    php is a good...
2    articles       7             keywords       laravel,relation,tag
3    articles       2             keywords       php,developer,html

.

Method 2

meta_data Table:

id   metable_type   metable_id    meta_type      meta_content

1    news           4             description    php is a good...
2    articles       7             keyword        laravel
2    articles       7             keyword        relation
2    articles       7             keyword        tag
3    articles       2             keyword       php
3    articles       2             keyword       developer
3    articles       2             keyword       html

My Questions:

Is there a better approach than these two methods ?
Which method is better?

User should be able to edit kewwords and descriptions for and article or news.


问:
Reading Cyrillic text from CSV / JSON with d3
I would like to import Cyrillic text from CSV or JSON using d3 (for the purpose of a bubble chart visualisation)

Once loaded with either of the functions:

```<code>d3.csv('spendings.csv', function(data) {
  console.log(data[0]);
});
</code>```

or

```<code>d3.json('spendings.json', function(data) {
  console.log(data[0]);
});
</code>```

the text

Многопрофилна болница за активно лечение /МБАЛ/ "Света Анна" АД - София

looks something like this in the DOM console:

M������������ ������� �� ������� ������� /����/ "����� ����" �� - �����

This tells me that the problem is not with the HTML encoding, but rather with the way Cyrillic text is read by d3.js

答:
I use Cyrillic in D3.

1.HTML:

```<code><head>
  <meta charset="utf-8">
</head>
</code>```

use utf-8 in editor .html .csv .json files

Body:
I would like to import Cyrillic text from CSV or JSON using d3 (for the purpose of a bubble chart visualisation)

Once loaded with either of the functions:

d3.csv('spendings.csv', function(data) {
  console.log(data[0]);
});

or

d3.json('spendings.json', function(data) {
  console.log(data[0]);
});

the text

Многопрофилна болница за активно лечение /МБАЛ/ "Света Анна" АД - София

looks something like this in the DOM console:

M������������ ������� �� ������� ������� /����/ "����� ����" �� - �����

This tells me that the problem is not with the HTML encoding, but rather with the way Cyrillic text is read by d3.js

Body:
I use Cyrillic in D3.

1.HTML:

<head>
  <meta charset="utf-8">
</head>

use utf-8 in editor .html .csv .json files


问:
Jest with React Native getting issue
I'm getting error when trying to run test cases  code.i am using react native with jest . all was working fine before upgrade 0.40 . now is 0.42 all my test cases stop working and getting  error  following error.

```<code>({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component, Children, PropTypes } from 'react';
                                                                                ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (node_modules/react-native-root-siblings/lib/AppRegistryInjection.js:3:22)
      at Object.<anonymous> (node_modules/react-native-root-siblings/lib/SiblingsManager.js:3:27)
</code>```

here is my .babelrc code

```<code>{
    "presets": [
        "react-native"
    ],
    "plugins": [
        "transform-decorators-legacy"
    ]
}
</code>```

what is issue I am not getting .

答:
I ran into very same problem with 0.42. I banged my head until I found a solution piece by piece.

You need to to write ignores in package.json. Example of mine:

```<code>"jest": {
        "preset": "react-native",
        "setupFiles": [
            "<rootDir>/src/config/jest.js"
        ],
        "transformIgnorePatterns": [
            "<rootDir>/(node_modules)/(?!react-native|react-navigation|bugsnag-react-native)"
        ],
        "transform": {
            "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
        }
</code>```

And my /config/jest.js looks like:

```<code>jest.mock('Linking', () => ({
  addEventListener: jest.fn(),
  removeEventListener: jest.fn(),
  openURL: jest.fn(),
  canOpenURL: jest.fn(),
  getInitialURL: jest.fn().mockImplementation(() => new Promise((resolve) => resolve()))
}));

jest.mock('mobx-react/native', () => require('mobx-react/custom'));
jest.mock('react-native-mixpanel', () => ({
  sharedInstanceWithToken: jest.fn(),
  trackWithProperties: jest.fn()
}));
jest.mock('bugsnag-react-native', () => ({
  Client: jest.fn(),
  Configuration: jest.fn()
}));
</code>```

I'm not guaranteed this solves all of your problems directly. However the idea is to ignore all the "evil-doers" (react-native-root-siblings in your case), thus avoiding such error messages.

Title: Jest with React Native getting issue

Body:
I'm getting error when trying to run test cases  code.i am using react native with jest . all was working fine before upgrade 0.40 . now is 0.42 all my test cases stop working and getting  error  following error.

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component, Children, PropTypes } from 'react';
                                                                                ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (node_modules/react-native-root-siblings/lib/AppRegistryInjection.js:3:22)
      at Object.<anonymous> (node_modules/react-native-root-siblings/lib/SiblingsManager.js:3:27)

here is my .babelrc code

{
    "presets": [
        "react-native"
    ],
    "plugins": [
        "transform-decorators-legacy"
    ]
}

what is issue I am not getting .

Body:
I ran into very same problem with 0.42. I banged my head until I found a solution piece by piece.

You need to to write ignores in package.json. Example of mine:

"jest": {
        "preset": "react-native",
        "setupFiles": [
            "<rootDir>/src/config/jest.js"
        ],
        "transformIgnorePatterns": [
            "<rootDir>/(node_modules)/(?!react-native|react-navigation|bugsnag-react-native)"
        ],
        "transform": {
            "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
        }

And my /config/jest.js looks like:

jest.mock('Linking', () => ({
  addEventListener: jest.fn(),
  removeEventListener: jest.fn(),
  openURL: jest.fn(),
  canOpenURL: jest.fn(),
  getInitialURL: jest.fn().mockImplementation(() => new Promise((resolve) => resolve()))
}));

jest.mock('mobx-react/native', () => require('mobx-react/custom'));
jest.mock('react-native-mixpanel', () => ({
  sharedInstanceWithToken: jest.fn(),
  trackWithProperties: jest.fn()
}));
jest.mock('bugsnag-react-native', () => ({
  Client: jest.fn(),
  Configuration: jest.fn()
}));

I'm not guaranteed this solves all of your problems directly. However the idea is to ignore all the "evil-doers" (react-native-root-siblings in your case), thus avoiding such error messages.


问:
Why is running AJAX queries in parallel much slower than doing serially?
I have a page where angular uses ng-init to run a few ajax call's to populate the page. The page took about 1s to load, and I found that strange so I did a little digging.

This was the original code (minus error handling)

```<code>accountService.roles(null, function (response) {
    $scope.roles = response;
});
masterDataService.getallparties(null, function (response) {
    $scope.parties = response;
});
accountService.users($scope.searchFilter, function (response) {
    $scope.users = response;
});
</code>```

Now I did a rewrite using serial calls instead of parallel:

```<code>accountService.roles(null, function (response) {
    $scope.roles = response;
    masterDataService.getallparties(null, function (response) {
        $scope.parties = response;
        accountService.users($scope.searchFilter, function (response) {
            $scope.users = response;
        });
    });
});
</code>```

And voila, the page now loads in about 100ms.

Is this expected? Is there something on my server (IIS / MVC 4.6) that's wrong?

EDIT: added screenshots

答: Browsers limit the number of simultaneous requests per domain. For Internet Explorer, this value is configurable in the Registry and is set by default to 2. See https://support.microsoft.com/en-us/help/282402/how-do-i-configure-internet-explorer-to-download-more-than-two-files-at-one-time.</p>

Body:
I have a page where angular uses ng-init to run a few ajax call's to populate the page. The page took about 1s to load, and I found that strange so I did a little digging.

This was the original code (minus error handling)

accountService.roles(null, function (response) {
    $scope.roles = response;
});
masterDataService.getallparties(null, function (response) {
    $scope.parties = response;
});
accountService.users($scope.searchFilter, function (response) {
    $scope.users = response;
});

Now I did a rewrite using serial calls instead of parallel:

accountService.roles(null, function (response) {
    $scope.roles = response;
    masterDataService.getallparties(null, function (response) {
        $scope.parties = response;
        accountService.users($scope.searchFilter, function (response) {
            $scope.users = response;
        });
    });
});

And voila, the page now loads in about 100ms.

Is this expected? Is there something on my server (IIS / MVC 4.6) that's wrong?

EDIT: added screenshots


问:
Adding a class to "body"
How can I modify or pre-process the  tag to add the class body? I don't want to create a whole html.tpl.php just to add a class.

答:
Common Body Class module provide users to add classes to any page through the an interface.
The interface has options to select multiple user roles as well as pages where the class can be rendered.

Title: Adding a class to "body"


问:
PDO query binding string instead of integer returns results
I have a table with and auto increment id and was just testing a few scenarios when I stumbled across a problem whereby PDO or mysql seems to convert a string to an integer when in an array.  Does anyone know why?

If my query is as follows:

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>1));
</code>```

it retrieves 1 record - all fine, but if the query uses a string either by design or mistake as follows:

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>'1 OR id > 0'));
</code>```

it still retrieves a record with id=1.

Surely nothing should be found?  I appreciate I should never allow the 2nd scenario to happen but why is PDO / mysql converting the string to an integer and how is it doing it?

答:
It's because execute create somthing like: SELECT * FROM tbl_test WHERE id='1 OR id > 0'

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id OR id>:id2");
$check->execute(array(':id'=>'1', ':id2' => 0));
</code>```

or just

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id>:id");
$check->execute(array(':id'=>'0'));
</code>```

Body:
I have a table with and auto increment id and was just testing a few scenarios when I stumbled across a problem whereby PDO or mysql seems to convert a string to an integer when in an array.  Does anyone know why?

If my query is as follows:

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>1));

it retrieves 1 record - all fine, but if the query uses a string either by design or mistake as follows:

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>'1 OR id > 0'));

it still retrieves a record with id=1.

Surely nothing should be found?  I appreciate I should never allow the 2nd scenario to happen but why is PDO / mysql converting the string to an integer and how is it doing it?

Body:
It's because execute create somthing like: SELECT * FROM tbl_test WHERE id='1 OR id > 0'

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id OR id>:id2");
$check->execute(array(':id'=>'1', ':id2' => 0));

or just

$check = $db->prepare("SELECT * FROM tbl_test WHERE id>:id");
$check->execute(array(':id'=>'0'));


问:
excel VBA populate column based on other filtered column
I am trying to fill an empty sheet column based on a filtered column right next to it. This is how I capture the two columns to only include and perform on visible rows:

```<code>Set rng = Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
Set rng2 = Range("N2:N" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
</code>```

Let's assume I have a value in rCell. I want now to add rCell to all cell values in rng and put it into the same row of rng2

I tried to loop through each cell in rng, add rCell and put its value into the corresponding row of rng2

```<code>        i = 0
        For Each cl In rng
            rng2(i).Value = cl + rCell
            i = i + 1
        Next
</code>```

cl manages to get the correct values of filtered cells of rng but it adds them to unfiltered column of rng2. Thus, indexing seems not to work!

答:
Maybe you can try something like that :</p>

```<code>For Each cl In Rng
    cl.Offset(0, 1).Value = cl + rCell
Next
</code>```

Body:
I am trying to fill an empty sheet column based on a filtered column right next to it. This is how I capture the two columns to only include and perform on visible rows:

Set rng = Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
Set rng2 = Range("N2:N" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)

Let's assume I have a value in rCell. I want now to add rCell to all cell values in rng and put it into the same row of rng2

I tried to loop through each cell in rng, add rCell and put its value into the corresponding row of rng2

        i = 0
        For Each cl In rng
            rng2(i).Value = cl + rCell
            i = i + 1
        Next

cl manages to get the correct values of filtered cells of rng but it adds them to unfiltered column of rng2. Thus, indexing seems not to work!

Body:
Maybe you can try something like that :

For Each cl In Rng
    cl.Offset(0, 1).Value = cl + rCell
Next


答:
You should make another class, like $not_active = "class=\"not-active-menu\"";
And add that to your code</p>

```<code><li>
     <a href="something.php" <?php if ($current_url == "something.php") {echo $active;} else { echo $not_active; }?>>
     <i class="fa fa-qrcode"></i> something
     </a>
</li>
</code>```

Title: Show active navigation for current page

Body:
i'm having some problems with my html, php code. With this code, my nav will show the active li but the other pages which are not active won't have style or links.

    <?php
    $current_url = basename($_SERVER['PHP_SELF']);
    $active = "class=\"active-menu\"";
    ?>

                    <?php if ($current_url == "home.php") { ?>
                    <a <?php echo $active;?> href="home.php"><?php } ?> Dashboard

                    <?php if ($current_url == "new.php") { ?>
                    <a <?php echo $active;?> href="new.php"><?php } ?> Nieuw item toevoegen

                    <?php if ($current_url == "show.php") { ?>
                    <a <?php echo $active;?> href="show.php"><?php } ?> Bekijk inventaris

                    <?php if ($current_url == "profile.php") { ?>
                    <a <?php echo $active;?> href="profile.php"><?php } ?> Gebruikersprofiel

                     Gebruikers

                            Beheerders

                            ICT - Verantwoordelijken

                            Raadplegers

                    <?php if ($current_url == "empty.php") { ?>
                    <a <?php echo $active;?> href="empty.php"><?php } ?> Lege pagina

the pages with no styling will also not have a link. The active-menu class has the styling.

Body:
You should make another class, like $not_active = "class=\"not-active-menu\"";
And add that to your code

<li>
     <a href="something.php" <?php if ($current_url == "something.php") {echo $active;} else { echo $not_active; }?>>
     <i class="fa fa-qrcode"></i> something
     </a>
</li>


问:
Sending and receiving data over Bluetooth Low Energy (BLE) using Telit BlueMod+SR
We are looking at using the Telit BlueMod+SR chip in a hardware idea we are working on. Towards that I've been trying to build a Bluetooth Low Energy (BLE) server simulation using the Telit BlueEva+SR evaluation board driven over USB by a Python script.

The two relevant manuals appear to be:

BlueMod+SR AT Command Reference

Terminal I/O Profile Client Implementation Guide (though I'm implementing the server)

(N.B. these are available here but are behind a register/login.)

I'm stuck on something basic: how to send or receive data. I understand that this is done by setting the value of a Generic Attribute Profile (GATT) service's characteristic. The BlueMod+SR already has the GATT service characteristics that I need (a UART data TX characteristic and a UART data RX characteristic) on its Terminal I/O Service. The UUID's of the characteristics I need are given in the Terminal I/O Profile Client Implementation Guide but I cannot see how to read from nor write to them. The AT Command Reference has a section on GATT Server commands but the only one listed, +LEATTRIB, is for defining the attributes for a service (and the ones I need are already defined).

What are the commands I need to read and write the values for the characteristics UART Data TX, UART Data RX, UART Credits TX, and UART Credits RX?

答: It turns out that I did not need to use the credit mechanism, that's handled for me. So to write to the TX characteristic I can either connect to BLE and just write the data, or use the multiplexing and write the data to channel 0x01 (Terminal I/O). Reading the RX characteristic si similarly just reading the serial connection.</p>


问:
How to save full ListView Data (which i fetch from Internet) contained (bitmap and strings) to internal memory
How to save full ListView Data (which i fetch from Internet) contained (bitmap and strings) to internal memory for Future Use when Internet is not Available.

This is My Main Code:DisplayList.java```
    public class DisplayList extends ListActivity {</p>

<code>    List<Flower> flowerList;
    ProgressBar progressBar;
    List<GetData> task;
    public static final String PHOTO_BASE_URL="http://services.hanselandpetal.com/photos/";
    private static final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_list);
      //  textView=(TextView)findViewById(R.id.data);
      //  textView.setMovementMethod(new ScrollingMovementMethod());

        progressBar=(ProgressBar)findViewById(R.id.progressBar);
        progressBar.setVisibility(View.INVISIBLE);
        task=new ArrayList<>();

        if(isOnline())
        {
            requestData("http://services.hanselandpetal.com/feeds/flowers.json");
        }
        else
        {
            Toast.makeText(DisplayList.this, "Network is not Available", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

//        if (id == R.id.task1)
//        {
//
//        }

        return super.onOptionsItemSelected(item);
    }

    private void requestData(String url) {
        GetData getData=new GetData();
        getData.execute(url);
    }

    public void update()
    {
        //Use FlowerAdapter to display data
        FlowerAdapter adapter = new FlowerAdapter(this, R.layout.item_flower, flowerList);
        setListAdapter(adapter);

    }

    protected boolean isOnline()
    {
        ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        if(networkInfo!=null && networkInfo.isConnectedOrConnecting())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private class GetData extends AsyncTask<String,String,List<Flower>>
    {
        @Override
        protected void onPreExecute()
        {
            // update("Task Started");
            if(task.size()==0) {
                progressBar.setVisibility(View.VISIBLE);
            }
            task.add(this);
        }

        @Override
        protected List<Flower> doInBackground(String... params) {
            String content="Internet is to slow";
            content=HttpManager1.getDataByHttpUrlConnection(params[0]);
            flowerList= FlowerJSONParser.parseFeed(content);

//            for(Flower flower:flowerList)
//            {
//                try
//                {
//                    String imageUrl=PHOTO_BASE_URL+flower.getPhoto();
//                    InputStream inputStream=(InputStream)new URL(imageUrl).getContent();
//                    Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
//                    flower.setBitmap(bitmap);
//                    inputStream.close();
//                }
//                catch (Exception e)
//                {
//                    e.printStackTrace();
//                }
//
//            }

            return flowerList;
        }

        @Override
        public void onPostExecute(List<Flower> result)
        {

            update();

            task.remove(this);
            if(task.size()==0) {
                progressBar.setVisibility(View.INVISIBLE);
            }

        }

        @Override
        protected void onProgressUpdate(String... values) {
            //update(values[0]);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Flower flower=flowerList.get(position);
        Intent intent=new Intent(this,DetailActivity.class);
        intent.putExtra("flowerName",flower.getName());
        intent.putExtra("imageBitmap",flower.getBitmap());
        intent.putExtra("instruction",flower.getInstructions());
        startActivityForResult(intent, REQUEST_CODE);

    }

}

```
```

In the above Program I am fetching flowerList (which contained bitmaps and Strings) from server in doInBackground-Method and pass it into FlowerAdapter to set ListView Items.
Can you please give me a way to stored all bitmap images and Strings(contained names and description) to Internal Memory.If you take this example and solve my big problem then i will be very appreciable to you.

答:
You just create a databse for local storage where just create a table with column name (id,flowerName,imageBitmap,instruction) and what ever you want to add after creating table just insert your data in localDB and when ever you need just fetch from there.

for creating database just make a class which extends SQLiteOpenHelper and in that implement  onCreate and onUpgrade method

in oncreate you just execute your table creation query.

Thanks!

Body:
How to save full ListView Data (which i fetch from Internet) contained (bitmap and strings) to internal memory for Future Use when Internet is not Available.

This is My Main Code:DisplayList.java

    public class DisplayList extends ListActivity {

    List<Flower> flowerList;
    ProgressBar progressBar;
    List<GetData> task;
    public static final String PHOTO_BASE_URL="http://services.hanselandpetal.com/photos/";
    private static final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_list);
      //  textView=(TextView)findViewById(R.id.data);
      //  textView.setMovementMethod(new ScrollingMovementMethod());

        progressBar=(ProgressBar)findViewById(R.id.progressBar);
        progressBar.setVisibility(View.INVISIBLE);
        task=new ArrayList<>();

        if(isOnline())
        {
            requestData("http://services.hanselandpetal.com/feeds/flowers.json");
        }
        else
        {
            Toast.makeText(DisplayList.this, "Network is not Available", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

//        if (id == R.id.task1)
//        {
//
//        }

        return super.onOptionsItemSelected(item);
    }

    private void requestData(String url) {
        GetData getData=new GetData();
        getData.execute(url);
    }

    public void update()
    {
        //Use FlowerAdapter to display data
        FlowerAdapter adapter = new FlowerAdapter(this, R.layout.item_flower, flowerList);
        setListAdapter(adapter);

    }

    protected boolean isOnline()
    {
        ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        if(networkInfo!=null && networkInfo.isConnectedOrConnecting())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private class GetData extends AsyncTask<String,String,List<Flower>>
    {
        @Override
        protected void onPreExecute()
        {
            // update("Task Started");
            if(task.size()==0) {
                progressBar.setVisibility(View.VISIBLE);
            }
            task.add(this);
        }

        @Override
        protected List<Flower> doInBackground(String... params) {
            String content="Internet is to slow";
            content=HttpManager1.getDataByHttpUrlConnection(params[0]);
            flowerList= FlowerJSONParser.parseFeed(content);

//            for(Flower flower:flowerList)
//            {
//                try
//                {
//                    String imageUrl=PHOTO_BASE_URL+flower.getPhoto();
//                    InputStream inputStream=(InputStream)new URL(imageUrl).getContent();
//                    Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
//                    flower.setBitmap(bitmap);
//                    inputStream.close();
//                }
//                catch (Exception e)
//                {
//                    e.printStackTrace();
//                }
//
//            }

            return flowerList;
        }

        @Override
        public void onPostExecute(List<Flower> result)
        {

            update();

            task.remove(this);
            if(task.size()==0) {
                progressBar.setVisibility(View.INVISIBLE);
            }

        }

        @Override
        protected void onProgressUpdate(String... values) {
            //update(values[0]);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Flower flower=flowerList.get(position);
        Intent intent=new Intent(this,DetailActivity.class);
        intent.putExtra("flowerName",flower.getName());
        intent.putExtra("imageBitmap",flower.getBitmap());
        intent.putExtra("instruction",flower.getInstructions());
        startActivityForResult(intent, REQUEST_CODE);

    }

}

In the above Program I am fetching flowerList (which contained bitmaps and Strings) from server in doInBackground-Method and pass it into FlowerAdapter to set ListView Items.
Can you please give me a way to stored all bitmap images and Strings(contained names and description) to Internal Memory.If you take this example and solve my big problem then i will be very appreciable to you.


问:
Select Option with Previous and next by jQuery
I have bug when I click next or prev button. Here is my HTML

$("#nextPage").click(function() {
  $('#pagination option:selected').next().attr('selected', 'selected');
  console.log("hahaha next");
})

$("#prevPage").click(function() {
  $('#pagination option:selected').prev().attr('selected', 'selected');
  console.log("prev");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
     <option value="1" selected>1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
    </select>
<input type="button" value="next" id="nextPage"></code>```

Here is my jsfiddle

Thank you

答:
Use prop instead of attr and its work perfect.

$("#nextPage").click(function() {
  $('#pagination option:selected').next().prop('selected', 'selected');
  console.log("hahaha next");
})

$("#prevPage").click(function() {
  $('#pagination option:selected').prev().prop('selected', 'selected');
  console.log("prev");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
  <option value="1" selected>1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>
<input type="button" value="next" id="nextPage"></code>```

Body:
I have bug when I click next or prev button. Here is my HTML

$("#nextPage").click(function() {
  $('#pagination option:selected').next().attr('selected', 'selected');
  console.log("hahaha next");
})

$("#prevPage").click(function() {
  $('#pagination option:selected').prev().attr('selected', 'selected');
  console.log("prev");
});

<input type="button" value="prev" id="prevPage">
<select id="pagination">
     <option value="1" selected>1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
    </select>
<input type="button" value="next" id="nextPage">

Here is my jsfiddle

Thank you

Body:
Use prop instead of attr and its work perfect.

$("#nextPage").click(function() {
  $('#pagination option:selected').next().prop('selected', 'selected');
  console.log("hahaha next");
})

$("#prevPage").click(function() {
  $('#pagination option:selected').prev().prop('selected', 'selected');
  console.log("prev");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
  <option value="1" selected>1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>
<input type="button" value="next" id="nextPage">


答:
Use .prop instead of .attr as .attr will just add an extra attribute to each option whilst .prop will actually change the selected item

$("#nextPage").click(function() {
  $('#pagination option:selected').next().prop('selected', true);
  console.log("hahaha next");
})

$("#prevPage").click(function() {
  $('#pagination option:selected').prev().prop('selected', true);
  console.log("prev");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
     <option value="1" selected>1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
    </select>
<input type="button" value="next" id="nextPage"></code>```

Title: Select Option with Previous and next by jQuery

Body:
Use .prop instead of .attr as .attr will just add an extra attribute to each option whilst .prop will actually change the selected item

$("#nextPage").click(function() {
  $('#pagination option:selected').next().prop('selected', true);
  console.log("hahaha next");
})

$("#prevPage").click(function() {
  $('#pagination option:selected').prev().prop('selected', true);
  console.log("prev");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
     <option value="1" selected>1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
    </select>
<input type="button" value="next" id="nextPage">


问:
QR Code reader & generator in Swift
Currently in Objective-C, i use Zbar(http://zbar.sourceforge.net/) to generate & read QR Code. Now, i want to move on Swift development only, is there any 'how to' or library about generate and read QR Code in Swift ?</p>

答:
SWIFT 3: QR Code Reader

STEP FIRST: Simply add a row in info.plist and type Privacy - CameraUsageDescription into the newly created row and add a string meant for informing the user on why access to the camera is needed within your app.

STEP SECOND: Use this code in your ViewController class

```<code>class QrCodeScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

var calssName:String = "QrCodeScannerViewController"

var captureSession:AVCaptureSession?
var videoPreviewLayer:AVCaptureVideoPreviewLayer?
var qrCodeFrameView:UIView?

@IBOutlet weak var messageLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    captureQRCode()

}

/* Open camera to capture QR CODE */
func captureQRCode() {
    captureSession = AVCaptureSession()
    let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    let input = try! AVCaptureDeviceInput(device: device) as AVCaptureDeviceInput
    captureSession?.addInput(input)

    let output = AVCaptureMetadataOutput()
    output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
    captureSession?.addOutput(output)
    output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]

    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    let bounds = self.view.layer.bounds
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.bounds = bounds
    videoPreviewLayer?.position = CGPoint(x:bounds.midX, y:bounds.midY)

    self.view.layer.addSublayer(videoPreviewLayer!)
    captureSession?.startRunning()
}

/* onAtivityResult from App Delegate */
func captureOutput(_ captureOutput: AVCaptureOutput!,
                   didOutputMetadataObjects metadataObjects: [Any]!,
                   from connection: AVCaptureConnection!) {
    for item in metadataObjects {
        if let metadataObject = item as? AVMetadataMachineReadableCodeObject {
            if metadataObject.type == AVMetadataObjectTypeQRCode {

                print("QR Code: \(metadataObject.stringValue)")
                hideCamera(voucherHashkey: metadataObject.stringValue)

            }
        }
    }

}

/* Hide camera after getting result */
func hideCamera(voucherHashkey:String){

    self.captureSession?.stopRunning()
    self.videoPreviewLayer?.removeFromSuperlayer()
    self.videoPreviewLayer = nil;
    self.captureSession = nil;

    // sendVocherDataToServer(voucherHashKey: voucherHashkey)

}
}
</code>```

Title: QR Code reader & generator in Swift

Body:
SWIFT 3: QR Code Reader

STEP FIRST: Simply add a row in info.plist and type Privacy - CameraUsageDescription into the newly created row and add a string meant for informing the user on why access to the camera is needed within your app.

STEP SECOND: Use this code in your ViewController class

class QrCodeScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

var calssName:String = "QrCodeScannerViewController"

var captureSession:AVCaptureSession?
var videoPreviewLayer:AVCaptureVideoPreviewLayer?
var qrCodeFrameView:UIView?

@IBOutlet weak var messageLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    captureQRCode()

}

/* Open camera to capture QR CODE */
func captureQRCode() {
    captureSession = AVCaptureSession()
    let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    let input = try! AVCaptureDeviceInput(device: device) as AVCaptureDeviceInput
    captureSession?.addInput(input)

    let output = AVCaptureMetadataOutput()
    output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
    captureSession?.addOutput(output)
    output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]

    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    let bounds = self.view.layer.bounds
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.bounds = bounds
    videoPreviewLayer?.position = CGPoint(x:bounds.midX, y:bounds.midY)

    self.view.layer.addSublayer(videoPreviewLayer!)
    captureSession?.startRunning()
}

/* onAtivityResult from App Delegate */
func captureOutput(_ captureOutput: AVCaptureOutput!,
                   didOutputMetadataObjects metadataObjects: [Any]!,
                   from connection: AVCaptureConnection!) {
    for item in metadataObjects {
        if let metadataObject = item as? AVMetadataMachineReadableCodeObject {
            if metadataObject.type == AVMetadataObjectTypeQRCode {

                print("QR Code: \(metadataObject.stringValue)")
                hideCamera(voucherHashkey: metadataObject.stringValue)

            }
        }
    }

}

/* Hide camera after getting result */
func hideCamera(voucherHashkey:String){

    self.captureSession?.stopRunning()
    self.videoPreviewLayer?.removeFromSuperlayer()
    self.videoPreviewLayer = nil;
    self.captureSession = nil;

    // sendVocherDataToServer(voucherHashKey: voucherHashkey)

}
}


答:
http://www.vogella.com/tutorials/AndroidSQLite/article.html

Please read the above tutorial for working with sqlite .The main issue of saving data would be resolved when there is no internet connection.Other that that use image library like Picasso or Fresco to save image in your local memmory.

Title: How to save full ListView Data (which i fetch from Internet) contained (bitmap and strings) to internal memory