问:
I am not able to scroll to elements below the list view. How to view those
I am using a ScrollView inside which I am using RelativeLayout inside which I am using ListView inside HorizontalScrollView. Now after that i am placing a button but not able to scroll to that button as the page is not scrolling, just the ListView is scrolling.

I want the list to scroll and after the list is finished the page should scroll so that i can see the button to click it

how to do that

I am sharing my xml that I have made so far

main.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<RelativeLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/heading2"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:text="Horizontal List View"
        android:textSize="30dp"
        android:textStyle="bold"
        android:focusable="true"/>

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:id="@+id/hori_scroll_view"
        android:layout_below="@+id/heading2"
        android:layout_marginTop="20dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/list"/>

    </HorizontalScrollView>

    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/page2"
        android:layout_below="@+id/hori_scroll_view"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Next" />

</RelativeLayout>
</ScrollView>
</code>```

答:
You can do this with RecyclerView

```<code><ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/heading2"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:text="Horizontal List View"
        android:textSize="30dp"
        android:textStyle="bold"
        android:focusable="true"/>

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="370dp"
            android:layout_below="@+id/heading2"
            android:layout_marginTop="20dp"
            android:scrollbars="horizontal"
            android:id="@+id/list"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/page2"
        android:layout_below="@+id/list"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Next" />
</RelativeLayout>
</ScrollView>
</code>```

Then Add this in your Activity,

```<code>LinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        RecyclerView myList = findViewById(R.id.list);
        myList.setLayoutManager(layoutManager);
</code>```

Body:
I am using a ScrollView inside which I am using RelativeLayout inside which I am using ListView inside HorizontalScrollView. Now after that i am placing a button but not able to scroll to that button as the page is not scrolling, just the ListView is scrolling.

I want the list to scroll and after the list is finished the page should scroll so that i can see the button to click it

how to do that

I am sharing my xml that I have made so far

main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<RelativeLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/heading2"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:text="Horizontal List View"
        android:textSize="30dp"
        android:textStyle="bold"
        android:focusable="true"/>

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:id="@+id/hori_scroll_view"
        android:layout_below="@+id/heading2"
        android:layout_marginTop="20dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/list"/>

    </HorizontalScrollView>

    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/page2"
        android:layout_below="@+id/hori_scroll_view"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Next" />

</RelativeLayout>
</ScrollView>

Body:
You can do this with RecyclerView

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/heading2"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:text="Horizontal List View"
        android:textSize="30dp"
        android:textStyle="bold"
        android:focusable="true"/>

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="370dp"
            android:layout_below="@+id/heading2"
            android:layout_marginTop="20dp"
            android:scrollbars="horizontal"
            android:id="@+id/list"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/page2"
        android:layout_below="@+id/list"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Next" />
</RelativeLayout>
</ScrollView>

Then Add this in your Activity,

LinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        RecyclerView myList = findViewById(R.id.list);
        myList.setLayoutManager(layoutManager);


来源: stackexchange

问:
MySQL Markup all records on Select with same values (first one included)
Connected with MySQL Markup Records with Duplicates on Select. The difference is I want to markup not only actually duplicated records but all records with same values including first one.

```<code>id     name
--------------
1      John    # mark this
2      Peter
3      John    # this
4      David
5      John    # and this
</code>```

The approach proposed by @m-khalid-junaid https://stackoverflow.com/a/47728321/1056384

```<code>SELECT DISTINCT a.*,
CASE WHEN b.id IS NULL THEN 0 ELSE 1 end `duplicate`
FROM tab a
LEFT JOIN tab b ON a.name = b.name AND a.id > b.id
ORDER BY a.id
</code>```

It has one or two problems for me:

It not markups first occurrence of "duplicate" record in group.

It uses order by id (not sure if it depends) but I need to sort result in real complex query by different ways.

If it makes sense for query optimization, my task is a little bit more complex. Actually, I need to markup duplicates inside groups only:

```<code>id   group  name
--------------
1    1      John    # mark this (dups in group #1)
2    1      Peter
3    1      John    # mark this (dups in group #1)
4    2      David
5    2      John    # this is not (it's in group #2)
</code>```

答:
While you can adjust the given query to your needs, I would use an EXISTS subquery here instead of a join.

```<code>select t.id, t.group, t.name, exists (
  select * from tab t2
  where t2.group = t.group
    and t2.name  = t.name
    and t2.id <> t.id
) as is_duplicate
from tab t
order by t.group, is_duplicate, t.name
</code>```

http://sqlfiddle.com/#!9/d24012/4

ContentLicense: CC BY-SA 3.0

Body:
Connected with MySQL Markup Records with Duplicates on Select. The difference is I want to markup not only actually duplicated records but all records with same values including first one.

id     name
--------------
1      John    # mark this
2      Peter
3      John    # this
4      David
5      John    # and this

The approach proposed by @m-khalid-junaid https://stackoverflow.com/a/47728321/1056384

SELECT DISTINCT a.*,
CASE WHEN b.id IS NULL THEN 0 ELSE 1 end `duplicate`
FROM tab a
LEFT JOIN tab b ON a.name = b.name AND a.id > b.id
ORDER BY a.id

It has one or two problems for me:

It not markups first occurrence of "duplicate" record in group.

It uses order by id (not sure if it depends) but I need to sort result in real complex query by different ways.

If it makes sense for query optimization, my task is a little bit more complex. Actually, I need to markup duplicates inside groups only:

id   group  name
--------------
1    1      John    # mark this (dups in group #1)
2    1      Peter
3    1      John    # mark this (dups in group #1)
4    2      David
5    2      John    # this is not (it's in group #2)

Body:
While you can adjust the given query to your needs, I would use an EXISTS subquery here instead of a join.

select t.id, t.group, t.name, exists (
  select * from tab t2
  where t2.group = t.group
    and t2.name  = t.name
    and t2.id <> t.id
) as is_duplicate
from tab t
order by t.group, is_duplicate, t.name

http://sqlfiddle.com/#!9/d24012/4


问:
How to address multidimensional json array in Python
I have a following context received from a query in Python script (an example):

{
    "active": false,
    "owner": "user1",
    "content": [
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]
      }
    ]
  }

making this to json array works without errors:

```<code>data = json.loads(*string_above*)
</code>```

as a result this works ok:

```<code>print data["owner"]
</code>```

user1

also this is ok:

```<code>print data["content"]
</code>```

[
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]}

Now my problem is how can I make this a multidimensional array?

E.g. command

```<code>print data["content"]["record"]
</code>```

gives an error:

TypeError: list indices must be integers, not str

what I was hoping to get is:

{
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }

Found many different comments on this kind of problem with Google but is there no a simple solution - what am I missing?

答:
I think you're confused. Let's fix that. The initial object you're returning is a dict not an array (list in Python speak).

```<code>d = { "active": False, "owner": "user1", "content": [ { "recordType": "test", "record": [ { ": id": "1", "date": "Nov 30, 2017 12:00:00 AM", "link": "http://localhost", "Size": 1234, }, { "id": "3", "date": "Nov 21, 2017 06:00:00 AM", "link": "http://localhost", "Size": 3241, } ] } ] }
isinstance(d, dict)
# True
</code>```

The thing you grab from d is a list:

```<code>isinstance(data["content"], list)
# True
</code>```

whose elements need to be referenced using int. So, to get the first element of data['content'] which is a dict, you would do

```<code>c0 = data['content'][0]
isinstance(c0, dict)
# True
</code>```

Body:
I have a following context received from a query in Python script (an example):

{
    "active": false,
    "owner": "user1",
    "content": [
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]
      }
    ]
  }

making this to json array works without errors:

data = json.loads(*string_above*)

as a result this works ok:

print data["owner"]

user1

also this is ok:

print data["content"]

[
      {
        "recordType": "test",
        "record": [
          {
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }      ]}

Now my problem is how can I make this a multidimensional array?

E.g. command

print data["content"]["record"]

gives an error:

TypeError: list indices must be integers, not str

what I was hoping to get is:

{
            "id": "1",
            "date": "Nov 30, 2017 12:00:00 AM",
            "link": "http://localhost",
            "Size": 1234,
          },
          {
            "id": "3",
            "date": "Nov 21, 2017 06:00:00 AM",
            "link": "http://localhost",
            "Size": 3241,
          }

Found many different comments on this kind of problem with Google but is there no a simple solution - what am I missing?

Body:
I think you're confused. Let's fix that. The initial object you're returning is a dict not an array (list in Python speak).

d = { "active": False, "owner": "user1", "content": [ { "recordType": "test", "record": [ { ": id": "1", "date": "Nov 30, 2017 12:00:00 AM", "link": "http://localhost", "Size": 1234, }, { "id": "3", "date": "Nov 21, 2017 06:00:00 AM", "link": "http://localhost", "Size": 3241, } ] } ] }
isinstance(d, dict)
# True

The thing you grab from d is a list:

isinstance(data["content"], list)
# True

whose elements need to be referenced using int. So, to get the first element of data['content'] which is a dict, you would do

c0 = data['content'][0]
isinstance(c0, dict)
# True


问:
Encapsulation concept
I have problem with concept and implementation of encapsulation.

Can someone explain it to me?

答:
Encapsulation is a moderately easy concept once you realise it (probably) comes from the same base word as capsule.

It's simply a containment of information.

Encapsulation means that a class publishes only what is needed for others to use it, and no more. This is called information hiding and it means classes can totally change their internals without having an effect on any of their users.

In other words, a dictionary class can begin life as a simple array and progress to a binary tree of words then even maybe to some database access functions, all without changing the interface to it.

In an object oriented world, objects hold both their data and the methods used to manipulate data and that is the pinnacle of encapsulation. One way this is done is to make sure each object knows which functions to call to manipulate its data, and ensure the correct ones are called.

As an example, here's a class for maintaining integer lists in my mythical, but strangely Python-like and therefore hopefully easy to understand, language:

class intlist:
    private int val[10]    # Slots for storing numbers.
    private bool used[10]  # Whether slot is used or not.

    public constructor:
        # Mark all slots unused.

        for i in 0..9:
            used[i] = false

    public function add(int v) throws out-of-memory:
         # Check each slot.

        for i in 0..9:
            # If unused, store value, mark used, return.

            if not used[i]:
                used[i] = true
                val[i] = v
                return

        # No free slots, so throw exception.

        throw out-of-memory

    public function del(int v) throws bad-value:
         # Check each slot.

        for i in 0..9:
            # If slot used and contains value.

            if used[i] and val[i] == v:
                # Mark unused and return.

                used[i] = false
                return

        # Value not found in any used slot, throw exception.

        throw bad-value

    public function has(int v):
         # Check each slot.

        for i in 0..9:
            # If slot used and contains value.

            if used[i] and val[i] == v:
                return true

        # Value not found in any used slot.

        return false
```

