问:
GKE: right way to mount same PV on multiple pods
I'm having trouble to create a persistent volume that I can use from different pods (1 write, another read).

Tried to use gcePersistentDisk directly in the pod spec like in the example on the k8s page (plus readOnly):

```<code>apiVersion: v1
kind: Pod
metadata:
  name: test-pd
spec:
  containers:
  - image: gcr.io/google_containers/test-webserver
    name: test-container
    volumeMounts:
    - mountPath: /test-pd
      name: test-volume
      readOnly: true
  volumes:
  - name: test-volume
    gcePersistentDisk:
      pdName: my-data-disk
      fsType: ext4
      readOnly: true
</code>```

Then in the second pod spec exactly the same except the readOnly ... but got an NoDiskConflict error.

Second approach is to use PersistentVolume and PersistentVolumeClaim like this:

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: data-standard
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany
  gcePersistentDisk:
    fsType: ext4
    pdName: data

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-standard-claim
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi
</code>```

But now I get an error telling me:

```<code>MountVolume.MountDevice failed for volume "kubernetes.io/gce-pd/xxx" (spec.Name: "yyy") pod "6ae34476-6197-11e7-9da5-42010a840186" (UID: "6ae34476-6197-11e7-9da5-42010a840186") with: mount failed: exit status 32 Mounting command: mount Mounting arguments: /dev/disk/by-id/google-gke-cluster-xxx /var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gke-cluster-xxx [ro] Output: mount: wrong fs type, bad option, bad superblock on /dev/sdb, missing codepage or helper program, or other error In some cases useful info is found in syslog - try dmesg | tail or so.
Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod "default"/"my-deployment". list of unattached/unmounted volumes=[data]
</code>```

So what is the correct way of using a GCE disk with multiple pods.

PS: Kubernetes 1.6.6

答: According to https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes, GCE Disks do not support ReadWriteMany. I am not sure if this explains the issue but I would advise you to try another compatible Volume type.</p>

Body:
I'm having trouble to create a persistent volume that I can use from different pods (1 write, another read).

Tried to use gcePersistentDisk directly in the pod spec like in the example on the k8s page (plus readOnly):

apiVersion: v1
kind: Pod
metadata:
  name: test-pd
spec:
  containers:
  - image: gcr.io/google_containers/test-webserver
    name: test-container
    volumeMounts:
    - mountPath: /test-pd
      name: test-volume
      readOnly: true
  volumes:
  - name: test-volume
    gcePersistentDisk:
      pdName: my-data-disk
      fsType: ext4
      readOnly: true

Then in the second pod spec exactly the same except the readOnly ... but got an NoDiskConflict error.

Second approach is to use PersistentVolume and PersistentVolumeClaim like this:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: data-standard
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany
  gcePersistentDisk:
    fsType: ext4
    pdName: data

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-standard-claim
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi

But now I get an error telling me:

MountVolume.MountDevice failed for volume "kubernetes.io/gce-pd/xxx" (spec.Name: "yyy") pod "6ae34476-6197-11e7-9da5-42010a840186" (UID: "6ae34476-6197-11e7-9da5-42010a840186") with: mount failed: exit status 32 Mounting command: mount Mounting arguments: /dev/disk/by-id/google-gke-cluster-xxx /var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gke-cluster-xxx [ro] Output: mount: wrong fs type, bad option, bad superblock on /dev/sdb, missing codepage or helper program, or other error In some cases useful info is found in syslog - try dmesg | tail or so.
Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod "default"/"my-deployment". list of unattached/unmounted volumes=[data]

So what is the correct way of using a GCE disk with multiple pods.

PS: Kubernetes 1.6.6


来源: stackexchange

问:
SQL join with selecting previous matching value with group by
I have 2 tables that I want to join on a key that matches with the first previous record.

I have a query that does this. However I also want to include a column in the results from each of the table. This forces me to include those 2 columns in the Group By attribute which is returning duplicate results.

The query I am using is similar to this (courtesy: stackoverflow):

```<code>SELECT t1.frame as frame1,
    t1.string as string1,
    max(t2.frame) as frame2,
    t2.string as string2
    FROM t1
    JOIN t2
    ON t2.frame < t1.frame and
    t1.key=t2.key
    GROUP BY t1.frame, t2.frame, t1.string, t2.string
    ORDER BY t2.frame
</code>```

The (problem) output I see is:

```<code>frame1, string1, frame2, string2
51      text1     6       text2
107253  text3     6       text2
</code>```

How can I include string2 in my results such that I don't want to group by it but only include its value for corresponding frame2?

I tried setting this up on sqlfiddle.com to make it easy to try. I populated with some dummy data but here along with this problem, I also see another problem which is it is also returning results where frame2=2. This is not expected, since it should always match frame=6. I suppose this may be side effect of grouping by string2?

Link to sqlfiddle example

Here I expect the output should only be 1 record which is:

```<code>frame1,string1,frame2,string2
51      text1    6     text2
</code>```

I am doing this on Spark SQL but this should be a generic SQL question.
Thanks.

Edit:
My data consists of incoming packets and I want to match a packet to the most recent one that came before it which has the matching ID. For e.g.

```<code>Table t2:
    frame#1:Key=a,Text=abc
    frame#2:Key=a,Text=def
    frame#3:Key=b,Text=efg
    frame#5:Key=c,Text=xyz

Table t1:
    frame#4:Key=a,Text=pqr
    frame#6:Key=c,Text=mno
</code>```

So here, for frame#4 from t1, I want to match it with frame from t2 that has come before it and has the same key. So it should match with frame#2 (not frame#3 coz key is different and not frame#1 coz frame#2 is more recent). Similarly, frame#6 should match with frame#5.

Hope it is clear now.

答:
THis query strips the tables down to "just the latest row" where "latest" is defined as "having the highest int value for the key column".

That's what the row_number() over() function does; assigns an incrementing number to a row, restarts it whenever key changes, and rows with the same key are ordered by frame descending, so the latest is always rownumber 1

```<code>SELECT
    a.frame as frame1,
    a.string as string1,
    b.frame as frame2
FROM
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t1
  ) a
  INNER JOIN
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t2
  ) b
  ON a.rown = 1 and a.key = b.key and b.rown=1
</code>```

if you need to change the definition of "latest" then change the order by to be ascending (it will give the lowest number of frame)

If as per my comment your definition of "first previous" differs, i.e. you want the row before the latest, (where a higher key number is "later") then make it rown = 2 in the ON clause, and make the order by to be key descending

(Perhaps it will help you if you just run the subqueries on their own, then look at the data and say "the rows I want always have a rown of X")

Update:

I suspect from your recent update that you want the ON clause to be where rown=2 for probably one of your tables if not the other. Because it's not clear to me which one of your tables is "behind" you'll have to edit the answer above a bit in sqlfiddle.. Here's a version that produces your requested output

```<code>SELECT
    a.frame as frame1,
    a.string as string1,
    b.frame as frame2,
    b.string
FROM
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t1
  ) a
  INNER JOIN
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t2
  ) b
  ON a.rown = 2 and a.key = b.key and b.rown=1