Now the only information published here are the constructor and three functions for adding, deleting, and checking for values (including what exceptions can be thrown).

Callers need know nothing about the internal data structures being used (val and used), or the properties of the functions beyond their "signatures" (the content of the "function" lines).

Because everything else is encapsulated, it can changed it at will without breaking the code that uses it.

I could, for example, do any of the following:

make the arrays longer;

store the data sorted, or in a binary tree instead of an array to make it faster.

change the used array into a count array (initialised to zero) so that many occurrences of a single number use just the one slot, increasing the quantity of numbers that can be stored where there are duplicates.

store the numbers in a database, located on a ZX-80 retro-computer located in outback Australia, and powered by methane produced from kangaroo droppings (though you may notice a latency change).

Basically, as long as the published API doesn't change, we am free to do whatever we want. In fact, we can also add things to the API without breaking other code, I just can't delete or change anything that users already rely on.

You should note that encapsulation isn't something new with object orientation. It's been around for ages, even in C by ensuring that information is hidden within a module (usually a source file or group thereof with private headers).

In fact, the stdio.h FILE* stuff is a good example of this. You don't care what's actually behind the pointer since all the functions which use it know how to do their stuff.

ContentLicense: CC BY-SA 2.5

Title: Encapsulation concept

Body:
Encapsulation is a moderately easy concept once you realise it (probably) comes from the same base word as capsule.

It's simply a containment of information.

Encapsulation means that a class publishes only what is needed for others to use it, and no more. This is called information hiding and it means classes can totally change their internals without having an effect on any of their users.

In other words, a dictionary class can begin life as a simple array and progress to a binary tree of words then even maybe to some database access functions, all without changing the interface to it.

In an object oriented world, objects hold both their data and the methods used to manipulate data and that is the pinnacle of encapsulation. One way this is done is to make sure each object knows which functions to call to manipulate its data, and ensure the correct ones are called.

As an example, here's a class for maintaining integer lists in my mythical, but strangely Python-like and therefore hopefully easy to understand, language:

class intlist:
    private int val[10]    # Slots for storing numbers.
    private bool used[10]  # Whether slot is used or not.

    public constructor:
        # Mark all slots unused.

        for i in 0..9:
            used[i] = false

    public function add(int v) throws out-of-memory:
         # Check each slot.

        for i in 0..9:
            # If unused, store value, mark used, return.

            if not used[i]:
                used[i] = true
                val[i] = v
                return

        # No free slots, so throw exception.

        throw out-of-memory

    public function del(int v) throws bad-value:
         # Check each slot.

        for i in 0..9:
            # If slot used and contains value.

            if used[i] and val[i] == v:
                # Mark unused and return.

                used[i] = false
                return

        # Value not found in any used slot, throw exception.

        throw bad-value

    public function has(int v):
         # Check each slot.

        for i in 0..9:
            # If slot used and contains value.

            if used[i] and val[i] == v:
                return true

        # Value not found in any used slot.

        return false

Now the only information published here are the constructor and three functions for adding, deleting, and checking for values (including what exceptions can be thrown).

Callers need know nothing about the internal data structures being used (val and used), or the properties of the functions beyond their "signatures" (the content of the "function" lines).

Because everything else is encapsulated, it can changed it at will without breaking the code that uses it.

I could, for example, do any of the following:

make the arrays longer;

store the data sorted, or in a binary tree instead of an array to make it faster.

change the used array into a count array (initialised to zero) so that many occurrences of a single number use just the one slot, increasing the quantity of numbers that can be stored where there are duplicates.

store the numbers in a database, located on a ZX-80 retro-computer located in outback Australia, and powered by methane produced from kangaroo droppings (though you may notice a latency change).

Basically, as long as the published API doesn't change, we am free to do whatever we want. In fact, we can also add things to the API without breaking other code, I just can't delete or change anything that users already rely on.

You should note that encapsulation isn't something new with object orientation. It's been around for ages, even in C by ensuring that information is hidden within a module (usually a source file or group thereof with private headers).

In fact, the stdio.h FILE* stuff is a good example of this. You don't care what's actually behind the pointer since all the functions which use it know how to do their stuff.

ContentLicense: CC BY-SA 4.0


问:
Eliminate Nulls
I'm out of luck finding information...

This powershell script collecting cert info in LocalMachine:

```<code>$cert_days = get-childitem cert:LocalMAchine -recurse  |
select  @{Name="{#CERTINFO}"; Expression={($_.FriendlyName)}} |
Sort "{#CERTINFO}"

write-host "{"
write-host " `"data`":`n"

convertto-json $cert_days

write-host
write-host "}"
</code>```

I can't exclude Nulls or empty items like " ".

Using  -ne $Null i get boolean results like true or false...

I would appreciate to hear Yours advice how to eliminate nulls or empty entries

答:
To exclude empty entries, you could add a filter to remove those, preferably before the Sort-Object call., e.g.

```<code>$certs = ls Cert:\LocalMachine\ -Recurse |
    Select @{Name = '{#CertInfo}'; Expression = {$_.FriendlyName}} |
    Where { $_.'{#CertInfo}' } |
    Sort '{#CertInfo}'
</code>```

Title: Eliminate Nulls

Body:
I'm out of luck finding information...

This powershell script collecting cert info in LocalMachine:

$cert_days = get-childitem cert:LocalMAchine -recurse  |
select  @{Name="{#CERTINFO}"; Expression={($_.FriendlyName)}} |
Sort "{#CERTINFO}"

write-host "{"
write-host " `"data`":`n"

convertto-json $cert_days

write-host
write-host "}"

I can't exclude Nulls or empty items like " ".

Using  -ne $Null i get boolean results like true or false...

I would appreciate to hear Yours advice how to eliminate nulls or empty entries

Body:
To exclude empty entries, you could add a filter to remove those, preferably before the Sort-Object call., e.g.

$certs = ls Cert:\LocalMachine\ -Recurse |
    Select @{Name = '{#CertInfo}'; Expression = {$_.FriendlyName}} |
    Where { $_.'{#CertInfo}' } |
    Sort '{#CertInfo}'


问:
How Do I Use The CSS Background Property?
```<code>body {
  background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
}
</code>```

That's my CSS for my body, yet, it won't load the image, but somehow,

```<code>body {
  background-color: #fff;
  background-image: url("milkshakeonthewindowsill.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
</code>```

this code does. What am I missing or doing wrong?

答:
In my experience, size cover has to be added separately:

```<code>body {
  background: url("milkshakeonthewindowsill.jpg") no-repeat fixed;
  background-size: cover;
}
</code>```

Body:
body {
  background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
}

That's my CSS for my body, yet, it won't load the image, but somehow,

body {
  background-color: #fff;
  background-image: url("milkshakeonthewindowsill.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

this code does. What am I missing or doing wrong?

Body:
In my experience, size cover has to be added separately:

body {
  background: url("milkshakeonthewindowsill.jpg") no-repeat fixed;
  background-size: cover;
}


问:
Expo xde is not launching on centOS?
I download the Expo Ide(.AppImage) from official site

https://docs.expo.io/versions/latest/introduction/installation.html

of expo and followed the following instructions:

```<code>chmod a+x xde*.AppImage
./xde*.AppImage
</code>```

but I am not able to launch a the xde on my system.

I have restarted all my development environment.

答:
the * sign refers to your specific version. Replace the * for the numbers there. For instance, </p>

```<code>chmod a+x xde-2.22.1-x86_64.AppImage
./xde-2.22.1-x86_64.AppImage
</code>```

Title: Expo xde is not launching on centOS?

Body:
I download the Expo Ide(.AppImage) from official site

https://docs.expo.io/versions/latest/introduction/installation.html

of expo and followed the following instructions:

chmod a+x xde*.AppImage
./xde*.AppImage

but I am not able to launch a the xde on my system.

I have restarted all my development environment.

Body:
the * sign refers to your specific version. Replace the * for the numbers there. For instance,

chmod a+x xde-2.22.1-x86_64.AppImage
./xde-2.22.1-x86_64.AppImage


问:
Create Kubernetes Pod with MySQL and PHP?

Hi there,
I have a docker container that is a php backend. I have created a kubernetes pod of this container. This is what my yml file looks like:

```<code> apiVersion: v1
 kind: Pod
 metadata:
  name: backend
  spec:
  containers:
 - name: backend
  image: 000.dkr.ecr.eu-west-1.amazonaws.com/fullstackapp
  ports:
  - containerPort: 8000
</code>```

However I want to be able to connect my MySql database (which is also a docker container) to the backend in the same pod.  However I have no idea how to go about doing this.  Any help would be appreciated!

答:
Well,

Since you have dockerized your app (you made an docker image), you also must use a docker image for your MySql database.

But here is the kicker, you need also to create services for your app pod and your MySql pod.

You can find all the details in the k8 documentation (which is really good)

To make myself clear:

1.) First create a deployment object for your app.

2.) Then make a service for your app.

You rinse and repeat for the MySql database.

1.) You need the deployment object (and not the pod kind), because the deployment object keeps you pod alive when one breaks, for instance if you have tree replicas (pods) the replicaSet that the deployment object uses, will make sure that there are three replicas of your app.

2.) Services will group your pods (via labels), because the pods that the deployment object will generate will have a short life (ephemeral), meaning their IP address will be unstable and you wont be able to rely on them.

So, you will use services that will give you a cluster IP (virtual IP), that other objects can use. For instance; when your app wants to connect to the MySQL database.

You can use the name of the MySQL service in your apps configuration files.

So, basically that's how you would connect a MySQL pod to you apps pod.

Take a look at the katacode project, they give you a playground to learn this kind of stuff.

Tom

Body:
Hi there,
I have a docker container that is a php backend. I have created a kubernetes pod of this container. This is what my yml file looks like:

 apiVersion: v1
 kind: Pod
 metadata:
  name: backend
  spec:
  containers:
 - name: backend
  image: 000.dkr.ecr.eu-west-1.amazonaws.com/fullstackapp
  ports:
  - containerPort: 8000

However I want to be able to connect my MySql database (which is also a docker container) to the backend in the same pod.  However I have no idea how to go about doing this.  Any help would be appreciated!


问:
How many SparkSessions can a single application have?
I have found that as Spark runs, and tables grow in size (through Joins) that the spark executors will eventually run out of memory and the entire system crashes. Even if I try to write temporary results to Hive tables (on HDFS), the system still doesn't free much memory, and my entire system crashes after about 130 joins.

However, through experimentation, I realized that if I break the problem into smaller pieces, write temporary results to hive tables, and Stop/Start the Spark session (and spark context), then the system's resources are freed. I was able to join over 1,000 columns using this approach.

But I can't find any documentation to understand if this is considered a good practice or not (I know you should not acquire multiple sessions at once). Most systems acquire the session in the beginning and close it in the end. I could also break the application into smaller ones, and use a driver like Oozie to schedule these smaller applications on Yarn. But this approach would start and stop the JVM at each stage, which seems a bit heavy-weight.

So my question: is it bad practice to continually start/stop the spark session to free system resources during the run of a single spark application?

But can you elaborate on what you mean by a single SparkContext on a single JVM? I was able call sparkSession.sparkContext().stop(), and also stop the SparkSession. I then created a new SparkSession and used a new sparkContext. No error was thrown.

I was also able to use this on the JavaSparkPi without any problems.

I have tested this in yarn-client and a local spark install.

What exactly does stopping the spark context do, and why can you not create a new one once you've stopped one?

答:
TL;DR You can have as many SparkSessions as needed.

You can have one and only one SparkContext on a single JVM, but the number of SparkSessions is pretty much unbounded.

But can you elaborate on what you mean by a single SparkContext on a single JVM?

It means that at any given time in the lifecycle of a Spark application the driver can only be one and only one which in turn means that there's one and only one SparkContext on that JVM available.

The driver of a Spark application is where the SparkContext lives (or it's the opposite rather where SparkContext defines the driver -- the distinction is pretty much blurry).

You can only have one SparkContext at one time. Although you can start and stop it on demand as many times you want, but I remember an issue about it that said you should not close SparkContext unless you're done with Spark (which usually happens at the very end of your Spark application).

In other words, have a single SparkContext for the entire lifetime of your Spark application.

There was a similar question What's the difference between SparkSession.sql vs Dataset.sqlContext.sql? about multiple SparkSessions that can shed more light on why you'd want to have two or more sessions.

I was able call sparkSession.sparkContext().stop(), and also stop the SparkSession.

So?! How does this contradict what I said?! You stopped the only SparkContext available on the JVM. Not a big deal. You could, but that's just one part of "you can only have one and only one SparkContext on a single JVM available", isn't it?

SparkSession is a mere wrapper around SparkContext to offer Spark SQL's structured/SQL features on top of Spark Core's RDDs.

From the point of Spark SQL developer, the purpose of a SparkSession is to be a namespace for query entities like tables, views or functions that your queries use (as DataFrames, Datasets or SQL) and Spark properties (that could have different values per SparkSession).

If you'd like to have the same (temporary) table name used for different Datasets, creating two SparkSessions would be what I'd consider the recommended way.

I've just worked on an example to showcase how whole-stage codegen works in Spark SQL and have created the following that simply turns the feature off.

```<code>// both where and select operators support whole-stage codegen
// the plan tree (with the operators and expressions) meets the requirements
// That's why the plan has WholeStageCodegenExec inserted
// You can see stars (*) in the output of explain
val q = Seq((1,2,3)).toDF("id", "c0", "c1").where('id === 0).select('c0)
scala> q.explain
== Physical Plan ==
*Project [_2#89 AS c0#93]
+- *Filter (_1#88 = 0)
   +- LocalTableScan [_1#88, _2#89, _3#90]

// Let's break the requirement of having up to spark.sql.codegen.maxFields
// I'm creating a brand new SparkSession with one property changed
val newSpark = spark.newSession()
import org.apache.spark.sql.internal.SQLConf.WHOLESTAGE_MAX_NUM_FIELDS
newSpark.sessionState.conf.setConf(WHOLESTAGE_MAX_NUM_FIELDS, 2)

scala> println(newSpark.sessionState.conf.wholeStageMaxNumFields)
2

// Let's see what's the initial value is
// Note that I use spark value (not newSpark)
scala> println(spark.sessionState.conf.wholeStageMaxNumFields)
100

import newSpark.implicits._
// the same query as above but created in SparkSession with WHOLESTAGE_MAX_NUM_FIELDS as 2
val q = Seq((1,2,3)).toDF("id", "c0", "c1").where('id === 0).select('c0)

// Note that there are no stars in the output of explain
// No WholeStageCodegenExec operator in the plan => whole-stage codegen disabled
scala> q.explain
== Physical Plan ==
Project [_2#122 AS c0#126]
+- Filter (_1#121 = 0)
   +- LocalTableScan [_1#121, _2#122, _3#123]
</code>```

I then created a new SparkSession and used a new SparkContext. No error was thrown.

Again, how does this contradict what I said about a single SparkContext being available? I'm curious.

What exactly does stopping the spark context do, and why can you not create a new one once you've stopped one?

You can no longer use it to run Spark jobs (to process large and distributed datasets) which is pretty much exactly the reason why you use Spark in the first place, doesn't it?

Try the following:

Stop SparkContext

Execute any processing using Spark Core's RDD or Spark SQL's Dataset APIs

An exception? Right! Remember that you close the "doors" to Spark so how could you have expected to be inside?! :)

Body:
TL;DR You can have as many SparkSessions as needed.

You can have one and only one SparkContext on a single JVM, but the number of SparkSessions is pretty much unbounded.

But can you elaborate on what you mean by a single SparkContext on a single JVM?

It means that at any given time in the lifecycle of a Spark application the driver can only be one and only one which in turn means that there's one and only one SparkContext on that JVM available.