</code>```

You might want to test this on larger data sets

ContentLicense: CC BY-SA 3.0

Body:
I have 2 tables that I want to join on a key that matches with the first previous record.

I have a query that does this. However I also want to include a column in the results from each of the table. This forces me to include those 2 columns in the Group By attribute which is returning duplicate results.

The query I am using is similar to this (courtesy: stackoverflow):

SELECT t1.frame as frame1,
    t1.string as string1,
    max(t2.frame) as frame2,
    t2.string as string2
    FROM t1
    JOIN t2
    ON t2.frame < t1.frame and
    t1.key=t2.key
    GROUP BY t1.frame, t2.frame, t1.string, t2.string
    ORDER BY t2.frame

The (problem) output I see is:

frame1, string1, frame2, string2
51      text1     6       text2
107253  text3     6       text2

How can I include string2 in my results such that I don't want to group by it but only include its value for corresponding frame2?

I tried setting this up on sqlfiddle.com to make it easy to try. I populated with some dummy data but here along with this problem, I also see another problem which is it is also returning results where frame2=2. This is not expected, since it should always match frame=6. I suppose this may be side effect of grouping by string2?

Link to sqlfiddle example

Here I expect the output should only be 1 record which is:

frame1,string1,frame2,string2
51      text1    6     text2

I am doing this on Spark SQL but this should be a generic SQL question.
Thanks.

Edit:
My data consists of incoming packets and I want to match a packet to the most recent one that came before it which has the matching ID. For e.g.

Table t2:
    frame#1:Key=a,Text=abc
    frame#2:Key=a,Text=def
    frame#3:Key=b,Text=efg
    frame#5:Key=c,Text=xyz

Table t1:
    frame#4:Key=a,Text=pqr
    frame#6:Key=c,Text=mno

So here, for frame#4 from t1, I want to match it with frame from t2 that has come before it and has the same key. So it should match with frame#2 (not frame#3 coz key is different and not frame#1 coz frame#2 is more recent). Similarly, frame#6 should match with frame#5.

Hope it is clear now.

Body:
THis query strips the tables down to "just the latest row" where "latest" is defined as "having the highest int value for the key column".

That's what the row_number() over() function does; assigns an incrementing number to a row, restarts it whenever key changes, and rows with the same key are ordered by frame descending, so the latest is always rownumber 1

SELECT
    a.frame as frame1,
    a.string as string1,
    b.frame as frame2
FROM
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t1
  ) a
  INNER JOIN
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t2
  ) b
  ON a.rown = 1 and a.key = b.key and b.rown=1

if you need to change the definition of "latest" then change the order by to be ascending (it will give the lowest number of frame)

If as per my comment your definition of "first previous" differs, i.e. you want the row before the latest, (where a higher key number is "later") then make it rown = 2 in the ON clause, and make the order by to be key descending

(Perhaps it will help you if you just run the subqueries on their own, then look at the data and say "the rows I want always have a rown of X")

Update:

I suspect from your recent update that you want the ON clause to be where rown=2 for probably one of your tables if not the other. Because it's not clear to me which one of your tables is "behind" you'll have to edit the answer above a bit in sqlfiddle.. Here's a version that produces your requested output

SELECT
    a.frame as frame1,
    a.string as string1,
    b.frame as frame2,
    b.string
FROM
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t1
  ) a
  INNER JOIN
  (SELECT
   frame,
   key,
   string,
   row_number() over(partition by key order by frame desc) as rown
   from t2
  ) b
  ON a.rown = 2 and a.key = b.key and b.rown=1

You might want to test this on larger data sets


问:
How to make vim paste from (and copy to) system's clipboard?
Unlike other editors, vim stores copied text in its own clipboard. So, it's very hard for me to copy some text from a webpage and paste it into the current working file. It so happens I have to either open gedit or type it manually.

Can I make vim paste from and to the system's clipboard?

答:
The simplest solution to this, that also works between different Linux machines through ssh is:

Check whether vim supports X-11 clipboard: vim --version | grep clipboard. If it reports back -clipboard and -xterm_clipboard you should install either vim-gtk or vim-gnome (gvim on arch linux)

Add the following lines to your .vimrc:

```<code>set clipboard=unnamedplus
set paste
</code>```

If you login on a different machine via ssh, use the option -Y: ssh -Y machine

Now copying and pasting should work exactly as expected on a single, and across different machines by only using y for yank and p for paste. NB modify .vimrc on all machines where you want to use this feature.

Body:
The simplest solution to this, that also works between different Linux machines through ssh is:

Check whether vim supports X-11 clipboard: vim --version | grep clipboard. If it reports back -clipboard and -xterm_clipboard you should install either vim-gtk or vim-gnome (gvim on arch linux)

Add the following lines to your .vimrc:

set clipboard=unnamedplus
set paste

If you login on a different machine via ssh, use the option -Y: ssh -Y machine

Now copying and pasting should work exactly as expected on a single, and across different machines by only using y for yank and p for paste. NB modify .vimrc on all machines where you want to use this feature.


问:
Laravel does not read env variables
Did anyone has issues with env variables? For some reason, helper env('VARIABLE') returns null every time I use it. It happened very unexpectedly and I dont really know the reason. Restarting the apache/IDE/computer does not work.

答:
Run those of command

```<code>composer dump-autoload
php artisan cache:clear
php artisan config:clear
php artisan view:clear
</code>```

Now try to read

```<code>$value = env('VARIABLE_NAME');
</code>```

if not working till now then,

Try another syntax to read env variable.

```<code>$value=getenv('VARIABLE_NAME');
</code>```

Title: Laravel does not read env variables

Body:
Run those of command

composer dump-autoload
php artisan cache:clear
php artisan config:clear
php artisan view:clear

Now try to read

$value = env('VARIABLE_NAME');

if not working till now then,

Try another syntax to read env variable.

$value=getenv('VARIABLE_NAME');


问:
In Mysql,How can select new data from last select data
Use PHP.
then in mysql hava this table

```<code>Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl
</code>```

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

```<code>SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；
</code>```

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

答:
Why don't you chain the conditions?

```<code>SELECT * FROM table WHERE `where` = 'US' and `sex` = 'boy';
</code>```

Also, it's a bad idea to use reserved keywords for column names (here: "where").

Body:
Use PHP.
then in mysql hava this table

Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

Body:
Why don't you chain the conditions?

SELECT * FROM table WHERE `where` = 'US' and `sex` = 'boy';

Also, it's a bad idea to use reserved keywords for column names (here: "where").


问:
SELECT QUERY: How can I select a specific data on my table to display
I have a query below. hope someone can help me with it, I need to display ONLY all "Checking" and "Validated" under [Tbl_Aspac].[request_mode]

```<code>SELECT [Tbl_Aspac].[request_number],
       [Tbl_Aspac].[platform],
       [Tbl_Aspac].[request_type],
       [Tbl_Aspac].[environment],
       [Tbl_Aspac].[id_fid],
       [Tbl_Aspac].[requestor],
       [Tbl_Aspac].[request_mode],/*←——*/
       [Tbl_Aspac].[isa_resolver],
       [Tbl_Aspac].[logged_date],
       [Tbl_Aspac].[request_medium],
       [Tbl_Aspac].[closed_date],
       [Tbl_Aspac].[host_name]
FROM Tbl_Aspac
ORDER BY [request_number];
</code>```

As of now there's "Checking" , "Validated" and "Completed" entries, I don't want to display the "Completed" ones only the validate and Checking

I used it for my Microsoft Access project. Thanks

the table looks like this

答:
```<code>SELECT [Tbl_Aspac].[request_number], [Tbl_Aspac].[platform], [Tbl_Aspac].[request_type], [Tbl_Aspac].[environment], [Tbl_Aspac].[id_fid], [Tbl_Aspac].[requestor], [Tbl_Aspac].[request_mode], [Tbl_Aspac].[isa_resolver], [Tbl_Aspac].[logged_date], [Tbl_Aspac].[request_medium], [Tbl_Aspac].[closed_date], [Tbl_Aspac].[host_name] FROM Tbl_Aspac WHERE [Tbl_Aspac].[request_mode] in ('Checking','Validated') ORDER BY [request_number];
</code>```

Check this.. Hope this helps

Body:
I have a query below. hope someone can help me with it, I need to display ONLY all "Checking" and "Validated" under [Tbl_Aspac].[request_mode]

SELECT [Tbl_Aspac].[request_number],
       [Tbl_Aspac].[platform],
       [Tbl_Aspac].[request_type],
       [Tbl_Aspac].[environment],
       [Tbl_Aspac].[id_fid],
       [Tbl_Aspac].[requestor],
       [Tbl_Aspac].[request_mode],/*←——*/
       [Tbl_Aspac].[isa_resolver],
       [Tbl_Aspac].[logged_date],
       [Tbl_Aspac].[request_medium],
       [Tbl_Aspac].[closed_date],
       [Tbl_Aspac].[host_name]
FROM Tbl_Aspac
ORDER BY [request_number];

As of now there's "Checking" , "Validated" and "Completed" entries, I don't want to display the "Completed" ones only the validate and Checking

I used it for my Microsoft Access project. Thanks

the table looks like this

Body:
SELECT [Tbl_Aspac].[request_number], [Tbl_Aspac].[platform], [Tbl_Aspac].[request_type], [Tbl_Aspac].[environment], [Tbl_Aspac].[id_fid], [Tbl_Aspac].[requestor], [Tbl_Aspac].[request_mode], [Tbl_Aspac].[isa_resolver], [Tbl_Aspac].[logged_date], [Tbl_Aspac].[request_medium], [Tbl_Aspac].[closed_date], [Tbl_Aspac].[host_name] FROM Tbl_Aspac WHERE [Tbl_Aspac].[request_mode] in ('Checking','Validated') ORDER BY [request_number];

Check this.. Hope this helps


问:
HTML Structure how do i wrap whole content inside div or section
i am little confused with html structure, should i wrap whole content inside inside div or section, because am making body 90% width apart from footer</p>

```<code><body>
    <div class="homepage">
        <nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
            navigation
        </nav> <!-- Nav End -->
        <header>
            Header content
        </header> <!-- Header End -->
        <section class="product">
            Main content
        </section>
        <!-- <hr class="Hhr"> -->
    </div> <!-- Homepage End -->
    <footer>
        Footer copyrights annd social icons
    </footer>
    </div>
</body>
</code>```

答:
Body should have default witdht and heigth (or 100%)

In the body, you can divide it in sections (big blocks) like header, page-content, footer. (But you can use  and  tags but they are like sections too)

Imagine a newspaper.

```<code><body>
  <section class="header">
    <div class="title">
      <h1>Title</h1>
      <p>Subtitle</p>
    </div>
    <nav class="navbar">
      ... Your menu
      <ul>
        <li> ....
          ...
      </ul>
    </nav>
  </section>

  <section class="content">
    <div class="news">
      <div id="new1">
        .....
      </div>
      ...
    </div>
    <div class="rrss">
      ....
    </div>
  </section>
  <section class="footer">
    ...
    <p> Copyright </p>
  </section>
<body>
</code>```

Then you can give diferent styles to the diferent parts of page.

```<code><style>
  body{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
  }
  .header{
    width: 90%;
  }
  ...
  ...
</style>
</code>```

Body:
i am little confused with html structure, should i wrap whole content inside inside div or section, because am making body 90% width apart from footer

            navigation

            Header content

            Main content

        Footer copyrights annd social icons

Body:
Body should have default witdht and heigth (or 100%)

In the body, you can divide it in sections (big blocks) like header, page-content, footer. (But you can use  and  tags but they are like sections too)

Imagine a newspaper.

<body>
  <section class="header">
    <div class="title">
      <h1>Title</h1>
      <p>Subtitle</p>
    </div>
    <nav class="navbar">
      ... Your menu
      <ul>
        <li> ....
          ...
      </ul>
    </nav>
  </section>

  <section class="content">
    <div class="news">
      <div id="new1">
        .....
      </div>
      ...
    </div>
    <div class="rrss">
      ....
    </div>
  </section>
  <section class="footer">
    ...
    <p> Copyright </p>
  </section>
<body>

Then you can give diferent styles to the diferent parts of page.

<style>
  body{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
  }
  .header{
    width: 90%;
  }
  ...
  ...
</style>


问:
What are the differences between these IBM.Data.DB2 dlls?
I have these dlls installed on my box. What are the differnces between them and when would I use each?

```<code>IBM.Data.DB2.dll
IBM.Data.DB2.Entity.dll
IBM.Data.DB2.ASP.dll
IBM.Data.DB2.9.5.5.dll
</code>```

One other thing, my db2 data is on Z/OS Mainframe, if that makes a difference.

答:
By "my box" I assume you mean something like a Windows desktop client that you use to connect to your DB2 data source. The article Which DB2 9.5 client connectivity option is right for you? explains (kind of) why you have all those different DLLs installed on your box.

The IBM.Data.DB2.dll file is the main resource reference you would add in Visual Studio to use its various methods. You can add all of those DLLs as references in a dummy Visual Studio project then browse them in the Object Browser, and you will see their different methods or lack of.

ContentLicense: CC BY-SA 2.5

Body:
I have these dlls installed on my box. What are the differnces between them and when would I use each?

IBM.Data.DB2.dll
IBM.Data.DB2.Entity.dll
IBM.Data.DB2.ASP.dll
IBM.Data.DB2.9.5.5.dll

One other thing, my db2 data is on Z/OS Mainframe, if that makes a difference.


问:
How to create a slideshow with text and images
I want code to slideshow texts and images in same time and same div. I try some code but the time is same but images fast than text

var myImage = document.getElementById("myphoto");
var imageArray = ["14184285_574618009394184_1196314983678721559_n.jpg", "uofk.jpg", "board.jpg"];
var imageIndex = 0;
function changeImage() {
  myphoto.setAttribute("src", imageArray[imageIndex])
  imageIndex++;
  if (imageIndex >= imageArray.length) {
    imageIndex = 0;
  }
}
var handel = setInterval(changeImage, 5000);
```

<pre class="lang-js prettyprint-override"><code>var cnt = 0,
  texts = [];

//save the texts in an array for re-use
$(".textContent").each(function () {
  texts[cnt++] = $(this).text();
});

function slide() {
  if (cnt >= texts.length)
    cnt = 0;

  $('#textMessage').html(texts[cnt++]);
  $('#textMessage').fadeIn('slow').animate({ opacity: 1.0 }, 5000).fadeOut('slow', function() {
    return slide()
  });
}

slide()
</code>```

答:
https://jsfiddle.net/q9d2t4kt/1/</p>

```<code><script>
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide(){
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide+1)%slides.length;
slides[currentSlide].className = 'slide showing';
}
</script>
<style>
/*
essential styles:
these make the slideshow work
*/
#slides{
position: relative;
height: 150px;
padding: 0px;
margin: 0px;
list-style-type: none;
}

 .slide{
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
 height: 100%;
opacity: 0;
z-index: 1;

-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
 }

  .showing{
   opacity: 1;
   z-index: 2;
  }

    /*
     non-essential styles:
  just for appearance; change whatever you want
   */

.slide{
font-size: 40px;
padding: 40px;
box-sizing: border-box;
background: #333;
color: #fff;
}

   .slide:nth-of-type(1){

          //you can use image tag
   background: red;
     }
      .slide:nth-of-type(2){
background: orange;
     }
 .slide:nth-of-type(3){
     background: green;
 }
      .slide:nth-of-type(4){
     background: blue;
       }
       .slide:nth-of-type(5){
 background: purple;
       }
           </style>
   <ul id="slides">
<li class="slide showing">Slide 1</li>
<li class="slide">Slide 2</li>
<li class="slide">Slide 3</li>
<li class="slide">Slide 4</li>
<li class="slide">Slide 5</li>
 </ul>
</code>```

Body:
I want code to slideshow texts and images in same time and same div. I try some code but the time is same but images fast than text

var myImage = document.getElementById("myphoto");
var imageArray = ["14184285_574618009394184_1196314983678721559_n.jpg", "uofk.jpg", "board.jpg"];
var imageIndex = 0;
function changeImage() {
  myphoto.setAttribute("src", imageArray[imageIndex])
  imageIndex++;
  if (imageIndex >= imageArray.length) {
    imageIndex = 0;
  }
}
var handel = setInterval(changeImage, 5000);

var cnt = 0,
  texts = [];

//save the texts in an array for re-use
$(".textContent").each(function () {
  texts[cnt++] = $(this).text();
});

function slide() {
  if (cnt >= texts.length)
    cnt = 0;

  $('#textMessage').html(texts[cnt++]);
  $('#textMessage').fadeIn('slow').animate({ opacity: 1.0 }, 5000).fadeOut('slow', function() {
    return slide()
  });
}

slide()

Body:
https://jsfiddle.net/q9d2t4kt/1/

<script>
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide(){
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide+1)%slides.length;
slides[currentSlide].className = 'slide showing';
}
</script>
<style>
/*
essential styles:
these make the slideshow work
*/
#slides{
position: relative;
height: 150px;
padding: 0px;
margin: 0px;
list-style-type: none;
}

 .slide{
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
 height: 100%;
opacity: 0;
z-index: 1;

-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
 }

  .showing{
   opacity: 1;
   z-index: 2;
  }

    /*
     non-essential styles:
  just for appearance; change whatever you want
   */

.slide{
font-size: 40px;
padding: 40px;
box-sizing: border-box;
background: #333;
color: #fff;
}

   .slide:nth-of-type(1){

          //you can use image tag
   background: red;
     }
      .slide:nth-of-type(2){
background: orange;
     }
 .slide:nth-of-type(3){
     background: green;
 }
      .slide:nth-of-type(4){
     background: blue;
       }
       .slide:nth-of-type(5){
 background: purple;
       }
           </style>
   <ul id="slides">
<li class="slide showing">Slide 1</li>
<li class="slide">Slide 2</li>
<li class="slide">Slide 3</li>
<li class="slide">Slide 4</li>
<li class="slide">Slide 5</li>
 </ul>


问:
S3 subclass constructor with list updating
Imagine that you have an S3 constructor like

```<code>new_my_class <- function(x, y, ..., subclass = NULL) {
  structure(list(x = x, y = y, ...), class = c(subclass, "my_class"))
}
</code>```

I want to create a subclass of my_class so that the list I use in structure is updated with other named elements. For this reason I tried something like

```<code>new_sub_class <- function(x, y, z) {
  new_my_class(x, y, z, subclass = "sub_class")
}
</code>```

The problem is that in this way I get a list with z that doesn't have a name. For instance with

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

I get

$x
  [1] 1

$y
  [1] 2

[[3]]
  [1] 3

attr(,"class")
  [1] "sub_class" "my_class"

while I would like to have

$x
  [1] 1

$y
  [1] 2

$z
  [1] 3

attr(,"class")
  [1] "sub_class" "my_class"

答:
Just add a name for the third argument, like:</p>

```<code>new_sub_class <- function(x, y, z) {
  new_my_class(x, y, z=z, subclass = "sub_class")
}

new_sub_class(1, 2, 3)
#$x
#[1] 1
#
#$y
#[1] 2
#
#$z
#[1] 3
#
#attr(,"class")
#[1] "sub_class" "my_class"
</code>```

Body:
Imagine that you have an S3 constructor like

new_my_class <- function(x, y, ..., subclass = NULL) {
  structure(list(x = x, y = y, ...), class = c(subclass, "my_class"))
}

I want to create a subclass of my_class so that the list I use in structure is updated with other named elements. For this reason I tried something like

new_sub_class <- function(x, y, z) {
  new_my_class(x, y, z, subclass = "sub_class")
}

The problem is that in this way I get a list with z that doesn't have a name. For instance with

new_sub_class(1, 2, 3)

I get

$x
  [1] 1

$y
  [1] 2

[[3]]
  [1] 3

attr(,"class")
  [1] "sub_class" "my_class"

while I would like to have

$x
  [1] 1

$y
  [1] 2

$z
  [1] 3

attr(,"class")
  [1] "sub_class" "my_class"

Body:
Just add a name for the third argument, like:

new_sub_class <- function(x, y, z) {
  new_my_class(x, y, z=z, subclass = "sub_class")
}

new_sub_class(1, 2, 3)
#$x
#[1] 1
#
#$y
#[1] 2
#
#$z
#[1] 3
#
#attr(,"class")
#[1] "sub_class" "my_class"


问:
Android SQLite how to delete with limit
I want to delete only one row  from my database table User.

I tried this, but I have no idea how to use SQLITE_ENABLE_UPDATE_DELETE_LIMIT.

Here is my code:

```<code>    SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("User", MODE_PRIVATE, null);

        //sqLiteDatabase.execSQL("INSERT INTO user (name, age) VALUES ('jihyo', 10)");

        sqLiteDatabase.execSQL("DELETE FROM user WHERE name ='jihyo' LIMIT 1");
        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM user WHERE name = 'jihyo'", null);
        int nameIndex = c.getColumnIndex("name");
        int ageIndex = c.getColumnIndex("age");

        c.moveToFirst();
        do {
            Log.v("name", c.getString(nameIndex));
            Log.v("age", c.getString(ageIndex));
        } while (c.moveToNext());
</code>```

Here is the error:

android.database.sqlite.SQLiteException: near "LIMIT": syntax error
  (code 1): , while compiling: DELETE FROM user WHERE name ='jihyo'
  LIMIT 1

答:
You can't apply limit in delete query because DELETE Clause don't have LIMIT
so you can Select single record using SELECT query and apply DELETE on the bases
of selected query
eg.

```<code>DELETE FROM user WHERE id IN
 (SELECT id FROM user
 WHERE name = 'jihyo'
 LIMIT 1);