The driver of a Spark application is where the SparkContext lives (or it's the opposite rather where SparkContext defines the driver -- the distinction is pretty much blurry).

You can only have one SparkContext at one time. Although you can start and stop it on demand as many times you want, but I remember an issue about it that said you should not close SparkContext unless you're done with Spark (which usually happens at the very end of your Spark application).

In other words, have a single SparkContext for the entire lifetime of your Spark application.

There was a similar question What's the difference between SparkSession.sql vs Dataset.sqlContext.sql? about multiple SparkSessions that can shed more light on why you'd want to have two or more sessions.

I was able call sparkSession.sparkContext().stop(), and also stop the SparkSession.

So?! How does this contradict what I said?! You stopped the only SparkContext available on the JVM. Not a big deal. You could, but that's just one part of "you can only have one and only one SparkContext on a single JVM available", isn't it?

SparkSession is a mere wrapper around SparkContext to offer Spark SQL's structured/SQL features on top of Spark Core's RDDs.

From the point of Spark SQL developer, the purpose of a SparkSession is to be a namespace for query entities like tables, views or functions that your queries use (as DataFrames, Datasets or SQL) and Spark properties (that could have different values per SparkSession).

If you'd like to have the same (temporary) table name used for different Datasets, creating two SparkSessions would be what I'd consider the recommended way.

I've just worked on an example to showcase how whole-stage codegen works in Spark SQL and have created the following that simply turns the feature off.

// both where and select operators support whole-stage codegen
// the plan tree (with the operators and expressions) meets the requirements
// That's why the plan has WholeStageCodegenExec inserted
// You can see stars (*) in the output of explain
val q = Seq((1,2,3)).toDF("id", "c0", "c1").where('id === 0).select('c0)
scala> q.explain
== Physical Plan ==
*Project [_2#89 AS c0#93]
+- *Filter (_1#88 = 0)
   +- LocalTableScan [_1#88, _2#89, _3#90]

// Let's break the requirement of having up to spark.sql.codegen.maxFields
// I'm creating a brand new SparkSession with one property changed
val newSpark = spark.newSession()
import org.apache.spark.sql.internal.SQLConf.WHOLESTAGE_MAX_NUM_FIELDS
newSpark.sessionState.conf.setConf(WHOLESTAGE_MAX_NUM_FIELDS, 2)

scala> println(newSpark.sessionState.conf.wholeStageMaxNumFields)
2

// Let's see what's the initial value is
// Note that I use spark value (not newSpark)
scala> println(spark.sessionState.conf.wholeStageMaxNumFields)
100

import newSpark.implicits._
// the same query as above but created in SparkSession with WHOLESTAGE_MAX_NUM_FIELDS as 2
val q = Seq((1,2,3)).toDF("id", "c0", "c1").where('id === 0).select('c0)

// Note that there are no stars in the output of explain
// No WholeStageCodegenExec operator in the plan => whole-stage codegen disabled
scala> q.explain
== Physical Plan ==
Project [_2#122 AS c0#126]
+- Filter (_1#121 = 0)
   +- LocalTableScan [_1#121, _2#122, _3#123]

I then created a new SparkSession and used a new SparkContext. No error was thrown.

Again, how does this contradict what I said about a single SparkContext being available? I'm curious.

What exactly does stopping the spark context do, and why can you not create a new one once you've stopped one?

You can no longer use it to run Spark jobs (to process large and distributed datasets) which is pretty much exactly the reason why you use Spark in the first place, doesn't it?

Try the following:

Stop SparkContext

Execute any processing using Spark Core's RDD or Spark SQL's Dataset APIs

An exception? Right! Remember that you close the "doors" to Spark so how could you have expected to be inside?! :)


问:
Looking for a good practice for dealing with repository in asp.net mvc
Currently I've got repository class for each data model for data access.

In the homepage, I need to display the top 5 records from each repository. So in the HomeController, I would need to have a lot of repository members, which doesn't feel right. Is there any good solution for this?

Thank you very much for your help. Any advice is welcome!

答:
I second Darin Dimitrov's response.

In my experience it is usual (in desktop development) to have a service layer that does all the talking to your repositories.

e.g.

View Model

Service

Repository1 : Repository 2

Data Access 1 : Data Access 2

then from the top end your only ever calling your service(s) which keeps things neet.


问:
C# - 3D array of 3D arrays
I want to have a very large 3D grid. If I simply create a 3D array (i.e T[,,]) I'm going to end up having a lot of unused (3D) positions in that grid, and due to memory usage, the grid will be far from how large I need it to be.

So my I idea is to make a "hollow" 3D grid of sub 3D grids (aka chunks) where each position contains a sub 3D grid. For chunks that are empty, the 3D array of that chunk does not exist in the parent 3D grid.

So I have a value of type : T[,,][,,]

Where the "top level" grid that contains the chunks is going to be a 3D array whose positions contain references to the chunks, or null if the chunk is empty.

My question is : how do I even initialize a value of type T[,,][,,] ? If I do new T[3,3,3][3,3,3] for example, the compiler is yelling :

```<code>CS0178  Invalid rank specifier: expected ',' or ']'
</code>```

Thank you.

答:
The syntax for creating a new array is as follows:

```<code>T[,,][,,] a = new T[3,3,3][,,];
</code>```

This gives you a 3D array of null values. You can set them to non-null 3D arrays as needed:

```<code>a[1,2,2] = new T[8,8,8];
</code>```

You may consider other alternatives for storing "chunks" of your 3D grid - for example, you could make a Dictionary with three-element tuples as keys and 3D arrays as values. This Q&A describes other available alternatives for implementing 3D matrices in C#.

Title: C# - 3D array of 3D arrays

Body:
I want to have a very large 3D grid. If I simply create a 3D array (i.e T[,,]) I'm going to end up having a lot of unused (3D) positions in that grid, and due to memory usage, the grid will be far from how large I need it to be.

So my I idea is to make a "hollow" 3D grid of sub 3D grids (aka chunks) where each position contains a sub 3D grid. For chunks that are empty, the 3D array of that chunk does not exist in the parent 3D grid.

So I have a value of type : T[,,][,,]

Where the "top level" grid that contains the chunks is going to be a 3D array whose positions contain references to the chunks, or null if the chunk is empty.

My question is : how do I even initialize a value of type T[,,][,,] ? If I do new T[3,3,3][3,3,3] for example, the compiler is yelling :

CS0178  Invalid rank specifier: expected ',' or ']'

Thank you.

Body:
The syntax for creating a new array is as follows:

T[,,][,,] a = new T[3,3,3][,,];

This gives you a 3D array of null values. You can set them to non-null 3D arrays as needed:

a[1,2,2] = new T[8,8,8];

You may consider other alternatives for storing "chunks" of your 3D grid - for example, you could make a Dictionary with three-element tuples as keys and 3D arrays as values. This Q&A describes other available alternatives for implementing 3D matrices in C#.


问:
How to increment value within a  tag
Hi I want to increment the value within an  and increment it by 1 every time a button is clicked. The code i have so far is shown below:

```<code><a data-role="button" data-icon="shop" class="ui-btn-right ui-shadow ui-corner-all ui-btn-icon-center ui-icon-heart" id="Count" style="text-align: center;">0</a>

<script>

btn.onclick = function() {
  var linkText = parseInt(document.getElementById('Count').value);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('Count').value = value;
  }
</script>
</code>```

however it does not update the value of  once I press the button. I want to be able to change the value of  tag for example 0 and once the button is pressed  tag will display 1

答:
Use textContent instead of value, which is a property reserved for input elements.

var count = document.getElementById('Count');

document.getElementById('button').onclick = function() {
  var linkText = +count.textContent;

  count.textContent = ++linkText;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="button">Increment</button>

0</code>```

Title: How to increment value within a <a> tag

Body:
Hi I want to increment the value within an  and increment it by 1 every time a button is clicked. The code i have so far is shown below:

0

however it does not update the value of  once I press the button. I want to be able to change the value of  tag for example 0 and once the button is pressed  tag will display 1

Body:
Use textContent instead of value, which is a property reserved for input elements.

var count = document.getElementById('Count');

document.getElementById('button').onclick = function() {
  var linkText = +count.textContent;

  count.textContent = ++linkText;
}

<button id="button">Increment</button>

<a data-role="button" id="Count">0</a>


问:
getting timestamp in php
How can I get the timestamp of a desired hour?  The hour is in a variable that the user set.</p>

答: You can use mktime() function to build timestamp of any datetime.</p>

Title: getting timestamp in php


问:
What is the best way to store market data for Algorithmic Trading setup?
I am making an Algorithmic Trading setup for trades automation. Currently, I have a broker API which helps me get historical data for all stocks that I'm interested in.

I am wondering how to store all the data, whether in a file system or database (SQL based or NoSQL). Data comes through REST API if thats relevant.

My use case here would be to query historical data to make trading decisions in live market. I would also have to develop a backtesting framework that will query Historical Data to check performance of strategy historically.

I am looking at a frequency of 5 mins - 1 hr candles and mostly Intraday trading strategies. Thanks

答:
As you say, there are many options and as STLDeveloper says this is kind of off topic since it is opinion based... anyway...

A simple strategy which I used in my own Python back-testing engine is to use Python Pandas DataFrame objects, and save/load to disk in an HD5 file using to_hdf() and read_hdf(). The primary advantage (for me) of HD5 is that it loads/saves far more quickly than CSV.

Using the above approach I easily manage several years of 1 minute data for back testing purposes, and data access certainly is not my performance bottleneck.

You will need to determine for yourself if your chosen data management approach is fast enough for live trading, but in general I think if your strategy is based on 5-min candles then any reasonable database approach is going to be sufficiently performant for your purposes.


问:
Android send POST request in Java to ASP.net Web API
When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. It seems not working.

```<code>String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());

JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));

OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();

BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
    response.append(output);
    response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();
</code>```

When executing the above code, it will have an FileNotFoundException in

```<code>conn.getInputStream()
</code>```

I also tried to implement source code in HttpClient style.

```<code>HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);

try {
     StringEntity se = new StringEntity((new Gson()).toJson(data));
     httpPost.setEntity(se);
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-Type", "application/json");

     HttpResponse response = httpClient.execute(httpPost);
     InputStream inputStream = response.getEntity().getContent();

     String result = "";
     if (inputStream != null)
          result = convertInputStreamToString(inputStream);
     else
          result = "Did not work!";

     Log.i("RESPONSE", result);

 } catch (Exception ex) {
     Log.i("Exception", ex.getMessage());
 }
 return output;
</code>```

And this time, it shows "The requested resource does not support http method 'get'".

I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. Any recommendations?

Finally, the following coding is my ASP.net Web API for reference.

```<code>[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
     var resp = new HttpResponseMessage(HttpStatusCode.OK);
     resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
     return resp;
}
</code>```

答:
Finally, I got a solution to fix this problem. It is due to the POST data in request body can not be read from Web API.

When the request Content-Type is "application/json",

Using string, The request body should be a plain text (e.g. "Text Message").

```<code>[FromBody] string inStr
</code>```

Using self-defined class, The request body should be a json string
(e.g { KEY: VALUE })

```<code>[FromBody] YourClass inObj
</code>```

Using array of self-defined class, The request body should be a json array string (e.g [{ KEY: VALUE }])

```<code>[FromBody] YourClass[] inObj
</code>```

And the self-defined class should be like as following:-

```<code>class YourClass {
    public string KEY { get; set; }
}
</code>```

Btw. Thanks for all reply and useful information.

Body:
When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. It seems not working.

String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());

JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));

OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();

BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
    response.append(output);
    response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();

When executing the above code, it will have an FileNotFoundException in

conn.getInputStream()

I also tried to implement source code in HttpClient style.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);

try {
     StringEntity se = new StringEntity((new Gson()).toJson(data));
     httpPost.setEntity(se);
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-Type", "application/json");

     HttpResponse response = httpClient.execute(httpPost);
     InputStream inputStream = response.getEntity().getContent();

     String result = "";
     if (inputStream != null)
          result = convertInputStreamToString(inputStream);
     else
          result = "Did not work!";

     Log.i("RESPONSE", result);

 } catch (Exception ex) {
     Log.i("Exception", ex.getMessage());
 }
 return output;

And this time, it shows "The requested resource does not support http method 'get'".

I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. Any recommendations?

Finally, the following coding is my ASP.net Web API for reference.

[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
     var resp = new HttpResponseMessage(HttpStatusCode.OK);
     resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
     return resp;
}

Body:
Finally, I got a solution to fix this problem. It is due to the POST data in request body can not be read from Web API.

When the request Content-Type is "application/json",

Using string, The request body should be a plain text (e.g. "Text Message").

[FromBody] string inStr

Using self-defined class, The request body should be a json string
(e.g { KEY: VALUE })

[FromBody] YourClass inObj

Using array of self-defined class, The request body should be a json array string (e.g [{ KEY: VALUE }])

[FromBody] YourClass[] inObj

And the self-defined class should be like as following:-

class YourClass {
    public string KEY { get; set; }
}

Btw. Thanks for all reply and useful information.


问:
How to deal with Huawei's and Xiaomi's "battery optimizations"
I have an app that listens for notifications via NotificationListenerService. My app survives both the Doze mode and app stand by on almost any phone (if properly set-up e.g. exception or a foreground service).

Then come the Huawei and Xiaomi with their own modifications of Android to "improve battery life". These can mess with background running apps so badly that after a week or two the app must be reinstalled. Even clearing data will not "unfreeze" the app. Even exceptions to their own "optimizations" does not reliably fix this. Only completely disabling all their optimizations e.g. enabling "high performance mode" might fix this. But users do not want to disable these options.

How do you deal with these cases? And how can we stop manufacturers to stop messing with core Android? Not to mention the funny ANRs & crashes in Zygote :(

答:
Then come the Huawei and Xiaomi with their own modifications of Android to "improve battery life".

Yes Xiaomi, Huawei and a few other manufacturers have their own layer of "Battery Saver" or "Security" that kills or restricts background running apps in order to improve security/battery backup, unless user white-lists your app in the relevant device settings.

What i found out about Xiaomi is that they white-list well known apps like Facebook, Whatsapp, etc. But you cannot request Xiaomi to white-list your app.

These can mess with background running apps so badly that after a week or two the app must be reinstalled. Even clearing data will not "unfreeze" the app.

These manufacturer apps simply terminate your app process. So your app should behave in such a way that termination at any moment should not create inconsistent state.

Also, you can always show a popup to user after installation asking him/her to go and white-list your app in battery saver. In Xiaomi, the user will need to select 'Do not restrict background activity' and also enable 'Auto Start' for your app. As far as i know, there is no other solution.

Let me know if you find one ;)


问:
Postgresql jsonb default insert value with dynamic timestamp
I have a status column in my postgres database with the type jsonb

I can prepopulate the json with something like this.

CREATE TABLE ...
  status jsonb NOT NULL DEFAULT '{"hello": "world"}'
 ...

But what I am asking and what I would like to have is a JSON property with a timestamp prepolulated using the function now()

CREATE TABLE ...
  status jsonb NOT NULL DEFAULT '{"created_at": "'now()'"}'
 ...

CREATE TABLE ...
  status jsonb NOT NULL DEFAULT '{"created_at": "'+now()'+"}'
 ...

Unfortunately these approaches above do not work. What would be the way to do it?

答:
You must create the JSONB at runtime using jsonb_build_object:

```<code>CREATE TABLE foobar
    (status jsonb NOT NULL DEFAULT jsonb_build_object('created_at', now()));
</code>```

SQL Fiddle here.

Body:
You must create the JSONB at runtime using jsonb_build_object:

CREATE TABLE foobar
    (status jsonb NOT NULL DEFAULT jsonb_build_object('created_at', now()));

SQL Fiddle here.


问:
urllib cannot read https
(Python 3.4.2)
Would anyone be able to help me fetch https pages with urllib? I've spent hours trying to figure this out.

Here's what I'm trying to do (pretty basic):

```<code>import urllib.request
url = "".join((baseurl, other_string, midurl, query))
response = urllib.request.urlopen(url)
html = response.read()
</code>```

Here's my error output when I run it:

```<code>File "./script.py", line 124, in <module>
    response = urllib.request.urlopen(url)
  File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 455, in open
    response = self._open(req, data)
  File "/usr/lib/python3.4/urllib/request.py", line 478, in _open
    'unknown_open', req)
  File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 1244, in unknown_open
    raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: 'https>
</code>```

I've also tried using data=None to no avail:

```<code>response = urllib.request.urlopen(url, data=None)
</code>```

I've also tried this:

```<code>import urllib.request, ssl
https_sslv3_handler = urllib.request.HTTPSHandler(context=ssl.SSLContext(ssl.PROTOCOL_SSLv3))
opener = urllib.request.build_opener(https_sslv3_handler)
urllib.request.install_opener(opener)
resp = opener.open(url)
html = resp.read().decode('utf-8')
print(html)
</code>```

A similar error occurs with this^ script, where the error is found on the "resp = ..." line and complains that 'https' is an unknown url type.

Python was compiled with SSL support on my computer (Arch Linux). I've tried reinstalling python3 and openssl a few times, but that doesn't help. I haven't tried to uninstall python completely and then reinstall because I would also need to uninstall a lot of other programs on my computer.

Anyone know what's going on?

-----EDIT-----

I figured it out, thanks to help from Andrew Stevlov's answer. My url had a ":" in it, and I guess urllib didn't like that. I replaced it with "%3A" and now it's working. Thanks so much guys!!!

答:
this may help

Ignore SSL certificate errors

```<code>ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
</code>```

Title: urllib cannot read https

Body:
(Python 3.4.2)
Would anyone be able to help me fetch https pages with urllib? I've spent hours trying to figure this out.

Here's what I'm trying to do (pretty basic):

import urllib.request
url = "".join((baseurl, other_string, midurl, query))
response = urllib.request.urlopen(url)
html = response.read()

Here's my error output when I run it:

File "./script.py", line 124, in <module>
    response = urllib.request.urlopen(url)
  File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 455, in open
    response = self._open(req, data)
  File "/usr/lib/python3.4/urllib/request.py", line 478, in _open
    'unknown_open', req)
  File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 1244, in unknown_open
    raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: 'https>

I've also tried using data=None to no avail:

response = urllib.request.urlopen(url, data=None)

I've also tried this:

import urllib.request, ssl
https_sslv3_handler = urllib.request.HTTPSHandler(context=ssl.SSLContext(ssl.PROTOCOL_SSLv3))
opener = urllib.request.build_opener(https_sslv3_handler)
urllib.request.install_opener(opener)
resp = opener.open(url)
html = resp.read().decode('utf-8')
print(html)

A similar error occurs with this^ script, where the error is found on the "resp = ..." line and complains that 'https' is an unknown url type.

Python was compiled with SSL support on my computer (Arch Linux). I've tried reinstalling python3 and openssl a few times, but that doesn't help. I haven't tried to uninstall python completely and then reinstall because I would also need to uninstall a lot of other programs on my computer.

Anyone know what's going on?

-----EDIT-----

I figured it out, thanks to help from Andrew Stevlov's answer. My url had a ":" in it, and I guess urllib didn't like that. I replaced it with "%3A" and now it's working. Thanks so much guys!!!

Body:
this may help

Ignore SSL certificate errors

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()


问:
iOS - Regionmonitoring in StandBy
I´ve implemented a monitoring function for beacons (didEnterRegion).
It works great if I use my iPhone. (App is in foreground, background or only installed and closed but my iPhone has to be in use (screen on).)

If my phone is in standBy mode (top button pressed), I get no notification with didEnterRegion.
If I use my phone (screen on), the notification pop up.
Is there an opportunity to get the didEnterRegion event also in the standby mode?

```<code>self->beaconLocationManager = [[CLLocationManager alloc] init];
[self->beaconLocationManager requestAlwaysAuthorization];
self->beaconLocationManager.delegate = self;
beaconLocationManager.allowsBackgroundLocationUpdates = YES;
NSString* beaconIdentName = [NSString stringWithFormat:@"Beacon%d", cnt];
NSUUID *uuid2=[[NSUUID alloc]initWithUUIDString:uuid];
clBeconRegion2=[[CLBeaconRegion alloc]initWithProximityUUID:uuid2 identifier:beaconIdentName];
clBeconRegion2.notifyOnEntry=YES;
clBeconRegion2.notifyEntryStateOnDisplay = NO;
[self->beaconLocationManager startMonitoringForRegion:clBeconRegion2];
[self->beaconLocationManager startRangingBeaconsInRegion:clBeconRegion2];

...

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"ENTER REGION");
    UILocalNotification *localNotification = [[UILocalNotification alloc]init];
    localNotification.alertBody = @"FOUNDED";
    localNotification.alertAction = [NSString stringWithFormat:@"%@ Connecting...", region.identifier];
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}
</code>```

Project settings:
Push notifications are on.
Background modes for location updates, backgroudn fetch, uses bluetooth LE accessories are on.

Tested on iOS 11.1

答:
The behavior described in the question is unusual and it does not match my experience of what I see on devices.  You are absolutely supposed to get didEnterRegion calls with a dark screen, and I have several apps on iOS 7-11.x where I have seen this happen.

The code shown looks good, and I don't even know a way to cause the behavior you describe even if you wanted to.  There must be some other unknown variable that is causing this unusual behavior on your phone.  I might try testing on a different phone, verifying you do not see this behavior, then using trial and error to try and make the phones' configurations identical until you figure out what the missing variable is.

Sorry, I know this is not an easy answer.

Title: iOS - Regionmonitoring in StandBy

Body:
I´ve implemented a monitoring function for beacons (didEnterRegion).
It works great if I use my iPhone. (App is in foreground, background or only installed and closed but my iPhone has to be in use (screen on).)

If my phone is in standBy mode (top button pressed), I get no notification with didEnterRegion.
If I use my phone (screen on), the notification pop up.
Is there an opportunity to get the didEnterRegion event also in the standby mode?

self->beaconLocationManager = [[CLLocationManager alloc] init];
[self->beaconLocationManager requestAlwaysAuthorization];
self->beaconLocationManager.delegate = self;
beaconLocationManager.allowsBackgroundLocationUpdates = YES;
NSString* beaconIdentName = [NSString stringWithFormat:@"Beacon%d", cnt];
NSUUID *uuid2=[[NSUUID alloc]initWithUUIDString:uuid];
clBeconRegion2=[[CLBeaconRegion alloc]initWithProximityUUID:uuid2 identifier:beaconIdentName];
clBeconRegion2.notifyOnEntry=YES;
clBeconRegion2.notifyEntryStateOnDisplay = NO;
[self->beaconLocationManager startMonitoringForRegion:clBeconRegion2];
[self->beaconLocationManager startRangingBeaconsInRegion:clBeconRegion2];

...

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"ENTER REGION");
    UILocalNotification *localNotification = [[UILocalNotification alloc]init];
    localNotification.alertBody = @"FOUNDED";
    localNotification.alertAction = [NSString stringWithFormat:@"%@ Connecting...", region.identifier];
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}

Project settings:
Push notifications are on.
Background modes for location updates, backgroudn fetch, uses bluetooth LE accessories are on.

Tested on iOS 11.1


问:
Javascript is concating or appending instead of adding
javascript function:

```<code>//from javascript file1
   for(i=0;i<10;i++){
      setContent(i);
   }