</code>```

Note: you can use  '=' in place of  'IN'

Title: Android SQLite how to delete with limit

Body:
I want to delete only one row  from my database table User.

I tried this, but I have no idea how to use SQLITE_ENABLE_UPDATE_DELETE_LIMIT.

Here is my code:

    SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("User", MODE_PRIVATE, null);

        //sqLiteDatabase.execSQL("INSERT INTO user (name, age) VALUES ('jihyo', 10)");

        sqLiteDatabase.execSQL("DELETE FROM user WHERE name ='jihyo' LIMIT 1");
        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM user WHERE name = 'jihyo'", null);
        int nameIndex = c.getColumnIndex("name");
        int ageIndex = c.getColumnIndex("age");

        c.moveToFirst();
        do {
            Log.v("name", c.getString(nameIndex));
            Log.v("age", c.getString(ageIndex));
        } while (c.moveToNext());

Here is the error:

android.database.sqlite.SQLiteException: near "LIMIT": syntax error
  (code 1): , while compiling: DELETE FROM user WHERE name ='jihyo'
  LIMIT 1

Body:
You can't apply limit in delete query because DELETE Clause don't have LIMIT
so you can Select single record using SELECT query and apply DELETE on the bases
of selected query
eg.

DELETE FROM user WHERE id IN
 (SELECT id FROM user
 WHERE name = 'jihyo'
 LIMIT 1);

Note: you can use  '=' in place of  'IN'


问:
How do I force evaluation of a cfif stored in a string?
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

```<code>"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"
</code>```

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

```<code><cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
</code>```

I also tried

```<code><cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
</code>```

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

答:
The only way to dynamically evaluate code that you are creating at runtime is via writing it out to a file, and then executing it.

The easiest way would be to write it a .cfm page in the Virtual File System (probably name the file after a UUID, so it's unique), and then  it where you need to run the contents.

I wouldn't normally advocate generating code at runtime like this, but it can be the most elegant solution in some cases.

As an alternative, instead of storing the CFML code in the database, you have a set of CFML email template files that get stored in a directory on your server, and in your database you simply record which template needs to be included either via cfinclude or cfmodule.

Body:
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

<cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>

I also tried

<cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?


问:
wp-admin shows blank page, how to fix it?
I am working with WordPress 3.5.8. Yesterday I made some changes into it to a friend. I don't know what happened, but after some time when I try to log in at wp-admin side and execute URL www.mysite.com/wp-admin it shows me a blank page. How do I solve this? I have searched over the internet and blogs. I found it could be related to hosting problems or brute force-attack, but I don't think that that's what happened to my site.

Links I visited:

http://wordpress.org/support/topic/wp-admin-wont-load-shows-blank-page

http://wordpress.org/support/topic/brute-force-attacks-and-wordpress?replies=1

http://wordpress.org/support/topic/wp-admin-wont-load-shows-blank-page

http://wordpress.org/support/topic/wp-admin-blank-page

http://wordpress.org/support/topic/blank-page-on-wp-admin

答:
In my case, I was able to see the backend, but in my front I was getting a blank page...

Nothing about debugging and disabling themes/plugins was useful...

After some research, I've realized that my index.php (located at the root directory, not the theme's one) was empty!

The only content was a message saying Silence is golden.

Using a backup I had, I could get back my original index.php and get the site working again.


问:
Webdriver getText not returning any meaningful value
I have the following html in a page

```<code><div class="mst_updt" style=""> 27/06/2017 12:02:31 </div>
</code>```

I am trying to extract the dynamic date value between the divs :

```<code> WebElement webElement =driver.findElement(By.cssSelector(".mst_updt"));

 String text = webElement.getText();
 System.out.println("i am text : " + text);

 System.out.println("Most read 1 : " +   webElement.getText());

 String a = driver.findElement(By.cssSelector(".mst_updt")).getText();
 System.out.println("Most read 2 : " + a);
 System.out.println(webElement);

 Boolean isTheTextPresent =  driver.getPageSource().contains("mst_updt");
 System.out.println("And did we find the string ? : " + isTheTextPresent);
</code>```

you will see i am trying various methods , here are the results i am getting, why cant i extract the date and time ??

i am text :

Most read 1 :

Most read 2 :

[[FirefoxDriver: firefox on ANY (e4a9c548-6146-4685-9944-6b5d51308bff)] -> css selector: .mst_updt]

And did we find the string ? : true

Full Code which should help..

```<code><div class="content">
    <div role="main" class="content-inner content-full-width">
        <div class="main-content">
          <section class="component-list">
             <div class="section group">
                <div class="col-lrg span-lrg_1_of_3">
    <div class="component-weekly-wrap">
        <header class="header-weekly-wrap">
            <h4 itemprop="name">
                <a class="section-title-link" href="example.com/static/survey-panel">Computer Survey Panel</a>
            </h4>
        </header>
        <article>
            <a href="example.com/static/survey-panel"><img alt="" src="/w-images/fa8edbd1-2c78-4415-9abf-334f7087ff8b/2/CTGRS17OA344213-370x229.jpg" /></a>
            <div class="col-inner weekly-wrap-details">
                    <p><p>Join our <a href="example.com/static/survey-panel" target="_blank"><strong>Research Survey Panel</strong></a> and earn an Amazon voucher for each survey you complete!</p>
<p><strong><a href="example.com/static/survey-panel">Find out more</a></strong></p></p>
            <!--<a class="btn download" href="#">More information</a> -->

            </div>
            </article>
    </div>
</div>
                <!--most read homepage updated START-->
<div class= "mst_updt" style="display:none;">
28/06/2017 12:38:15
</div>
<!--most read homepage updated END-->
<div class="col-lrg component-list-most-read span-lrg_2_of_3">
    <div class="col-inner component-most-read">
        <header class="header-most-read">
            <h4 itemprop="name">Most read</h4>
        </header>
        <div class="ol">
            <ol>
                <li>

                </li>
                <li>

                </li>
                <li>

                </li>
                <li>

                </li>
                <li>

                </li>
            </ol>
        </div>
    </div>
</div>

             </div>
         </section>
      </div>
   </div>
</div>
</code>```

答:
the solution was supplied by : Rafał Laskowski

i could get the value by xpath of cssSelector, it needed returning by using : getAttribute("innerHTML");

```<code>s String a = driver.findElement(By.cssSelector(".mst_updt")).getAttribute("innerHTML");

String b = driver.findElement(By.xpath("//html/body/div[3]/div[2]/div[7]/div/div/section/div/div[2]")).getAttribute("innerHTML");

System.out.println("Most read 2 : " + a);
System.out.println("Most read 3 : " + b);
</code>```

Body:
I have the following html in a page

 27/06/2017 12:02:31

I am trying to extract the dynamic date value between the divs :

 WebElement webElement =driver.findElement(By.cssSelector(".mst_updt"));

 String text = webElement.getText();
 System.out.println("i am text : " + text);

 System.out.println("Most read 1 : " +   webElement.getText());

 String a = driver.findElement(By.cssSelector(".mst_updt")).getText();
 System.out.println("Most read 2 : " + a);
 System.out.println(webElement);

 Boolean isTheTextPresent =  driver.getPageSource().contains("mst_updt");
 System.out.println("And did we find the string ? : " + isTheTextPresent);

you will see i am trying various methods , here are the results i am getting, why cant i extract the date and time ??

i am text :

Most read 1 :

Most read 2 :

[[FirefoxDriver: firefox on ANY (e4a9c548-6146-4685-9944-6b5d51308bff)] -> css selector: .mst_updt]

And did we find the string ? : true

Full Code which should help..

                Computer Survey Panel

Join our Research Survey Panel and earn an Amazon voucher for each survey you complete!

Find out more

28/06/2017 12:38:15

Most read

Body:
the solution was supplied by : Rafał Laskowski

i could get the value by xpath of cssSelector, it needed returning by using : getAttribute("innerHTML");

s String a = driver.findElement(By.cssSelector(".mst_updt")).getAttribute("innerHTML");

String b = driver.findElement(By.xpath("//html/body/div[3]/div[2]/div[7]/div/div/section/div/div[2]")).getAttribute("innerHTML");

System.out.println("Most read 2 : " + a);
System.out.println("Most read 3 : " + b);


问:
Expect Script interaction
I have an expect script that I would like to use to check disk health on SuSE servers.  The expect script will/would take the output of df -T|grep ext*|awk '{print $1}' to generate a list for ext2 or 3 type disk drives.  I can then take that list and iterate thought it, executing e2fsck -n $partition and dumpe2fs -h $partition.

I have a start on the script, I have omitted the access part as that is straight forward.

The issue I have is this only works if the partition file(parts.txt),  exists on the server that I spawn the expect script on.  I had hoped that all the work could be done on the server that I login to.

```<code>send_user "\nthese are the ext partitions on this element\n"
exp_send "df -T|grep ext*\|awk \'\{ print \$1 \}\' > parts.txt\r
expect "#"
set f [open "parts.txt" r]
while { [ gets $f part ] != -1} {
    exp_send "dumpe2fs -h $part\r"
    expect "#"
    exp_send "e2fsck -n $part\r"
    expect "#"
}
close $f
exp_send "exit\r"
expect {
    -re "~ #" {
        exp_send "exit\r"
    }
    -re ":~>" {
        exp_send "exit\r"
    }
}
expect eof
</code>```

答:
You either need to transfer the parts list to the local side (i.e., the system that actually runs expect) or you need to move the iteration to the remote side.
If I had to choose between the two approaches, I'd probably use the first option; that would give me far more options for complex handling of unexpected conditions.

Getting the list locally

To move the part list locally, we adapt your script so that it runs the df … command and writes the output to where we can see it, and use a more complex expect command to process the output.

```<code>exp_send "df -T|grep ext*|awk '{ print \$1 }'\r"
set theParts {}
expect {
    -re {[^\s#]+} {
        lappend theParts $expect_out(0,string)
        exp_continue
    }
    "#" {
        # Just an empty script here
    }
}
</code>```

This expect will look for two things at once, but with the first one if it finds a sequence of non-space non-hash characters, it appends that sequence (stored by default in that particular “field” of the expect_out array) to the list in the variable theParts and keeps waiting. (That's what the exp_continue does.)

Now that you have a list, you could write it out to a local parts.txt, but why would you bother? Might as well use foreach to walk over it directly:

```<code>foreach part $theParts {
    exp_send "dumpe2fs -h $part\r"
    expect "#"
    exp_send "e2fsck -n $part\r"
    expect "#"
}
</code>```

Moving the looping remotely

The other approach is to put the looping on the other machine.

```<code>exp_send "df -T|grep ext*|awk '{ print \$1 }' >parts.txt\r"
expect "#"
exp_send "for part in `cat parts.txt`; do dumpe2fs -h \$part || break; e2fsck -n \$part || break; done\r"
expect "#"
</code>```

This is quite a bit shorter, but in the form above not very robust. You can make robust shell scripts, but it takes quite a bit of work (and is much easier in my experience if you write the shell script itself to a file on the remote host and then run it from there).

For your understanding, the looping script I've done above is this (when split over multiple lines and without the backslashes for Tcl, which are only really needed before Tcl metacharacters — in this script, that's $ only):

for part in `cat parts.txt`; do
    dumpe2fs -h $part || break
    e2fsck -n $part || break
done
```

Title: Expect Script interaction

Body:
I have an expect script that I would like to use to check disk health on SuSE servers.  The expect script will/would take the output of df -T|grep ext*|awk '{print $1}' to generate a list for ext2 or 3 type disk drives.  I can then take that list and iterate thought it, executing e2fsck -n $partition and dumpe2fs -h $partition.

I have a start on the script, I have omitted the access part as that is straight forward.

The issue I have is this only works if the partition file(parts.txt),  exists on the server that I spawn the expect script on.  I had hoped that all the work could be done on the server that I login to.

send_user "\nthese are the ext partitions on this element\n"
exp_send "df -T|grep ext*\|awk \'\{ print \$1 \}\' > parts.txt\r
expect "#"
set f [open "parts.txt" r]
while { [ gets $f part ] != -1} {
    exp_send "dumpe2fs -h $part\r"
    expect "#"
    exp_send "e2fsck -n $part\r"
    expect "#"
}
close $f
exp_send "exit\r"
expect {
    -re "~ #" {
        exp_send "exit\r"
    }
    -re ":~>" {
        exp_send "exit\r"
    }
}
expect eof

Body:
You either need to transfer the parts list to the local side (i.e., the system that actually runs expect) or you need to move the iteration to the remote side.
If I had to choose between the two approaches, I'd probably use the first option; that would give me far more options for complex handling of unexpected conditions.

Getting the list locally

To move the part list locally, we adapt your script so that it runs the df … command and writes the output to where we can see it, and use a more complex expect command to process the output.

exp_send "df -T|grep ext*|awk '{ print \$1 }'\r"
set theParts {}
expect {
    -re {[^\s#]+} {
        lappend theParts $expect_out(0,string)
        exp_continue
    }
    "#" {
        # Just an empty script here
    }
}

This expect will look for two things at once, but with the first one if it finds a sequence of non-space non-hash characters, it appends that sequence (stored by default in that particular “field” of the expect_out array) to the list in the variable theParts and keeps waiting. (That's what the exp_continue does.)

Now that you have a list, you could write it out to a local parts.txt, but why would you bother? Might as well use foreach to walk over it directly:

foreach part $theParts {
    exp_send "dumpe2fs -h $part\r"
    expect "#"
    exp_send "e2fsck -n $part\r"
    expect "#"
}

Moving the looping remotely

The other approach is to put the looping on the other machine.

exp_send "df -T|grep ext*|awk '{ print \$1 }' >parts.txt\r"
expect "#"
exp_send "for part in `cat parts.txt`; do dumpe2fs -h \$part || break; e2fsck -n \$part || break; done\r"
expect "#"

This is quite a bit shorter, but in the form above not very robust. You can make robust shell scripts, but it takes quite a bit of work (and is much easier in my experience if you write the shell script itself to a file on the remote host and then run it from there).

For your understanding, the looping script I've done above is this (when split over multiple lines and without the backslashes for Tcl, which are only really needed before Tcl metacharacters — in this script, that's $ only):

for part in `cat parts.txt`; do
    dumpe2fs -h $part || break
    e2fsck -n $part || break
done


问:
Windows IoT BackgroundTask Async/Await
I am having a play with a Raspberry Pi 3 running Windows IoT. I have wired up a DS18B20 sensor and I am able to communicate to it fine via a UWP app.

I now wanted to make this app into a BackgroundTask app.
I am using this code for the OneWire coms

```<code>class WireSearchResult
{
    public byte[] id = new byte[8];
    public int lastForkPoint = 0;
}
public class OneWire
{
    private SerialDevice serialPort = null;
    DataWriter dataWriteObject = null;
    DataReader dataReaderObject = null;

    public async Task<string> GetFirstSerialPort()
    {
        try
        {
            string aqs = SerialDevice.GetDeviceSelector("UART0");
            var dis = await DeviceInformation.FindAllAsync(aqs);
            if (dis.Count > 0)
            {
                var deviceInfo = dis.First();
                return deviceInfo.Id;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to get serial device: " + ex.Message);
        }

        return null;
    }

    public void shutdown()
    {
        if (serialPort != null)
        {
            serialPort.Dispose();
            serialPort = null;
        }
    }

    async Task<bool> onewireReset(string deviceId)
    {
        try
        {
            if (serialPort != null)
                serialPort.Dispose();

            serialPort = await SerialDevice.FromIdAsync(deviceId);

            // Configure serial settings
            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.BaudRate = 9600;
            serialPort.Parity = SerialParity.None;
            serialPort.StopBits = SerialStopBitCount.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = SerialHandshake.None;

            dataWriteObject = new DataWriter(serialPort.OutputStream);
            dataWriteObject.WriteByte(0xF0);
            await dataWriteObject.StoreAsync();

            dataReaderObject = new DataReader(serialPort.InputStream);
            await dataReaderObject.LoadAsync(1);
            byte resp = dataReaderObject.ReadByte();
            if (resp == 0xFF)
            {
                System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                return false;
            }
            else if (resp == 0xF0)
            {
                System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                return false;
            }
            else
            {
                //System.Diagnostics.Debug.WriteLine("Response: " + resp);
                serialPort.Dispose();
                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 115200;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;
                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataReaderObject = new DataReader(serialPort.InputStream);
                return true;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
            return false;
        }
    }

    public async Task onewireWriteByte(byte b)
    {
        for (byte i = 0; i < 8; i++, b = (byte)(b >> 1))
        {
            // Run through the bits in the byte, extracting the
            // LSB (bit 0) and sending it to the bus
            await onewireBit((byte)(b & 0x01));
        }
    }

    async Task<byte> onewireBit(byte b)
    {
        var bit = b > 0 ? 0xFF : 0x00;
        dataWriteObject.WriteByte((byte)bit);
        await dataWriteObject.StoreAsync();
        await dataReaderObject.LoadAsync(1);
        var data = dataReaderObject.ReadByte();
        return (byte)(data & 0xFF);
    }

    async Task<byte> onewireReadByte()
    {
        byte b = 0;
        for (byte i = 0; i < 8; i++)
        {
            // Build up byte bit by bit, LSB first
            b = (byte)((b >> 1) + 0x80 * await onewireBit(1));
        }
       // System.Diagnostics.Debug.WriteLine("onewireReadByte result: " + b);
        return b;
    }

    public async Task<double> getTemperature(string deviceId)
    {
        double tempCelsius = -200;

        if (await onewireReset(deviceId))
        {
            await onewireWriteByte(0xCC); //1-Wire SKIP ROM command (ignore device id)
            await onewireWriteByte(0x44); //DS18B20 convert T command
                                          // (initiate single temperature conversion)
                                          // thermal data is stored in 2-byte temperature
                                          // register in scratchpad memory

            // Wait for at least 750ms for data to be collated
            await Task.Delay(750);

            // Get the data
            await onewireReset(deviceId);
            await onewireWriteByte(0xCC); //1-Wire Skip ROM command (ignore device id)
            await onewireWriteByte(0xBE); //DS18B20 read scratchpad command
                                          // DS18B20 will transmit 9 bytes to master (us)
                                          // starting with the LSB

            byte tempLSB = await onewireReadByte(); //read lsb
            byte tempMSB = await onewireReadByte(); //read msb

            // Reset bus to stop sensor sending unwanted data
            await onewireReset(deviceId);

            // Log the Celsius temperature
            tempCelsius = ((tempMSB * 256) + tempLSB) / 16.0;
            var temp2 = ((tempMSB << 8) + tempLSB) * 0.0625; //just another way of calculating it

            System.Diagnostics.Debug.WriteLine("Temperature: " + tempCelsius + " degrees C " + temp2);
        }
        return tempCelsius;
    }
}
</code>```

And finally the StartupTask

```<code>public sealed class StartupTask : IBackgroundTask
{
    private BackgroundTaskDeferral deferral;

    private OneWire onewire;
    private string deviceId = string.Empty;
    private bool inprog = false;
    private Timer timer;

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        deferral = taskInstance.GetDeferral();

        onewire = new OneWire();
        deviceId = await onewire.GetFirstSerialPort();

        if(deviceId != null)
          await onewire.getTemperature(deviceId));

        BackgroundTaskDeferral.Complete();
    }

}
</code>```

The problem I have is that when I run this code it hangs on one of the lines that disposes of the SerialDevice in OneWire class.

I have read in a few places that its related to the BackgroundTask and using Async/Await

答:
I'm using the same onewire code in a background task to talk to the DS18B20 sensor and was experiencing exactly the same behaviour as you.

What I found is that if I put a delay of 100 milliseconds before calling the serial port dispose method it works

```<code>await Task.Delay(100)
</code>```

I've tried less than 100 milliseconds but it just kept hanging.

This stackoverflow questions first answer explains the issue with serial ports in the .Net Framework Why Thread.Sleep() before SerialPort.Open and Close?

Title: Windows IoT BackgroundTask Async/Await

Body:
I am having a play with a Raspberry Pi 3 running Windows IoT. I have wired up a DS18B20 sensor and I am able to communicate to it fine via a UWP app.

I now wanted to make this app into a BackgroundTask app.
I am using this code for the OneWire coms

class WireSearchResult
{
    public byte[] id = new byte[8];
    public int lastForkPoint = 0;
}
public class OneWire
{
    private SerialDevice serialPort = null;
    DataWriter dataWriteObject = null;
    DataReader dataReaderObject = null;

    public async Task<string> GetFirstSerialPort()
    {
        try
        {
            string aqs = SerialDevice.GetDeviceSelector("UART0");
            var dis = await DeviceInformation.FindAllAsync(aqs);
            if (dis.Count > 0)
            {
                var deviceInfo = dis.First();
                return deviceInfo.Id;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to get serial device: " + ex.Message);
        }

        return null;
    }

    public void shutdown()
    {
        if (serialPort != null)
        {
            serialPort.Dispose();
            serialPort = null;
        }
    }

    async Task<bool> onewireReset(string deviceId)
    {
        try
        {
            if (serialPort != null)
                serialPort.Dispose();

            serialPort = await SerialDevice.FromIdAsync(deviceId);

            // Configure serial settings
            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.BaudRate = 9600;
            serialPort.Parity = SerialParity.None;
            serialPort.StopBits = SerialStopBitCount.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = SerialHandshake.None;

            dataWriteObject = new DataWriter(serialPort.OutputStream);
            dataWriteObject.WriteByte(0xF0);
            await dataWriteObject.StoreAsync();

            dataReaderObject = new DataReader(serialPort.InputStream);
            await dataReaderObject.LoadAsync(1);
            byte resp = dataReaderObject.ReadByte();
            if (resp == 0xFF)
            {
                System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                return false;
            }
            else if (resp == 0xF0)
            {
                System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                return false;
            }
            else
            {
                //System.Diagnostics.Debug.WriteLine("Response: " + resp);
                serialPort.Dispose();
                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 115200;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;
                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataReaderObject = new DataReader(serialPort.InputStream);
                return true;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
            return false;
        }
    }

    public async Task onewireWriteByte(byte b)
    {
        for (byte i = 0; i < 8; i++, b = (byte)(b >> 1))
        {
            // Run through the bits in the byte, extracting the
            // LSB (bit 0) and sending it to the bus
            await onewireBit((byte)(b & 0x01));
        }
    }

    async Task<byte> onewireBit(byte b)
    {
        var bit = b > 0 ? 0xFF : 0x00;
        dataWriteObject.WriteByte((byte)bit);
        await dataWriteObject.StoreAsync();
        await dataReaderObject.LoadAsync(1);
        var data = dataReaderObject.ReadByte();
        return (byte)(data & 0xFF);
    }

    async Task<byte> onewireReadByte()
    {
        byte b = 0;
        for (byte i = 0; i < 8; i++)
        {
            // Build up byte bit by bit, LSB first
            b = (byte)((b >> 1) + 0x80 * await onewireBit(1));
        }
       // System.Diagnostics.Debug.WriteLine("onewireReadByte result: " + b);
        return b;
    }

    public async Task<double> getTemperature(string deviceId)
    {
        double tempCelsius = -200;

        if (await onewireReset(deviceId))
        {
            await onewireWriteByte(0xCC); //1-Wire SKIP ROM command (ignore device id)
            await onewireWriteByte(0x44); //DS18B20 convert T command
                                          // (initiate single temperature conversion)
                                          // thermal data is stored in 2-byte temperature
                                          // register in scratchpad memory

            // Wait for at least 750ms for data to be collated
            await Task.Delay(750);

            // Get the data
            await onewireReset(deviceId);
            await onewireWriteByte(0xCC); //1-Wire Skip ROM command (ignore device id)
            await onewireWriteByte(0xBE); //DS18B20 read scratchpad command
                                          // DS18B20 will transmit 9 bytes to master (us)
                                          // starting with the LSB

            byte tempLSB = await onewireReadByte(); //read lsb
            byte tempMSB = await onewireReadByte(); //read msb

            // Reset bus to stop sensor sending unwanted data
            await onewireReset(deviceId);

            // Log the Celsius temperature
            tempCelsius = ((tempMSB * 256) + tempLSB) / 16.0;
            var temp2 = ((tempMSB << 8) + tempLSB) * 0.0625; //just another way of calculating it

            System.Diagnostics.Debug.WriteLine("Temperature: " + tempCelsius + " degrees C " + temp2);
        }
        return tempCelsius;
    }
}

And finally the StartupTask

public sealed class StartupTask : IBackgroundTask
{
    private BackgroundTaskDeferral deferral;

    private OneWire onewire;
    private string deviceId = string.Empty;
    private bool inprog = false;
    private Timer timer;

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        deferral = taskInstance.GetDeferral();

        onewire = new OneWire();
        deviceId = await onewire.GetFirstSerialPort();

        if(deviceId != null)
          await onewire.getTemperature(deviceId));

        BackgroundTaskDeferral.Complete();
    }

}

The problem I have is that when I run this code it hangs on one of the lines that disposes of the SerialDevice in OneWire class.

I have read in a few places that its related to the BackgroundTask and using Async/Await

Body:
I'm using the same onewire code in a background task to talk to the DS18B20 sensor and was experiencing exactly the same behaviour as you.

What I found is that if I put a delay of 100 milliseconds before calling the serial port dispose method it works

await Task.Delay(100)

I've tried less than 100 milliseconds but it just kept hanging.

This stackoverflow questions first answer explains the issue with serial ports in the .Net Framework Why Thread.Sleep() before SerialPort.Open and Close?


问:
Typing effect: Word per Word
I've been figuring out how to have a typing effect that is word per word instead of letter per letter. So far, all links I've searched are offering letter per letter typewriter effect.

https://macarthur.me/typeit/
https://github.com/mattboldt/typed.js/

Is this possible to achieve? Or have you done something similar?

答:
This is pretty easy.
Just register an interval, split your text, reverse the array and pop the last item. The one you append to the text-container then. Done.

JS

```<code>var myText = "Some text you want to be typed automagically..";
var myWords = myText.split(" ").reverse();

var ntrvl = setInterval(function() {
  addNextWord();
}, 150);

function addNextWord() {
  var nextWord = myWords.pop();
  if(nextWord !== undefined) {
      var textNow = $(".write-here").text() + " " + nextWord;
      $(".write-here").text(textNow);
  }
}
</code>```

What do you think of this?

JSfiddle

Title: Typing effect: Word per Word

Body:
This is pretty easy.
Just register an interval, split your text, reverse the array and pop the last item. The one you append to the text-container then. Done.

JS

var myText = "Some text you want to be typed automagically..";
var myWords = myText.split(" ").reverse();

var ntrvl = setInterval(function() {
  addNextWord();
}, 150);

function addNextWord() {
  var nextWord = myWords.pop();
  if(nextWord !== undefined) {
      var textNow = $(".write-here").text() + " " + nextWord;
      $(".write-here").text(textNow);
  }
}

What do you think of this?

JSfiddle


问:
Customizing OpenFileDialog in .Net
In need to create native looking customized .Net OpenFileDialog in Windows XP and Windows Vista/7. Add new controls to it, etc. Is there any way to customize standard OpenFileDialog in .Net (WPF specifically)? I've looked through the solutions like OpenFileDialogEx, but all that WINAPI hooking stuff is not acceptable for me. Maybe one knows a way to extract native dialogs via Reflection or something? How the native OpenFileDialog in Windows Vista/7 is implemented? Is it written in WPF? Thanks in advance.

Regards, Pavel.

答:
You might take a look at this CodeProject link.

It's an interesting way to create just about any file dialog you might want.  And the author includes a link to a WPF version as well as the original article written with XP in mind.

Title: Customizing OpenFileDialog in .Net


问:
Closing socket in client crashes nodejs server
On C client I do:

```<code>socket()
connect() on port 6969
send()
//I have seen that I didn't call recv so nodejs try me to send data but My program was gone
and finally closesocket()
</code>```

On nodejs server I receive the message so the connection is established:

```<code>const port = 6969;
var net = require('net');
var server = net.createServer(function(connection) {
    console.log('client connected');
    connection.on('close', function() {
        console.log('conn closed');
    });
    connection.on('end', function() {
        console.log('conn ended');// that is not called
    });
    connection.on("error", function(err) {
        console.log("Caught flash policy server socket error: ");
        console.log(err.stack);
    });
    connection.on('data', function(data) {
        data = data.toString();
        console.log('client sended the folowing string:' + data);
        connection.write("Response");
        console.log('Sended response to client');
    });
});
server.listen(port, function() {
    console.log('server is listening');
});
</code>```

This is the result of my terminal:

```<code>server is listening
client connected
client sended the folowing string:err404
Sended response to client
Caught flash policy server socket error:
Error: read ECONNRESET
    at exports._errnoException (util.js:1018:11)
    at TCP.onread (net.js:568:26)
conn closed
</code>```

So I have read Node js ECONNRESET already but I don't understand if this is normal why my nodejs server crash?

Edit: I found this snippet:

```<code>connection.on("error", function(err) {
    console.log("Caught flash policy server socket error: ");
    console.log(err.stack);
});
</code>```

This code on client side will produce the same error:

```<code>#ifdef WIN32
Sleep(5000);
int iResult = shutdown(sock, SD_BOTH);
printf("shutdown is called\n");
Sleep(5000);
#elif defined (linux)
sleep(5);
int iResult = shutdown(sock, SHUT_RDWR);
printf("shutdown is called\n");
sleep(5);
#endif // WIN32
    if (iResult == SOCKET_ERROR) {closesocket(sock);printf("SOCKET_ERROR");}
    printf("iResult=%d",iResult);
</code>```

Edit:
Now I catch either close event and end event: but the same error is still throwed.

Edit: I've Updated my code.
And I found where is the problem:NodeJs is trying to send me data but I've already called shutdown().

答:
There 2 things to consider, one in your server and one in your client code.

Server code:

You have to use the end event instead of the close event, see
https://nodejs.org/api/net.html#net_event_end:

```<code>connection.on('end', function (){
   console.log('client disconnected');
});
</code>```

end event:

Emitted when the other end of the socket sends a FIN packet, thus ending the readable side of the socket.

close event:

Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

So that means, that the close event will occur after the end event.

Client code:

You have to call shutdown before closing the socket to prevent further reads or writes which then would cause an error because the socket is already down.

The Windows version of shutdown is described here at MSDN and the Linux variant here in a manpage.

Windows:

```<code>int ret = shutdown(sockfd, SD_BOTH); /* Shutdown both send and receive operations. */
</code>```

Linux:

```<code>int ret = shutdown(sockfd, SHUT_RDWR); /* Disables further send and receive operations. */
</code>```

Importance of flushing sent data:

The shutdown function does not guarantees that data that is already in the buffer does not get send. It is needed that all data get's flushed before the call to close occur. In this answer on SO is written down a nice way to do that rather than just sleep 20 ms or so.

In order to test if that is your problem you can use Sleep(2000) in Windows and sleep(2) in Linux to sleep 2 seconds between shutdown and close.

On this page is a nice comparison between close/closesocket and shutdown:

You're ready to close the connection on your socket descriptor. This is easy. You can just use the regular Unix file descriptor close() function:

```<code>close(sockfd);
</code>```

This will prevent any more reads and writes to the socket. Anyone attempting to read or write the socket on the remote end will receive an error.

Just in case you want a little more control over how the socket closes, you can use the shutdown() function. It allows you to cut off communication in a certain direction, or both ways (just like close() does.) Synopsis:

```<code>int shutdown(int sockfd, int how);
</code>```

[...]

shutdown() returns 0 on success, and -1 on error (with errno set accordingly.)

Body:
On C client I do:

socket()
connect() on port 6969
send()
//I have seen that I didn't call recv so nodejs try me to send data but My program was gone
and finally closesocket()

On nodejs server I receive the message so the connection is established:

const port = 6969;
var net = require('net');
var server = net.createServer(function(connection) {
    console.log('client connected');
    connection.on('close', function() {
        console.log('conn closed');
    });
    connection.on('end', function() {
        console.log('conn ended');// that is not called
    });
    connection.on("error", function(err) {
        console.log("Caught flash policy server socket error: ");
        console.log(err.stack);
    });
    connection.on('data', function(data) {
        data = data.toString();
        console.log('client sended the folowing string:' + data);
        connection.write("Response");
        console.log('Sended response to client');
    });
});
server.listen(port, function() {
    console.log('server is listening');
});

This is the result of my terminal:

server is listening
client connected
client sended the folowing string:err404
Sended response to client
Caught flash policy server socket error:
Error: read ECONNRESET
    at exports._errnoException (util.js:1018:11)
    at TCP.onread (net.js:568:26)
conn closed

So I have read Node js ECONNRESET already but I don't understand if this is normal why my nodejs server crash?

Edit: I found this snippet:

connection.on("error", function(err) {
    console.log("Caught flash policy server socket error: ");
    console.log(err.stack);
});

This code on client side will produce the same error:

#ifdef WIN32
Sleep(5000);
int iResult = shutdown(sock, SD_BOTH);
printf("shutdown is called\n");
Sleep(5000);
#elif defined (linux)
sleep(5);
int iResult = shutdown(sock, SHUT_RDWR);
printf("shutdown is called\n");
sleep(5);
#endif // WIN32
    if (iResult == SOCKET_ERROR) {closesocket(sock);printf("SOCKET_ERROR");}
    printf("iResult=%d",iResult);

Edit:
Now I catch either close event and end event: but the same error is still throwed.

Edit: I've Updated my code.
And I found where is the problem:NodeJs is trying to send me data but I've already called shutdown().

Body:
There 2 things to consider, one in your server and one in your client code.

Server code:

You have to use the end event instead of the close event, see
https://nodejs.org/api/net.html#net_event_end:

connection.on('end', function (){
   console.log('client disconnected');
});

end event:

Emitted when the other end of the socket sends a FIN packet, thus ending the readable side of the socket.

close event:

Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

So that means, that the close event will occur after the end event.

Client code:

You have to call shutdown before closing the socket to prevent further reads or writes which then would cause an error because the socket is already down.

The Windows version of shutdown is described here at MSDN and the Linux variant here in a manpage.

Windows:

int ret = shutdown(sockfd, SD_BOTH); /* Shutdown both send and receive operations. */

Linux:

int ret = shutdown(sockfd, SHUT_RDWR); /* Disables further send and receive operations. */

Importance of flushing sent data:

The shutdown function does not guarantees that data that is already in the buffer does not get send. It is needed that all data get's flushed before the call to close occur. In this answer on SO is written down a nice way to do that rather than just sleep 20 ms or so.

In order to test if that is your problem you can use Sleep(2000) in Windows and sleep(2) in Linux to sleep 2 seconds between shutdown and close.

On this page is a nice comparison between close/closesocket and shutdown:

You're ready to close the connection on your socket descriptor. This is easy. You can just use the regular Unix file descriptor close() function:

close(sockfd);

This will prevent any more reads and writes to the socket. Anyone attempting to read or write the socket on the remote end will receive an error.

Just in case you want a little more control over how the socket closes, you can use the shutdown() function. It allows you to cut off communication in a certain direction, or both ways (just like close() does.) Synopsis:

int shutdown(int sockfd, int how);

[...]

shutdown() returns 0 on success, and -1 on error (with errno set accordingly.)


问:
How to get HTTP server to run?
I am trying to setup a Python server so that I can build a website to run my Python scripts. I understand that I need to set up a server with cgi, but I am not really a networking expert, nor too strong in Python programming.

Basically, I am looking to setup a website that has ability to click a button and in turn it runs a python script that I have.

I am running python -m http.server 8000 (or python -m http.server --cgi 8000) command and I am assuming that this should be my local server. I try opening http://127.0.0.1:8000/, but I get a message saying This site can't be reached.

Now I do not have any website there or anything like that so I'm not sure if this is ok or not. Does anyone have suggestions as to what I should do and how I get this up and running?  Do you think this may have something to do with my work firewall?

Let's say I have a simple website built like this:

```<code><html>
<head>
</head>
<body>
<button>Click here to run script!</button>
</body>
</html>
</code>```

and I have a script called testrun.py.

Thank you very much for your help!

I am running on Python3, Windows 7.

答:
By typing python -m http.server 8000 you started a server but, depending on your settings, it is not always running on http://127.0.0.1:8000/

For a more general approach visit http://localhost:8000

Title: How to get HTTP server to run?

Body:
I am trying to setup a Python server so that I can build a website to run my Python scripts. I understand that I need to set up a server with cgi, but I am not really a networking expert, nor too strong in Python programming.

Basically, I am looking to setup a website that has ability to click a button and in turn it runs a python script that I have.

I am running python -m http.server 8000 (or python -m http.server --cgi 8000) command and I am assuming that this should be my local server. I try opening http://127.0.0.1:8000/, but I get a message saying This site can't be reached.

Now I do not have any website there or anything like that so I'm not sure if this is ok or not. Does anyone have suggestions as to what I should do and how I get this up and running?  Do you think this may have something to do with my work firewall?

Let's say I have a simple website built like this:

<button>Click here to run script!</button>

and I have a script called testrun.py.

Thank you very much for your help!

I am running on Python3, Windows 7.

ContentLicense: CC BY-SA 4.0


问:
Send GCM Push Notification to device
I'm trying to develop an Xamarin Android App, the uses GCM services to send push Notifications.

I followed the tutorial presented on Xamarin tutorial page, that teach how to Register GCM, requesting the device Token and how to create a Message Sender.

All works fine, excepts that I want to send a push message to a particularly device with token x, and not to all of them.

The Message Sender looks like this:

```<code>    private static void messageSender(string title, string message, string summary)
    {
        var jGcmData = new JObject();
        var jData = new JObject();

        jData.Add("message", message);
        jData.Add("title", title);
        jData.Add("summary", summary);
        jGcmData.Add("to", "/topics/global");
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }
    }
</code>```

Any help?

答:
```<code>*client side*

    private void SendNotification()
        {
            var jGcmData = new JObject();
            var jData = new JObject();

            jData.Add("title", txtTitle.Text);
            jData.Add("message", txtMessage.Text);
            jData.Add("summary", txtSummary.Text);
            jGcmData.Add("to", "/topics/global");
            jGcmData.Add("data", jData);
            var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation(
                        "Authorization", "key=" + API_KEY);
                    Task.WaitAll(client.PostAsync(url,
                            new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to send GCM message:");
                Console.Error.WriteLine(ex.StackTrace);
            }
        }
*phone side*

public override void OnMessageReceived(string from, Bundle data)
        {
            var message = data.GetString("message");
            var title = data.GetString("title");
            var summary = data.GetString("summary");
            Log.Debug("MyGcmListenerService", "From:    " + from);
            Log.Debug("MyGcmListenerService", "Message: " + message);
            Log.Debug("MyGcmListenerService", "Title: " + title);
            Log.Debug("MyGcmListenerService", "Summary: " + summary);
            SendNotification(message, title, summary);
        }
        void SendNotification(string message,string title,string summary)
        {

            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
            var notificationBuilder = new Notification.Builder(this)
                .SetSmallIcon(Resource.Drawable.aalogo2)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetSubText(summary)
                .SetAutoCancel(true)
                .SetContentIntent(pendingIntent);
            var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
            notificationManager.Notify(0, notificationBuilder.Build());
        }
</code>```

Title: Send GCM Push Notification to device

Body:
I'm trying to develop an Xamarin Android App, the uses GCM services to send push Notifications.

I followed the tutorial presented on Xamarin tutorial page, that teach how to Register GCM, requesting the device Token and how to create a Message Sender.

All works fine, excepts that I want to send a push message to a particularly device with token x, and not to all of them.

The Message Sender looks like this:

    private static void messageSender(string title, string message, string summary)
    {
        var jGcmData = new JObject();
        var jData = new JObject();

        jData.Add("message", message);
        jData.Add("title", title);
        jData.Add("summary", summary);
        jGcmData.Add("to", "/topics/global");
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }
    }

Any help?


问:
Aligning images in the center with text next to them
I´m just working on my first website. It´s a onepager about Halo just to mess around a bit and learn HTML, CSS and Javascript. I want to create a section, listing all the boxes of the games with a little text next to them. I got two boxes in one picture. That´s what I got now:

    #historyBackground {
    background: url(../images/uff.jpg);
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: none;
    position: absolute;
    }

    #halo-1-2-box {
    height: 50%;
    width: 30%;
    opacity: 0;
    transition: all ease .5s;
    }

    #centerImage {
    vertical-align: middle;
    text-align:center;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <section id="historyBackground">
    <div id="centerImage">
    <img src="images/history/halo1&2_box.png" alt="Halo Combat Evolved and
    Halo 2 Box" id="halo-1-2-box">
    <p id="halo-1">Insert Lorem Ipsum here</p>
    <p id="halo-2">Insert Lorem Ipsum here</p>
    </div>
    </section></code>```

(if you wonder what's the opacity 0 and transition doing in the box-id, that's for an animation to just show the image when scrolling down)

Of course there is some style to the text as well, but I don't think it's important for the question since it's just the color, font-family etc.

As you can see, I've added a div in order to center the image without turning it into a block element. However, if I add float left to the first p-element and float right to the second one, they don´t align next to the text, but under it.

Does anyone know how to align the image in the middle of the window and the first text element left to it and the second one right to it? (I know I could just set the margin-top of the text-elements to minus whatever, but that's not that good for responsiveness)

答:
I hope this works:</p>

```<code><section id="historyBackground">
<div id="centerImage">
<p id="halo-1">Insert Lorem Ipsum here</p>
<center>
     <img src="images/history/halo1&2_box.png" alt="Halo Combat Evolved and Halo 2 Box" id="halo-1-2-box">