//from javascript file2 where function is present
        setContent: function (content) {
        var xy=0;
        xy = parseInt(xy + content);
        console.log(xy);
</code>```

Above code is appending the content instead of adding

答:
do,

```<code>xy = xy + parseInt(content);
</code>```

instead of,

```<code>xy = parseInt(xy + content);
</code>```

as by doing this xy is concatenated first then is parsed to integer

Body:
javascript function:

//from javascript file1
   for(i=0;i<10;i++){
      setContent(i);
   }

//from javascript file2 where function is present
        setContent: function (content) {
        var xy=0;
        xy = parseInt(xy + content);
        console.log(xy);

Above code is appending the content instead of adding

Body:
do,

xy = xy + parseInt(content);

instead of,

xy = parseInt(xy + content);

as by doing this xy is concatenated first then is parsed to integer


问:
Docker Container Virtual Host SSL Configuration
I have the following setup and working properly (I am on Docker 1.6):

One Docker container acts as the virtual host proxy for the other web applications running in individual Docker containers. (I should add that I am not a whiz at configuring servers, or networks for that matter.)

I have been trying to add SSL to the setup, but with little success. Each container mounts the file directory on the host for the certificates. For example, to run a container once I use the following:

```<code>docker run -d -P --name build \
    -v /home/applications/src/ssl-cert:/etc/ssl/certs \
    -e "DBL=mysql:dbname=build;host=192.168.0.1;port=3306" \
    -e "DB_USER=foo" -e "DB_PASS=bar" \
    --link mysql56:mysql \
    --add-host dockerhost:`/sbin/ip addr | grep 'eth0' | grep 'inet' | cut -d'/' -f1 | awk '{print $2}'` \
    -p 8001:80 -p 4431:443 \
     repos/build:latest
</code>```

If I attempt to connect to https://build.example.com I get certificate errors and cannot connect. The container's Apache configuration has the appropriate configuration in default-ssl.conf for the certificate files (which works if this is a stand-alone instance):

```<code><VirtualHost _default_:443>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/html/

    # Enable/Disable SSL for this virtual host.
    SSLEngine on

    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS

    SSLCertificateFile /etc/ssl/certs/build.crt
    SSLCertificateKeyFile /etc/ssl/certs/build.key
    SSLCACertificateFile /etc/ssl/certs/digicert/digicertca.crt

    #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
        SSLOptions +StdEnvVars
    </Directory>

    BrowserMatch "MSIE [2-6]" \
        nokeepalive ssl-unclean-shutdown \
        downgrade-1.0 force-response-1.0
    # MSIE 7 and newer should be able to use keepalive
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

</VirtualHost>
</code>```

Then I attempt to run the following for the proxy container:

```<code>docker run -it -d -P --name apache_proxy \
    -v /home/applications/src/ssl-cert:/etc/ssl/certs \
    -p 8000:80 -p 443:443 \
    repos/apache-proxy:latest
</code>```

This container also contains the same default-ssl.conf.

I have tried running this in several different configurations:

running the SSL config in the Apache proxy container only

running the SSL config in the build application container only

running the SSL config in both containers

If feel as if I am missing something obvious, but cannot put a finger on what it would be. Is there something I am missing when it comes to running SSL in a configuration like this?

答:
Normally if your servers run behind an apache server you would only need to configure Apache to work with SSL Certificates.
This if Apache is the only "outside" exposed server and the other servers are not directly accessible from the outside world

You would need apache to proxy to the other servers by virtue of url or port like e.g.:

```<code><VirtualHost *:443>
    ServerName SERVERNAME_HERE

    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS

    SSLCertificateFile /etc/ssl/certs/build.crt
    SSLCertificateKeyFile /etc/ssl/certs/build.key
    SSLCACertificateFile /etc/ssl/certs/digicert/digicertca.crt

    # Proxy pass to other server
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://OTHER_SERVER_IP_WITHIN_DOCKER_NETWORK:8081/
    ProxyPassReverse / http://OTHER_SERVER_IP_WITHIN_DOCKER_NETWORK:8081/

<!--Other config-->
</VirtualHost>
</code>```

Hope that helps you along...

Body:
I have the following setup and working properly (I am on Docker 1.6):

One Docker container acts as the virtual host proxy for the other web applications running in individual Docker containers. (I should add that I am not a whiz at configuring servers, or networks for that matter.)

I have been trying to add SSL to the setup, but with little success. Each container mounts the file directory on the host for the certificates. For example, to run a container once I use the following:

docker run -d -P --name build \
    -v /home/applications/src/ssl-cert:/etc/ssl/certs \
    -e "DBL=mysql:dbname=build;host=192.168.0.1;port=3306" \
    -e "DB_USER=foo" -e "DB_PASS=bar" \
    --link mysql56:mysql \
    --add-host dockerhost:`/sbin/ip addr | grep 'eth0' | grep 'inet' | cut -d'/' -f1 | awk '{print $2}'` \
    -p 8001:80 -p 4431:443 \
     repos/build:latest

If I attempt to connect to https://build.example.com I get certificate errors and cannot connect. The container's Apache configuration has the appropriate configuration in default-ssl.conf for the certificate files (which works if this is a stand-alone instance):

<VirtualHost _default_:443>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/html/

    # Enable/Disable SSL for this virtual host.
    SSLEngine on

    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS

    SSLCertificateFile /etc/ssl/certs/build.crt
    SSLCertificateKeyFile /etc/ssl/certs/build.key
    SSLCACertificateFile /etc/ssl/certs/digicert/digicertca.crt

    #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
        SSLOptions +StdEnvVars
    </Directory>

    BrowserMatch "MSIE [2-6]" \
        nokeepalive ssl-unclean-shutdown \
        downgrade-1.0 force-response-1.0
    # MSIE 7 and newer should be able to use keepalive
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

</VirtualHost>

Then I attempt to run the following for the proxy container:

docker run -it -d -P --name apache_proxy \
    -v /home/applications/src/ssl-cert:/etc/ssl/certs \
    -p 8000:80 -p 443:443 \
    repos/apache-proxy:latest

This container also contains the same default-ssl.conf.

I have tried running this in several different configurations:

running the SSL config in the Apache proxy container only

running the SSL config in the build application container only

running the SSL config in both containers

If feel as if I am missing something obvious, but cannot put a finger on what it would be. Is there something I am missing when it comes to running SSL in a configuration like this?

Body:
Normally if your servers run behind an apache server you would only need to configure Apache to work with SSL Certificates.
This if Apache is the only "outside" exposed server and the other servers are not directly accessible from the outside world

You would need apache to proxy to the other servers by virtue of url or port like e.g.:

<VirtualHost *:443>
    ServerName SERVERNAME_HERE

    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    SSLCipherSuite ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS

    SSLCertificateFile /etc/ssl/certs/build.crt
    SSLCertificateKeyFile /etc/ssl/certs/build.key
    SSLCACertificateFile /etc/ssl/certs/digicert/digicertca.crt

    # Proxy pass to other server
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass / http://OTHER_SERVER_IP_WITHIN_DOCKER_NETWORK:8081/
    ProxyPassReverse / http://OTHER_SERVER_IP_WITHIN_DOCKER_NETWORK:8081/

<!--Other config-->
</VirtualHost>

Hope that helps you along...


问:
Django Model Form does not display Image field properly and does not Post it
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates.

Here is how it looks

enter image description here

Here is the definition in the Model.

```<code>picture = models.ImageField(upload_to=user_directory_path)
</code>```

So when Django creates the Form it does it in that weird way for the File filed

How should I then define the Field for File in the Model? Or where is the error lying?

The Form had this instruction>

```<code>{% load widget_tweaks %}
<form method="post" action="{% url 'book_create' %}" class="js-book-create-form" enctype="multipart/form-data">

  {% csrf_token %}

  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
    <h4 class="modal-title">Create a new book</h4>
  </div>
  <div class="modal-body">
    {% for field in form %}
      <div class="form-group{% if field.errors %} has-error{% endif %}">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {% render_field field class="form-control" %}
        {% for error in field.errors %}
          <p class="help-block">{{ error }}</p>
        {% endfor %}
      </div>
    {% endfor %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create book</button>
  </div>
</form>
</code>```

The handling of the form was like this:

```<code>data = dict()

    if request.method == 'POST':
        form = NewStockOfBookssForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
</code>```

答:
Have you set enctype="multipart/form-data" for the form tag? This is required for fields with upload/image inputs, as described in the documentation.

How are you managing the form? If you use the FormView (or derivative) CBVs, this is done for you, but if not, you'll need to explicitly also pass files=(request.FILES or None) to the form's constructor.

Body:
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates.

Here is how it looks

enter image description here

Here is the definition in the Model.

picture = models.ImageField(upload_to=user_directory_path)

So when Django creates the Form it does it in that weird way for the File filed

How should I then define the Field for File in the Model? Or where is the error lying?

The Form had this instruction>

{% load widget_tweaks %}
<form method="post" action="{% url 'book_create' %}" class="js-book-create-form" enctype="multipart/form-data">

  {% csrf_token %}

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

Create a new book

    {% for field in form %}

        {{ field.label }}
        {% render_field field class="form-control" %}
        {% for error in field.errors %}

{{ error }}

        {% endfor %}

    {% endfor %}

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create book</button>

</form>

The handling of the form was like this:

data = dict()

    if request.method == 'POST':
        form = NewStockOfBookssForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False


问:
pointStart and pointInterval does not work
I adjusted pointStart and pointInterval within chart-options:

```<code>        xAxis: {
                   type: 'datetime',
                   ordinal: true,
                   tickInterval: 5 * 60 * 1000, // 5 minute intervals
                   minTickInterval: 5 * 60 * 1000, // 5 minute intervals
               },

               plotOptions: {
                   series: {
                     pointStart: "2017-11-25T00:00:00",
                     pointInterval: 5 * 60 * 1000, // 5 minute intervals

               }},
</code>```

When plotting, the chart is shown but with wrong x-time-axis. Start and end date is shown as "1970-01-01" and the interval between each tick is 1 ms. What is wrong?

答: Time needs to be given in milliseconds since 1970.</p>

Body:
I adjusted pointStart and pointInterval within chart-options:

        xAxis: {
                   type: 'datetime',
                   ordinal: true,
                   tickInterval: 5 * 60 * 1000, // 5 minute intervals
                   minTickInterval: 5 * 60 * 1000, // 5 minute intervals
               },

               plotOptions: {
                   series: {
                     pointStart: "2017-11-25T00:00:00",
                     pointInterval: 5 * 60 * 1000, // 5 minute intervals

               }},

When plotting, the chart is shown but with wrong x-time-axis. Start and end date is shown as "1970-01-01" and the interval between each tick is 1 ms. What is wrong?


问:
Is there any good add-ins in Visual C#2008?
My visual assist x didn't work after I installed visual c# 2008.
Is there any good add-ins like VAX? </p>

答:
The Visual Studio 2008 Comparison Chart shows that the Express editions do not support addins.

You will have to purchase at least the Standard edition to use addins.

OwnerDisplayName: Jinx

LastEditorDisplayName: Jinx

OwnerDisplayName: Joe Erickson


问:
Interlocked.Increment() not working the way I'd expect in the Task Parallel Library
I have a Parallel.ForEach() loop that takes a list of URL's and downloads each of them for some additional processing.  Outside my loop I have declared a loop counter variable and inside the loop body I use Interlocked.Increment() thinking this would be the best way to keep a "thread safe" way of increasing the count as each loop interation is performed.

```<code>int counter = 0;

Parallel.ForEach(urlList, (url, state) =>
{
    // various code statments

    Interlocked.Increment( ref counter );

    Debug.WriteLine(" ......... counter: " + counter);
});
</code>```

I would have thought that I would see something similar to:

```<code> ......... 1
 ......... 2
 ......... 3
 ......... 4
 ......... 5
 .........
 .........
 ......... n
</code>```

But what I get instead is 16 " ......... 0" (this is because I have a dual quad core computer with 8 native cores, but hyper threading is enabled giving me a total of 16 cores).  Then I will start to see the counter get incremented normally for the most part but sometimes I will see duplicate or even triplicate counter values in the Debug output.

Using a Parallel.ForEach() what is the best way to count loop iterations?  Thanks for any advice.

答: I'm not sure, but I think this is probably due to the way variable captures work in lambdas. Have you tried putting it in a separate function, or moving the variable outside and declaring it as static?</p>

Body:
I have a Parallel.ForEach() loop that takes a list of URL's and downloads each of them for some additional processing.  Outside my loop I have declared a loop counter variable and inside the loop body I use Interlocked.Increment() thinking this would be the best way to keep a "thread safe" way of increasing the count as each loop interation is performed.

int counter = 0;

Parallel.ForEach(urlList, (url, state) =>
{
    // various code statments

    Interlocked.Increment( ref counter );

    Debug.WriteLine(" ......... counter: " + counter);
});

I would have thought that I would see something similar to:

 ......... 1
 ......... 2
 ......... 3
 ......... 4
 ......... 5
 .........
 .........
 ......... n

But what I get instead is 16 " ......... 0" (this is because I have a dual quad core computer with 8 native cores, but hyper threading is enabled giving me a total of 16 cores).  Then I will start to see the counter get incremented normally for the most part but sometimes I will see duplicate or even triplicate counter values in the Debug output.

Using a Parallel.ForEach() what is the best way to count loop iterations?  Thanks for any advice.


问:
How can I import field names from a list or dictionary using prettytable in python
Every examples I saw the user knows the number and the names of columns. What if my field names are in a list or in a dictionary and I don't know the number of them?

I read that the right code would be:

```<code>t = PrettyTable()
t.set_field_names("first","second","third")
</code>```

but in my case names are inside a dictionary named columns:

```<code>columns = {column0: "first", column1: "second", column3: "third"}
</code>```

I remind the number of columns is unknown for me. I tried with:

```<code>for x in range(0,len(columns)):
    target="column"+str(x)
    t.set_field_names(columns[target])
</code>```

or with a list:

```<code>columns = ["first","second","third"]
t = PrettyTable()
t.set_field_names(columns)
</code>```

but everytime error is the same:

```<code> File "time_based_blind.py", line 105, in <module>
    t.set_field_names(columns)
 File "/usr/lib/python2.7/dist-packages/prettytable.py", line 217, in __getattr__
    raise AttributeError(name)
AttributeError: set_field_names
</code>```

答:
PrettyTable has no attribute set_field_names
you might change that to

columns = ["first","second","third"]
t = PrettyTable(columns)

Body:
Every examples I saw the user knows the number and the names of columns. What if my field names are in a list or in a dictionary and I don't know the number of them?

I read that the right code would be:

t = PrettyTable()
t.set_field_names("first","second","third")

but in my case names are inside a dictionary named columns:

columns = {column0: "first", column1: "second", column3: "third"}

I remind the number of columns is unknown for me. I tried with:

for x in range(0,len(columns)):
    target="column"+str(x)
    t.set_field_names(columns[target])

or with a list:

columns = ["first","second","third"]
t = PrettyTable()
t.set_field_names(columns)

but everytime error is the same:

 File "time_based_blind.py", line 105, in <module>
    t.set_field_names(columns)
 File "/usr/lib/python2.7/dist-packages/prettytable.py", line 217, in __getattr__
    raise AttributeError(name)
AttributeError: set_field_names


问:
php: chars from String without conversion
i try to decode a string with php. It was coded bevore with vba on another machine. The Strings will come from a database. But for the first time a hardcoded String, to find the problems. The Teststring is "¦ÞµºÎ× hg". With VBA i get the following result when exploding to chars an get the Ascii Values:

¦ÞµºÎ× hg <- the String

9 <- length of the String

1:¦:166  <- first Char = "¦", Ascii Code 166
2:Þ:222  <- second Char = "Þ", Ascii Code 222
3:µ:181  and so on
4:º:186
5:Î:206
6:×:215
7: :160
8:h:104
9:g:103```
</div>
</div>
</p>

<p>when Trying the same with php maybe php thinks this is UTF8 coded or anything else and gives me wrong chars:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>"¦ÞµºÎ× hg" <- Input String

16 <- length 16???

b"""       <- i dindn't know from where this is?!
\n
1:¦:166\n  <- first Char = "¦", Ascii Code 166, correct!
2:Ã:195\n  <- second Char = "Ã", Ascii Code 195, WTF?
3:ž:158\n
4:Â:194\n
5:µ:181\n
6:Â:194\n
7:º:186\n
8:Ã:195\n
9:Ž:142\n
10:Ã:195\n
11:—:151\n
"""

""</code>```

I've tried different ways to get the chars out of the String and i've tried different things with detect_encoding and iconv, but the result stays always the same:

$strToDecode = "¦ÞµºÎ× hg"
$lenEnc = mb_strlen($strToDecode, 'ASCII');

 $r = "";
 $asci = 0;
 $char = "";
 $rTest = "\n";
 for($i=1; $i <= $lenEnc-5; $i++) {
  //$r = Right($strToDecode, $lenEnc - $i );
  //$r = mb_substr($strToDecode, $i, 1, "ASCII");
  $r = $strToDecode[$i];
  $asci = ord($r);
  $rTest .= $i . ":" . $r . ":" . $asci . "\n";
  $strResult .= $char;
 }

dd($strToDecode, $lenEnc, $rTest, $strResult);```

What can i do, to get the real chars without changing them?

Many thanks for every tip :)

best Regards.

答:
With $strToDecode = iconv("UTF-8", "WINDOWS-1252", $strToDecode);
 i get mostly 80% of the strings encoded now. But in some cases i get
for example  iconv(): Detected an illegal character in input string, bei ¬ÛÆ¿ÄÚ¦½¢˜žn—åÖ¬Ìß¯ÊÉg[†º¤ÞÛèå«ÆÜ¢§®¾¢Ç¡ËÖÑ¨

mb_detect_encoding($strToDecode, 'auto'); says it's UTF-8 in booth cases.
In the mysql table, the data comes from there is latin 1 - latin1_german1_ci in the settings and i can't change this because the db is used from some more files since years, without this problems. They work with vba and i can't change them all ;)

Body:
i try to decode a string with php. It was coded bevore with vba on another machine. The Strings will come from a database. But for the first time a hardcoded String, to find the problems. The Teststring is "¦ÞµºÎ× hg". With VBA i get the following result when exploding to chars an get the Ascii Values:

¦ÞµºÎ× hg <- the String

9 <- length of the String

1:¦:166  <- first Char = "¦", Ascii Code 166
2:Þ:222  <- second Char = "Þ", Ascii Code 222
3:µ:181  and so on
4:º:186
5:Î:206
6:×:215
7: :160
8:h:104
9:g:103

when Trying the same with php maybe php thinks this is UTF8 coded or anything else and gives me wrong chars:

"¦ÞµºÎ× hg" <- Input String

16 <- length 16???

b"""       <- i dindn't know from where this is?!
\n
1:¦:166\n  <- first Char = "¦", Ascii Code 166, correct!
2:Ã:195\n  <- second Char = "Ã", Ascii Code 195, WTF?
3:ž:158\n
4:Â:194\n
5:µ:181\n
6:Â:194\n
7:º:186\n
8:Ã:195\n
9:Ž:142\n
10:Ã:195\n
11:—:151\n
"""

""

I've tried different ways to get the chars out of the String and i've tried different things with detect_encoding and iconv, but the result stays always the same:

$strToDecode = "¦ÞµºÎ× hg"
$lenEnc = mb_strlen($strToDecode, 'ASCII');

 $r = "";
 $asci = 0;
 $char = "";
 $rTest = "\n";
 for($i=1; $i <= $lenEnc-5; $i++) {
  //$r = Right($strToDecode, $lenEnc - $i );
  //$r = mb_substr($strToDecode, $i, 1, "ASCII");
  $r = $strToDecode[$i];
  $asci = ord($r);
  $rTest .= $i . ":" . $r . ":" . $asci . "\n";
  $strResult .= $char;
 }

dd($strToDecode, $lenEnc, $rTest, $strResult);

What can i do, to get the real chars without changing them?

Many thanks for every tip :)

best Regards.


问:
Which context should i use in a service?
I have two services in my application - lA_svc & lB_svc.

The MainActivity lauches lA_svc - which context should I use for launching the service from the activity?

Now lA_svc sends an intent to launch lB_svc - which context should I use here in the startService() method?

After a while, lB_svc sends an intent to launch lA_svc, which context do I use here?

Can you please link any gist(s), example(s) to understand the context as per which the services are to be launched?

答:
Basically both your Activity and Services are all context. While starting a service, it doesn't matter which context you use. Use you Activity/Service or even application context.

Here's a nice article that specifies when actually it matters which context to use.