</center>
<p id="halo-2">Insert Lorem Ipsum here</p> </div>
</section>
</code>```

Body:
I´m just working on my first website. It´s a onepager about Halo just to mess around a bit and learn HTML, CSS and Javascript. I want to create a section, listing all the boxes of the games with a little text next to them. I got two boxes in one picture. That´s what I got now:

    #historyBackground {
    background: url(../images/uff.jpg);
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: none;
    position: absolute;
    }

    #halo-1-2-box {
    height: 50%;
    width: 30%;
    opacity: 0;
    transition: all ease .5s;
    }

    #centerImage {
    vertical-align: middle;
    text-align:center;
    }

Insert Lorem Ipsum here

Insert Lorem Ipsum here

(if you wonder what's the opacity 0 and transition doing in the box-id, that's for an animation to just show the image when scrolling down)

Of course there is some style to the text as well, but I don't think it's important for the question since it's just the color, font-family etc.

As you can see, I've added a div in order to center the image without turning it into a block element. However, if I add float left to the first p-element and float right to the second one, they don´t align next to the text, but under it.

Does anyone know how to align the image in the middle of the window and the first text element left to it and the second one right to it? (I know I could just set the margin-top of the text-elements to minus whatever, but that's not that good for responsiveness)

Body:
I hope this works:

<section id="historyBackground">
<div id="centerImage">
<p id="halo-1">Insert Lorem Ipsum here</p>
<center>
     <img src="images/history/halo1&2_box.png" alt="Halo Combat Evolved and Halo 2 Box" id="halo-1-2-box">
</center>
<p id="halo-2">Insert Lorem Ipsum here</p> </div>
</section>


问:
How to get the last number of a string using selenium webdriver
1 - 2 of 2

Above is my text. This is from paging of a web application. How do i extract the last number of the above text. SO i will get the count of list in that page and i can run a loop with respect to the number.

答:
You could just split the string using the spaces and then grab the last element of the split array. That should cover you even if the last number has more than one digit. Throw in a trim, just in case, to remove any leading/trailing white space.</p>

```<code>String[] splitter = pageCount.trim().split(" ");
System.out.println(splitter[splitter.length - 1]);
</code>```

Body:
You could just split the string using the spaces and then grab the last element of the split array. That should cover you even if the last number has more than one digit. Throw in a trim, just in case, to remove any leading/trailing white space.

String[] splitter = pageCount.trim().split(" ");
System.out.println(splitter[splitter.length - 1]);


问:
Which file to configure Http Post Authentication for nutch1.13
I am going to crawl a website using Nutch1.13, but the website needs http post authentication.I found that Nutch wiki has some content about it: HttpPostAuthentication.

It said:

A configuration file with a list of domains for which authentication should be done along with the login URL and POST data.

I wonder which file i should put the configuration information in?
I didn't find any concrete example in the article.

I also find another link:NUTCH-827. So do i need to make changes to the source code and rebuild to achieve Http Post Authentication or changes has already be made in nutch1.13?

答:
To specify which file Nutch will need to load with your configuration you should use the http.auth.file key in your nutch-site.xml, you can take a look at the example configuration provided in the httpclient-auth.xml.template. Especially starting at this line https://github.com/apache/nutch/blob/master/conf/httpclient-auth.xml.template#L61.

Keep in mind that you'll need to enable the protocol-httpclient plugin. And finally you will not need to modify Nutch as the status of the NUTCH-827 states this was resolved and merged since v1.10.


问:
Python export some list and put all in for loop
I am writing a program that exports monitoring data.

I have python code which sends API requests and gets a response as json in form of a dictionary.

Responses look like this:

```<code>[
  {
    "diskwrite": 667719532544,
    "name": "test-hostname",
    "maxmem": 536870912,
    "diskread": 876677015576,
    "mem": 496111616,
    "id": "qemu/102",
    "node": "node1",
    "template": 0,
    "cpu": 0.00947819269772254,
    "vmid": 102,
    "type": "qemu",
    "maxcpu": 2,
    "netout": 15081562546,
    "maxdisk": 10737418240,
    **"status": "running",**
    "netin": 15852619497,
    "disk": 0,
    "uptime": 3273086
  },
  {
    "maxcpu": 8,
    "type": "qemu",
    "vmid": 106,
    "cpu": 0.500598230113925,
    "template": 0,
    "node": "node1",
    "id": "qemu/106",
    "mem": 10341007360,
    "maxmem": 10737418240,
    "diskread": 8586078094720,
    "name": "some.other-hostname",
    "diskwrite": 6052378838016,
    "uptime": 1900411,
    "disk": 0,
    "netin": 4899018841106,
    **"status": "stopping",**
    "maxdisk": 107374182400,
    "netout": 4788420573355
  },
  ...
</code>```

I'd like to loop through all the hostnames and their items as is ("diskwrite", "mem", "cpu", etc) but I'd like to add these items to a dictionary only if they have a status of running ("status":"running").

```<code>ram_metric.set({'type': "total"}, ram[0])
cpu_metric.set({'type': 'average', 'interval': '5 minutes'}, cpu[0])
</code>```

I also need a loop that will make this line of code and for every "name" item creating this row with host=name:

```<code>ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
                       {'host': host})
cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
                       {'host': host})
</code>```

Please, I don't know how to do that.

答:
Maybe I am not understanding your question correctly, since I am having a little trouble understanding exactly what you want.

If you want to get a list of all host-names you can do the following.
You can use a list comprehension for this.  Something like:

```<code>running_hosts =  [running_host['name'] for running_host in my_list_of_dicts if running_host['status'] == "running"]
</code>```

Body:
I am writing a program that exports monitoring data.

I have python code which sends API requests and gets a response as json in form of a dictionary.

Responses look like this:

[
  {
    "diskwrite": 667719532544,
    "name": "test-hostname",
    "maxmem": 536870912,
    "diskread": 876677015576,
    "mem": 496111616,
    "id": "qemu/102",
    "node": "node1",
    "template": 0,
    "cpu": 0.00947819269772254,
    "vmid": 102,
    "type": "qemu",
    "maxcpu": 2,
    "netout": 15081562546,
    "maxdisk": 10737418240,
    **"status": "running",**
    "netin": 15852619497,
    "disk": 0,
    "uptime": 3273086
  },
  {
    "maxcpu": 8,
    "type": "qemu",
    "vmid": 106,
    "cpu": 0.500598230113925,
    "template": 0,
    "node": "node1",
    "id": "qemu/106",
    "mem": 10341007360,
    "maxmem": 10737418240,
    "diskread": 8586078094720,
    "name": "some.other-hostname",
    "diskwrite": 6052378838016,
    "uptime": 1900411,
    "disk": 0,
    "netin": 4899018841106,
    **"status": "stopping",**
    "maxdisk": 107374182400,
    "netout": 4788420573355
  },
  ...

I'd like to loop through all the hostnames and their items as is ("diskwrite", "mem", "cpu", etc) but I'd like to add these items to a dictionary only if they have a status of running ("status":"running").

ram_metric.set({'type': "total"}, ram[0])
cpu_metric.set({'type': 'average', 'interval': '5 minutes'}, cpu[0])

I also need a loop that will make this line of code and for every "name" item creating this row with host=name:

ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
                       {'host': host})
cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
                       {'host': host})

Please, I don't know how to do that.

Body:
Maybe I am not understanding your question correctly, since I am having a little trouble understanding exactly what you want.

If you want to get a list of all host-names you can do the following.
You can use a list comprehension for this.  Something like:

running_hosts =  [running_host['name'] for running_host in my_list_of_dicts if running_host['status'] == "running"]


问:
What does DeprecationWarning mean when running Python
I ran a Python program and got a DeprecationWarning, like:

```<code>D:\programs\anaconda2\lib\site-packages\sklearn\utils\deprecation.py:70: DeprecationWarning: Function log_multivariate_normal_density is deprecated; The function log_multivariate_normal_density is deprecated in 0.18 and will be removed in 0.20.
  warnings.warn(msg, category=DeprecationWarning)
</code>```

I can't confirm what is wrong about it. What is a DeprecationWarning?

答: In general developers are developing libraries and in developing sometime add o change thing and sometime remove theme. removing is danger because user may used that and if a developer want to remove a thing first have to notify others to don't use this feature or things and after this he can remove. and DeprecationWarning is this notification.</p>

Body:
I ran a Python program and got a DeprecationWarning, like:

D:\programs\anaconda2\lib\site-packages\sklearn\utils\deprecation.py:70: DeprecationWarning: Function log_multivariate_normal_density is deprecated; The function log_multivariate_normal_density is deprecated in 0.18 and will be removed in 0.20.
  warnings.warn(msg, category=DeprecationWarning)

I can't confirm what is wrong about it. What is a DeprecationWarning?