问:
Converting Geometry to Longitude/Latitude coordinates in R
https://data.sfgov.org/Transportation/Bike-Share-Stations/gtyg-jpkj

I am working with this dataset, and am wondering if I could convert geometry (Geom in the table) to two columns: longitude and latitude in R.

Thank you!

Body:
Yes it is. Easiest way is probably using the tidyr package. Here's the one-liner:

library(tidyr)
df <- fread("~/Downloads/Bike_Share_Stations.csv") # Read data

extract(df, Geom, into = c('Lat', 'Lon'), '\\((.*),(.*)\\)', conv = T)

The last argument is a regular expression using group matches. It is a simple pattern: it starts with a literal (. The most inner two parentheses (.*) are the two coordinates devided by the comma. Only these are extracted. The pattern ends with the corresponding literal ).

Here is a subset of the resulting data:

     UID    Site ID             Last Edited Date           Lat             Lon
  1:   1  SF-T24 S1 05/23/2016 12:00:00 AM +0000 37.7518243814  -122.426627114
  2:   2  SF-G33 S1 05/23/2016 12:00:00 AM +0000 37.7935049482  -122.392846514
  3:   3   SOMA-06A 05/23/2016 12:00:00 AM +0000 37.7897420277  -122.394678441
  4:   4  SF-T22 S5 05/23/2016 12:00:00 AM +0000 37.7512809413  -122.431836215
  5:   5  SF-R25 S4 05/23/2016 12:00:00 AM +0000 37.7567132725  -122.421038213
 ---
103: 103     Embr-E 05/23/2016 12:00:00 AM +0000 37.8047749378  -122.403247294
104: 104  SF-N26 S1 05/23/2016 12:00:00 AM +0000 37.7682271629  -122.420291015
105: 105 Market-11B 05/23/2016 12:00:00 AM +0000 37.7922638478  -122.397066071
106: 106  SF-O27 S2 05/23/2016 12:00:00 AM +0000 37.7671609432  -122.415485214
107: 107  SF-T23 S5 05/23/2016 12:00:00 AM +0000 37.7514609421  -122.429135213


来源: stackexchange

问:
Not all lines of grep output returned
I am writing a shell script to interact with our local Docker repo and have found that I get different results from my bash script than I expect. First, from the command line using:

```<code>des@dev: docker images | grep gateway
</code>```

I get:

```<code>test-gateway     4.27.0-1.5.2-301    b215d109c627        8 days ago           1.977 GB
test-gateway     dev                 b215d109c627        8 days ago           1.977 GB
test-gateway     staging             b215d109c627        8 days ago           1.977 GB
test-gateway     4.26.2-1.5.2-298    7376dd26db6e        2 weeks ago          2.117 GB
test-gateway     4.26.2-1.5.2-297    c84e6de5a18e        2 weeks ago          2.117 GB
test-gateway     4.26.0-1.5.2-296    e6a772c0e230        2 weeks ago          2.048 GB
test-gateway     4.24.3-1.5.2-295    d3743f5246f4        3 weeks ago          1.978 GB
test-gateway     prod                d3743f5246f4        3 weeks ago          1.978 GB
test-gateway     4.24.1-1.5.2-294    99065a070172        5 weeks ago          1.908 GB
test-gateway     4.24.1-1.5.2-293    90639b86573a        5 weeks ago          1.908 GB
test-gateway     4.24.1-1.5.2-292    223f8c3a41cf        5 weeks ago          1.908 GB
test-gateway     4.24.0-1.5.2-291    5646792848cf        6 weeks ago          1.873 GB
test-gateway     4.24.0-1.5.2-290    8a4e92f6a7b9        6 weeks ago          1.847 GB
test-gateway     4.24.0-1.5.2-289    475e72c8691e        6 weeks ago          1.847 GB
test-gateway     4.23.8-1.5.2-288    1c83a9f9ccc4        7 weeks ago          1.812 GB
test-gateway     4.23.8-1.5.2-287    5e77c056c703        7 weeks ago          1.812 GB
test-gateway     4.23.7-1.5.2-286    b9d9f95ec17d        7 weeks ago          1.812 GB
test-gateway     4.23.6-1.5.2-282    f40fe68c0183        8 weeks ago          1.997 GB
</code>```

Running the following script:

```<code>#!/bin/bash
docker images | grep gateway | while read line; do
    read line
    echo "$line"
done;
</code>```

Returns:

```<code>test-gateway     staging             b215d109c627        8 days ago           1.977 GB
test-gateway     4.26.2-1.5.2-298    7376dd26db6e        2 weeks ago          2.117 GB
test-gateway     4.26.0-1.5.2-296    e6a772c0e230        2 weeks ago          2.048 GB
test-gateway     prod                d3743f5246f4        3 weeks ago          1.978 GB
test-gateway     4.24.1-1.5.2-293    90639b86573a        5 weeks ago          1.908 GB
test-gateway     4.24.0-1.5.2-291    5646792848cf        6 weeks ago          1.873 GB
test-gateway     4.24.0-1.5.2-289    475e72c8691e        6 weeks ago          1.847 GB
test-gateway     4.23.8-1.5.2-287    5e77c056c703        7 weeks ago          1.812 GB
test-gateway     4.23.6-1.5.2-282    f40fe68c0183        8 weeks ago          1.997 GB
</code>```

Why doesn't the bash script return all of the matching rows?

NOTE: Just looking at the output I see it appears the script is somehow doing away with lines where the sizes of the images are the same - which makes this even stranger as there is nothing limiting the output in the script.

答:
You have an extra read line call that is making you skip each line of the results as you parse the output, which needs to be removed.

Also remove an extra layer of sub-shell processing by introducing a simple process-substitution syntax with a read command and while-loop. The syntax basically allows you read from the command output as if it were reading from a file.

```<code>while IFS= read -r line; do
    printf '%s\n' "$line"
done< <(docker images | grep gateway)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Not all lines of grep output returned

Body:
I am writing a shell script to interact with our local Docker repo and have found that I get different results from my bash script than I expect. First, from the command line using:

des@dev: docker images | grep gateway

I get:

test-gateway     4.27.0-1.5.2-301    b215d109c627        8 days ago           1.977 GB
test-gateway     dev                 b215d109c627        8 days ago           1.977 GB
test-gateway     staging             b215d109c627        8 days ago           1.977 GB
test-gateway     4.26.2-1.5.2-298    7376dd26db6e        2 weeks ago          2.117 GB
test-gateway     4.26.2-1.5.2-297    c84e6de5a18e        2 weeks ago          2.117 GB
test-gateway     4.26.0-1.5.2-296    e6a772c0e230        2 weeks ago          2.048 GB
test-gateway     4.24.3-1.5.2-295    d3743f5246f4        3 weeks ago          1.978 GB
test-gateway     prod                d3743f5246f4        3 weeks ago          1.978 GB
test-gateway     4.24.1-1.5.2-294    99065a070172        5 weeks ago          1.908 GB
test-gateway     4.24.1-1.5.2-293    90639b86573a        5 weeks ago          1.908 GB
test-gateway     4.24.1-1.5.2-292    223f8c3a41cf        5 weeks ago          1.908 GB
test-gateway     4.24.0-1.5.2-291    5646792848cf        6 weeks ago          1.873 GB
test-gateway     4.24.0-1.5.2-290    8a4e92f6a7b9        6 weeks ago          1.847 GB
test-gateway     4.24.0-1.5.2-289    475e72c8691e        6 weeks ago          1.847 GB
test-gateway     4.23.8-1.5.2-288    1c83a9f9ccc4        7 weeks ago          1.812 GB
test-gateway     4.23.8-1.5.2-287    5e77c056c703        7 weeks ago          1.812 GB
test-gateway     4.23.7-1.5.2-286    b9d9f95ec17d        7 weeks ago          1.812 GB
test-gateway     4.23.6-1.5.2-282    f40fe68c0183        8 weeks ago          1.997 GB

Running the following script:

#!/bin/bash
docker images | grep gateway | while read line; do
    read line
    echo "$line"
done;

Returns:

test-gateway     staging             b215d109c627        8 days ago           1.977 GB
test-gateway     4.26.2-1.5.2-298    7376dd26db6e        2 weeks ago          2.117 GB
test-gateway     4.26.0-1.5.2-296    e6a772c0e230        2 weeks ago          2.048 GB
test-gateway     prod                d3743f5246f4        3 weeks ago          1.978 GB
test-gateway     4.24.1-1.5.2-293    90639b86573a        5 weeks ago          1.908 GB
test-gateway     4.24.0-1.5.2-291    5646792848cf        6 weeks ago          1.873 GB
test-gateway     4.24.0-1.5.2-289    475e72c8691e        6 weeks ago          1.847 GB
test-gateway     4.23.8-1.5.2-287    5e77c056c703        7 weeks ago          1.812 GB
test-gateway     4.23.6-1.5.2-282    f40fe68c0183        8 weeks ago          1.997 GB

Why doesn't the bash script return all of the matching rows?

NOTE: Just looking at the output I see it appears the script is somehow doing away with lines where the sizes of the images are the same - which makes this even stranger as there is nothing limiting the output in the script.

Body:
You have an extra read line call that is making you skip each line of the results as you parse the output, which needs to be removed.

Also remove an extra layer of sub-shell processing by introducing a simple process-substitution syntax with a read command and while-loop. The syntax basically allows you read from the command output as if it were reading from a file.

while IFS= read -r line; do
    printf '%s\n' "$line"
done< <(docker images | grep gateway)


问:
reverse half of the list
I was asked to write a function reverseHalves() that rearranges a given linked list so that the first half of the nodes is moved to the back of the second half. e.g.

Given a linked list [1 2 3 4 5 6], the resulting list should be [4 5 6 1 2 3].

When given a linked list with an odd number of nodes,  the list should be split with the first half  having an additional node. That is, given the list [1 2 3 4 5], the resulting list should be [4 5 1 2 3].

But the my function will give a infinite output...

```<code>typedef struct _listnode{
    int item;
    struct _listnode *next;
} ListNode;

typedef struct _linkedlist{
    int size;
    ListNode *head;
    ListNode *tail;
} LinkedList;
</code>```

Here are the functions I used:

```<code>// printList will print out the value in every nodes until there is a NULL
void printList(LinkedList *ll);
ListNode * findNode(LinkedList *ll, int index);
int insertNode(LinkedList *ll, int index, int value);

void reverseHalves(LinkedList *ll)
{
    int index;
    ListNode *new_head, *new_tail;
    new_head = NULL;
    new_tail = NULL;

    // determine the index of new tail, and the new head which is index+1*
    index = (ll->size + 1) / 2;

    // get the new head by findNode func,whose index is index+1
    // make new_head point to the node found*
    new_head = findNode(ll, index);

    // make initial tail->next be the initial head*
    ll->tail->next = ll->head;

    // set the head to be the new head
    ll->head = new_head;

    insertNode(ll, ll->size, -1);
    new_tail = findNode(ll, ll->size);
    new_tail = NULL;
}
</code>```

答:
Here's the code for reversing second half(right) of linked list.</p>

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

struct Node{
  int data;
  struct Node* next;
};

void append(struct Node** head_ref, int new_data)
{

  struct Node* new_node=(struct Node*)malloc(sizeof(struct Node));
  new_node->data=new_data;
  new_node->next=NULL;

  struct Node* last=*head_ref;
  if(*head_ref==NULL){
      *head_ref=new_node;
      return;
  }

while(last->next!=NULL)
    last=last->next;

last->next=new_node;
return;

}

int display(struct Node* n)
{
  int m=0;
  printf("\n");
  while(n!=NULL)
  {
      printf(" %d ",n->data);
      n=n->next;
      m=m+1;
  }

return m;
}

void reverse(struct Node** head_ref, int mid)
{
if(*head_ref==NULL)
{
    printf("\nEmpty List cannot be reversed");
    return;
}

struct Node* last=*head_ref;
struct Node* second_last;
struct Node* beg=*head_ref;
int c=1;
while(c<=mid){
    second_last=last;
    last=last->next;
    c=c+1;
}

struct Node* prev=NULL;
struct Node* current=last;
struct Node* next;

while(current != NULL)
{
    next=current->next;
    current->next=prev;
    prev=current;
    current=next;
}
*head_ref=beg;
second_last->next=prev;

}

int main()
{
int size;
struct Node* head=NULL;
int i,mid;
for(i=0;i<11;i++)
{
    append(&head,rand()%19 +1);
}
size=display(head);
printf("\n Size of linked list: %d",size);

if(size%2==0)
    mid=(size+1)/2;
else
    mid=size/2;

reverse(&head, mid);
display(head);
return 0;
}
</code>```

Title: reverse half of the list

Body:
I was asked to write a function reverseHalves() that rearranges a given linked list so that the first half of the nodes is moved to the back of the second half. e.g.

Given a linked list [1 2 3 4 5 6], the resulting list should be [4 5 6 1 2 3].

When given a linked list with an odd number of nodes,  the list should be split with the first half  having an additional node. That is, given the list [1 2 3 4 5], the resulting list should be [4 5 1 2 3].

But the my function will give a infinite output...

typedef struct _listnode{
    int item;
    struct _listnode *next;
} ListNode;

typedef struct _linkedlist{
    int size;
    ListNode *head;
    ListNode *tail;
} LinkedList;

Here are the functions I used:

// printList will print out the value in every nodes until there is a NULL
void printList(LinkedList *ll);
ListNode * findNode(LinkedList *ll, int index);
int insertNode(LinkedList *ll, int index, int value);

void reverseHalves(LinkedList *ll)
{
    int index;
    ListNode *new_head, *new_tail;
    new_head = NULL;
    new_tail = NULL;

    // determine the index of new tail, and the new head which is index+1*
    index = (ll->size + 1) / 2;

    // get the new head by findNode func,whose index is index+1
    // make new_head point to the node found*
    new_head = findNode(ll, index);

    // make initial tail->next be the initial head*
    ll->tail->next = ll->head;

    // set the head to be the new head
    ll->head = new_head;

    insertNode(ll, ll->size, -1);
    new_tail = findNode(ll, ll->size);
    new_tail = NULL;
}

Body:
Here's the code for reversing second half(right) of linked list.

#include<stdio.h>
#include<stdlib.h>

struct Node{
  int data;
  struct Node* next;
};

void append(struct Node** head_ref, int new_data)
{

  struct Node* new_node=(struct Node*)malloc(sizeof(struct Node));
  new_node->data=new_data;
  new_node->next=NULL;

  struct Node* last=*head_ref;
  if(*head_ref==NULL){
      *head_ref=new_node;
      return;
  }

while(last->next!=NULL)
    last=last->next;

last->next=new_node;
return;

}

int display(struct Node* n)
{
  int m=0;
  printf("\n");
  while(n!=NULL)
  {
      printf(" %d ",n->data);
      n=n->next;
      m=m+1;
  }

return m;
}

void reverse(struct Node** head_ref, int mid)
{
if(*head_ref==NULL)
{
    printf("\nEmpty List cannot be reversed");
    return;
}

struct Node* last=*head_ref;
struct Node* second_last;
struct Node* beg=*head_ref;
int c=1;
while(c<=mid){
    second_last=last;
    last=last->next;
    c=c+1;
}

struct Node* prev=NULL;
struct Node* current=last;
struct Node* next;

while(current != NULL)
{
    next=current->next;
    current->next=prev;
    prev=current;
    current=next;
}
*head_ref=beg;
second_last->next=prev;

}

int main()
{
int size;
struct Node* head=NULL;
int i,mid;
for(i=0;i<11;i++)
{
    append(&head,rand()%19 +1);
}
size=display(head);
printf("\n Size of linked list: %d",size);

if(size%2==0)
    mid=(size+1)/2;
else
    mid=size/2;

reverse(&head, mid);
display(head);
return 0;
}


问:
Cakephp: multiple levels of belongsto in model
In a model, is it possible to do multiple iterations of belongsTo?

Assuming 3 tables, alerts, schedules, tasks and the model is for alerts. I want to get at a field from tasks but I have to join through schedules.

```<code> alerts.schedule_id -> schedules.tasks_id -> tasks.name
</code>```

I tried this syntax:

```<code>var $belongsTo = array(
         'Schedule' => array(
             'className' => 'Schedule',
             'foreignKey' => 'schedule_id'
         ),
         'Task' => array(
             'className' => 'Task',
             'foreignKey' => 'task_id'
         ));
</code>```

But that just joins both Schedules and Tasks directly to Alerts (here's the sql that was generated:

```<code>LEFT JOIN `schedules` AS `Schedule` ON (`Alert`.`schedule_id` = `Schedule`.`id`) LEFT JOIN `tasks` AS `Task` ON (`Alert`.`task_id` = `Task`.`id`)
)
</code>```

答:
Try this.

in alert.php

```<code>CLass Alert extends AppModel{
    var $name = 'Alert';
    var $belongsTo = array(
         'Schedule' => array(
             'className' => 'Schedule',
             'foreignKey' => 'schedule_id'
         )
    );
}
</code>```

in schedule.php

```<code> CLass Schedule extends AppModel{
        var $name = 'Schedule';
        var $belongsTo = array(
             'Task' => array(
                'className' => 'Task',
                'foreignKey' => 'task_id'
            )
        );
    }
</code>```

then find with recursive=>2

ContentLicense: CC BY-SA 2.5

Body:
In a model, is it possible to do multiple iterations of belongsTo?

Assuming 3 tables, alerts, schedules, tasks and the model is for alerts. I want to get at a field from tasks but I have to join through schedules.

 alerts.schedule_id -> schedules.tasks_id -> tasks.name

I tried this syntax:

var $belongsTo = array(
         'Schedule' => array(
             'className' => 'Schedule',
             'foreignKey' => 'schedule_id'
         ),
         'Task' => array(
             'className' => 'Task',
             'foreignKey' => 'task_id'
         ));

But that just joins both Schedules and Tasks directly to Alerts (here's the sql that was generated:

LEFT JOIN `schedules` AS `Schedule` ON (`Alert`.`schedule_id` = `Schedule`.`id`) LEFT JOIN `tasks` AS `Task` ON (`Alert`.`task_id` = `Task`.`id`)
)

Body:
Try this.

in alert.php

CLass Alert extends AppModel{
    var $name = 'Alert';
    var $belongsTo = array(
         'Schedule' => array(
             'className' => 'Schedule',
             'foreignKey' => 'schedule_id'
         )
    );
}

in schedule.php

 CLass Schedule extends AppModel{
        var $name = 'Schedule';
        var $belongsTo = array(
             'Task' => array(
                'className' => 'Task',
                'foreignKey' => 'task_id'
            )
        );
    }

then find with recursive=>2


问:
Stumped by "The remote server returned an error: (403) Forbidden" with WCF Service in https
I have a WCF Service that I have boiled down to next to nothing because of this error.  It is driving me up the wall.  Here's what I have now.

A very simple WCF service with one method that returns a string with the value, "test".

A very simple Web app that uses the service and puts the value of the string into a label.

A web server running IIS 6 on Win 2003 with a SSL certificate.

Other WCF services on the same server that work.

I publish the WCF service to it's https location

I run the web app in debug mode in VS and it works perfectly.

I publish the web app to it's https location on the same server the WCF service resides under the same SSL certificate

I get, "The remote server returned an error: (403) Forbidden"

I have changed almost every setting in IIS as well as the WCF and Web apps to no avail.  I have compared setting in the WCF services that work and everything is the same.

Below are the setting in the web.config for the WCF Service and the WEB app:

It appears the problem has to do with the Web app but I am out of ideas. Any ideas:

WCF Service:

```<code>  <system.serviceModel>
<bindings>
</code>```

```<code><client />

<services>
  <service behaviorConfiguration="Ucf.Smtp.Wcf.SmtpServiceBehavior" name="Ucf.Smtp.Wcf.SmtpService">
    <host>
      <baseAddresses>
        <add baseAddress="https://test.net.ucf.edu/webservices/Smtp/" />
      </baseAddresses>
    </host>
    <endpoint address="" binding="wsHttpBinding" contract="Ucf.Smtp.Wcf.ISmtpService" bindingConfiguration="SSLBinding">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name="Ucf.Smtp.Wcf.SmtpServiceBehavior">
      <serviceMetadata httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" httpsHelpPageEnabled="True"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
</code>```

Web App:

```<code>    <system.serviceModel>
    <bindings><wsHttpBinding>
<binding name="WSHttpBinding_ISmtpService" closeTimeout="00:01:00"
 openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
 bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
 maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
 textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
 <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
  maxBytesPerRead="4096" maxNameTableCharCount="16384" />
 <reliableSession ordered="true" inactivityTimeout="00:10:00"
  enabled="false" />
 <security mode="Transport">
  <transport clientCredentialType="None" proxyCredentialType="None"
   realm="" />
  <message clientCredentialType="Windows" negotiateServiceCredential="true"
   establishSecurityContext="true" />
 </security>
</binding>
</code>```

```<code><client>

<endpoint address="https://net228.net.ucf.edu/webservices/smtp/SmtpService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISmtpService"
contract="SmtpService.ISmtpService" name="WSHttpBinding_ISmtpService">
<identity>
 <dns value="localhost" />
</identity>
</code>```

```<code>  </client>
</system.serviceModel>
</code>```

答: Make sure you have compilation debug="true" set.

Body:
I have a WCF Service that I have boiled down to next to nothing because of this error.  It is driving me up the wall.  Here's what I have now.

A very simple WCF service with one method that returns a string with the value, "test".

A very simple Web app that uses the service and puts the value of the string into a label.

A web server running IIS 6 on Win 2003 with a SSL certificate.

Other WCF services on the same server that work.

I publish the WCF service to it's https location

I run the web app in debug mode in VS and it works perfectly.

I publish the web app to it's https location on the same server the WCF service resides under the same SSL certificate

I get, "The remote server returned an error: (403) Forbidden"

I have changed almost every setting in IIS as well as the WCF and Web apps to no avail.  I have compared setting in the WCF services that work and everything is the same.

Below are the setting in the web.config for the WCF Service and the WEB app:

It appears the problem has to do with the Web app but I am out of ideas. Any ideas:

WCF Service:

  <system.serviceModel>
<bindings>

<client />

<services>
  <service behaviorConfiguration="Ucf.Smtp.Wcf.SmtpServiceBehavior" name="Ucf.Smtp.Wcf.SmtpService">
    <host>
      <baseAddresses>
        <add baseAddress="https://test.net.ucf.edu/webservices/Smtp/" />
      </baseAddresses>
    </host>
    <endpoint address="" binding="wsHttpBinding" contract="Ucf.Smtp.Wcf.ISmtpService" bindingConfiguration="SSLBinding">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name="Ucf.Smtp.Wcf.SmtpServiceBehavior">
      <serviceMetadata httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" httpsHelpPageEnabled="True"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

Web App:

    <system.serviceModel>
    <bindings><wsHttpBinding>
<binding name="WSHttpBinding_ISmtpService" closeTimeout="00:01:00"
 openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
 bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
 maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
 textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
 <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
  maxBytesPerRead="4096" maxNameTableCharCount="16384" />
 <reliableSession ordered="true" inactivityTimeout="00:10:00"
  enabled="false" />
 <security mode="Transport">
  <transport clientCredentialType="None" proxyCredentialType="None"
   realm="" />
  <message clientCredentialType="Windows" negotiateServiceCredential="true"
   establishSecurityContext="true" />
 </security>
</binding>

<client>

<endpoint address="https://net228.net.ucf.edu/webservices/smtp/SmtpService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISmtpService"
contract="SmtpService.ISmtpService" name="WSHttpBinding_ISmtpService">
<identity>
 <dns value="localhost" />
</identity>

  </client>
</system.serviceModel>


问:
Convert xml to csv in Power shell
Hello I am new to Powershell, but I have looked all over for an answer to this question, how do I convert XML data to CSV data in powershell?

Here is my xml file:

```<code><users>
     <user>
        <id>"data"</id>
        <name>"data"</name>
        <disabled>"data"</disabled>
        <title>"data"</title>
        <email>"data"</email>
        <role>
             <name>"data"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60019</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data"</name>
        </site>
    </user>
</users>
</code>```

The fields that are multiple layers in the tree are the biggest pain. Here is the script I have come up with so far. I am able to get the basic fields such as name and email. I really need the fields that are labeled custom fields and their subsets.

```<code>#Converts the xml to a CSV file
$samage_users.users.user | select-Object @(
@{l="Email";e={$_.email}},
@{l="Name";e={$_.name}},
@{l="ID";e={$_.ID}},
@{l="Phone";e={$_.phone}},
@{l="Site";e={$_.site.name}},
@{l="Reports_To";e={$_.reports_to.name}},
@{l="Reports_To_Email";e={$_.reports_to.email}})|
export-csv "Samanage_users.csv" -NoTypeInformation -Append
$page ++
start-sleep -s 10
}
While ($page -lt ($pages + 2))
}
Function NewUsers
{
foreach ($user in $new_user)
{
</code>```

CSV output file should look something like this. (see attached)

CSV Output File

Any help is greatly appreciated!

Thanks

答:
You would need to generate an object, similarly to how you are doing it now, but you would need to add properties to it for each custom field before outputting it. The only complication comes in if you have users with different custom fields. Since PowerShell won't output any properties that the first item in your array has you have to find all potential properties, and add them to the first object. This should do what you want I'm fairly sure. I've added a second user to the XML with a different custom field (replaced 60019 with 60034) to show the output.

```<code>[xml]$samage_users=@'
<users>
        <user>
        <id>"data"</id>
        <name>"data"</name>
        <disabled>"data"</disabled>
        <title>"data"</title>
        <email>"data"</email>
        <role>
                <name>"data"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60019</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data"</name>
        </site>
    </user>
    <user>
        <id>"data2"</id>
        <name>"data2"</name>
        <disabled>"data2"</disabled>
        <title>"data2"</title>
        <email>"data2"</email>
        <role>
                <name>"data2"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60034</custom_field_id>
                <value>"data2"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data2"</name>
        </site>
    </user>
</users>
'@

$Results = ForEach($User in $samage_users.users.user) {
    $UserObject = [PSCustomObject][ordered]@{
        "Email" = $User.email
        "Name" = $User.name
        "ID" = $User.ID
        "Phone" = $User.phone
        "Site" = $User.site.name
        "Reports_To" = $User.reports_to.name
        "Reports_To_Email" = $User.reports_to.email
    }
    $User.custom_fields_values.custom_fields_value | ForEach {Add-Member -InputObject $UserObject -NotePropertyName $_.custom_field_id -NotePropertyValue $_.value}
    $UserObject
}
$Results | ForEach{ $_.PSObject.Properties.Name }| Select -Unique | Where{ $_ -notin $Results[0].PSObject.Properties.Name } | ForEach{ Add-Member -InputObject $Results[0] -NotePropertyName $_ -NotePropertyValue ' ' }
$Results | FT *
</code>```

The output of that is:

```<code>Email   Name    ID      Phone Site    Reports_To Reports_To_Email 60019  60021   60018   60034
-----   ----    --      ----- ----    ---------- ---------------- -----  -----   -----   -----
"data"  "data"  "data"        "data"                              "data" "data"  "data"
"data2" "data2" "data2"       "data2"                                    "data2" "data2" "data2"
</code>```

You could just as easily pipe $Results to Export-Csv if you need it output to a file.

Title: Convert xml to csv in Power shell

Body:
Hello I am new to Powershell, but I have looked all over for an answer to this question, how do I convert XML data to CSV data in powershell?

Here is my xml file:

<users>
     <user>
        <id>"data"</id>
        <name>"data"</name>
        <disabled>"data"</disabled>
        <title>"data"</title>
        <email>"data"</email>
        <role>
             <name>"data"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60019</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data"</name>
        </site>
    </user>
</users>

The fields that are multiple layers in the tree are the biggest pain. Here is the script I have come up with so far. I am able to get the basic fields such as name and email. I really need the fields that are labeled custom fields and their subsets.

#Converts the xml to a CSV file
$samage_users.users.user | select-Object @(
@{l="Email";e={$_.email}},
@{l="Name";e={$_.name}},
@{l="ID";e={$_.ID}},
@{l="Phone";e={$_.phone}},
@{l="Site";e={$_.site.name}},
@{l="Reports_To";e={$_.reports_to.name}},
@{l="Reports_To_Email";e={$_.reports_to.email}})|
export-csv "Samanage_users.csv" -NoTypeInformation -Append
$page ++
start-sleep -s 10
}
While ($page -lt ($pages + 2))
}
Function NewUsers
{
foreach ($user in $new_user)
{

CSV output file should look something like this. (see attached)

CSV Output File

Any help is greatly appreciated!

Thanks

Body:
You would need to generate an object, similarly to how you are doing it now, but you would need to add properties to it for each custom field before outputting it. The only complication comes in if you have users with different custom fields. Since PowerShell won't output any properties that the first item in your array has you have to find all potential properties, and add them to the first object. This should do what you want I'm fairly sure. I've added a second user to the XML with a different custom field (replaced 60019 with 60034) to show the output.

[xml]$samage_users=@'
<users>
        <user>
        <id>"data"</id>
        <name>"data"</name>
        <disabled>"data"</disabled>
        <title>"data"</title>
        <email>"data"</email>
        <role>
                <name>"data"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60019</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data"</name>
        </site>
    </user>
    <user>
        <id>"data2"</id>
        <name>"data2"</name>
        <disabled>"data2"</disabled>
        <title>"data2"</title>
        <email>"data2"</email>
        <role>
                <name>"data2"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60034</custom_field_id>
                <value>"data2"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data2"</name>
        </site>
    </user>
</users>
'@

$Results = ForEach($User in $samage_users.users.user) {
    $UserObject = [PSCustomObject][ordered]@{
        "Email" = $User.email
        "Name" = $User.name
        "ID" = $User.ID
        "Phone" = $User.phone
        "Site" = $User.site.name
        "Reports_To" = $User.reports_to.name
        "Reports_To_Email" = $User.reports_to.email
    }
    $User.custom_fields_values.custom_fields_value | ForEach {Add-Member -InputObject $UserObject -NotePropertyName $_.custom_field_id -NotePropertyValue $_.value}
    $UserObject
}
$Results | ForEach{ $_.PSObject.Properties.Name }| Select -Unique | Where{ $_ -notin $Results[0].PSObject.Properties.Name } | ForEach{ Add-Member -InputObject $Results[0] -NotePropertyName $_ -NotePropertyValue ' ' }
$Results | FT *

The output of that is:

Email   Name    ID      Phone Site    Reports_To Reports_To_Email 60019  60021   60018   60034
-----   ----    --      ----- ----    ---------- ---------------- -----  -----   -----   -----
"data"  "data"  "data"        "data"                              "data" "data"  "data"
"data2" "data2" "data2"       "data2"                                    "data2" "data2" "data2"

You could just as easily pipe $Results to Export-Csv if you need it output to a file.


问:
How to detect value changes of an input jQuery?
I am currently using this function to detect for any changes made to an input box in jQuery.

```<code>$(document).on("input change paste keyup", "input, textarea, select", function(e) {
    //do something
});
</code>```

The problem is that when you change the value of an input through code such as this $("input").val(currentColorChosen);, the function does not run.

How do I solve this so that the function can detect all changes made to an input, including value changes made through jQuery.

答:
I had just posted answer here

You can try using interval or timeout like this

```<code>var searchValue = $('#myTextbox').val();

function checkSearchChanged() {
    var currentValue = $('#myTextbox').val();
    if ((currentValue) && currentValue != searchValue && currentValue != '') {
        searchValue = $('#myTextbox').val();
       console.log(searchValue)
    }
    setTimeout(checkSearchChanged, 0.1);
}

$(function () {
    setTimeout(checkSearchChanged, 0.1);
});
</code>```

checkout working plunker here

Body:
I am currently using this function to detect for any changes made to an input box in jQuery.

$(document).on("input change paste keyup", "input, textarea, select", function(e) {
    //do something
});

The problem is that when you change the value of an input through code such as this $("input").val(currentColorChosen);, the function does not run.

How do I solve this so that the function can detect all changes made to an input, including value changes made through jQuery.

Body:
I had just posted answer here

You can try using interval or timeout like this

var searchValue = $('#myTextbox').val();

function checkSearchChanged() {
    var currentValue = $('#myTextbox').val();
    if ((currentValue) && currentValue != searchValue && currentValue != '') {
        searchValue = $('#myTextbox').val();
       console.log(searchValue)
    }
    setTimeout(checkSearchChanged, 0.1);
}

$(function () {
    setTimeout(checkSearchChanged, 0.1);
});

checkout working plunker here


问:
Filtering a Key Value from a Dictionary in C#
I'm new to C# and am currently trying to figure out the best way to implement the following:

I have a list of species with an associated group:

```<code>Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"
</code>```

Given a string of an animal, I need to return its group.
eg. "Cheetah" would return "Cat".

I have implemented the following:

```<code>// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}
</code>```

Instead of having a foreach loop, is there a faster way to find the key given an animal value?

//EDIT:

Currently trying to initialize with a Tuple

```<code>var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};
</code>```

I'm getting the following error:     Unexpected symbol `{'

答:
If you don't want to use another way to store your data and you store them in a dictionary with keys the animal species, I would suggest you change the type of the value that is associated with each key, to a HashSet

```<code>Dictionary<string, HashSet<string>>
</code>```

Doing so you can iterate through the keys (O(n), where n is the number of keys) of the dictionary and using HashSet Contains method in O(1) you can find out if the animal is associated with the current key/spiece or not.

Body:
I'm new to C# and am currently trying to figure out the best way to implement the following:

I have a list of species with an associated group:

Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"

Given a string of an animal, I need to return its group.
eg. "Cheetah" would return "Cat".

I have implemented the following:

// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}

Instead of having a foreach loop, is there a faster way to find the key given an animal value?

//EDIT:

Currently trying to initialize with a Tuple

var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};

I'm getting the following error:     Unexpected symbol `{'

Body:
If you don't want to use another way to store your data and you store them in a dictionary with keys the animal species, I would suggest you change the type of the value that is associated with each key, to a HashSet

Dictionary<string, HashSet<string>>

Doing so you can iterate through the keys (O(n), where n is the number of keys) of the dictionary and using HashSet Contains method in O(1) you can find out if the animal is associated with the current key/spiece or not.


问:
Figuring out if variable is instanceof a prototype of a function
Say I have

```<code>function Foo() {
    // stuff
}

Foo.prototype.bar = function() {
    return new Bar();
}

function Bar() {};

module.exports = Foo;
</code>```

Now say I have

```<code>const foo = new Foo();
console.log(foo instanceof Foo); // true

const bar = new Foo().bar();
console.log(bar instanceof Foo); // false
console.log(bar instanceof Foo.prototype.bar); // false
</code>```

Here Bar is never exported. So how can I test if bar is an instance of ... something? Can I somehow have bar instanceof Foo or a subset of Foo or something?

答:
You could compare the prototype of one bar to another:</p>

```<code> Object.getPrototypeOf(bar) === Object.getPrototypeOf((new Foo).bar())
</code>```

Body:
Say I have

function Foo() {
    // stuff
}

Foo.prototype.bar = function() {
    return new Bar();
}

function Bar() {};

module.exports = Foo;

Now say I have

const foo = new Foo();
console.log(foo instanceof Foo); // true

const bar = new Foo().bar();
console.log(bar instanceof Foo); // false
console.log(bar instanceof Foo.prototype.bar); // false

Here Bar is never exported. So how can I test if bar is an instance of ... something? Can I somehow have bar instanceof Foo or a subset of Foo or something?

Body:
You could compare the prototype of one bar to another:

 Object.getPrototypeOf(bar) === Object.getPrototypeOf((new Foo).bar())


问:
How can I use set_fact and with_together?
I am trying to convert bash environment variables that are sourced from a properties file on a remote machine. I am registering the keys and values to two register variables and then trying to loop through them using with_together and set_fact

Here is how I am sourcing my variables key/values

```<code>- name: Source Env Properties
  shell: . <source utility> && ( set -a posix ; set| sed 's,=.*,,' )
  register: variable_keys

- shell: . <source utility> && ( set -a posix ; set| sed 's,^.*=,,' )
  register: variable_values
</code>```

After that I try to set_fact using the two registered values.

```<code>- name: set variables
  set_fact:
     "{{item.0}}:{{item.1}}"
  with_together:
    - "{{ variable_keys.stdout_lines }}"
    - "{{ variable_values.stdout_lines }}"
</code>```

The output of the tasks seems like it should be working but when trying to use those variables it says they are not defined.

Can anyone tell me why this isn't working?

答:
So, your first problem, as I alluded to in my comment, is that the syntax in your set_fact block is incorrect.  If you have this:

```<code>"{{item.0}}:{{item.1}}"
</code>```

Then you have single string, not a key: value pair.  You would need to modify that to look like

```<code>- name: set variables
  set_fact:
    "{{item.0}}": "{{item.1}}"
  with_together:
    - "{{ variable_keys.stdout_lines }}"
    - "{{ variable_values.stdout_lines }}"
</code>```

But that's only half the problem.  Your sed expressions may end up producing syntactically invalid output, because they will include bash function definitions. That is, if I run the first command in my local environment, the output includes all the cruft from shell functions for bash completions, git prompts, etc, like this:

```<code>scl ()
{
    local CMD
    if [ "$CMD"
        eval "module $@";
    else
        /usr/bin/scl "$@";
    fi
}
</code>```

That's just going to break ansible:

```<code>failed: [localhost] (item=[u"'", u"'"]) => {"changed": false, "failed": true, "item": ["'", "'"], "msg": "The variable name ''' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}
</code>```

You'll need to make sure you filter out that content.  I used this:

```<code>- name: Source Env Properties
  shell: . ./myvars.sh && ( set -a posix; set| sed -n '/^[A-Z]/ s,=.*,,p' )
  register: variable_keys

- shell: . ./myvars.sh && ( set -a posix; set| sed -n '/^[A-Z]/ s,^.*=,,p' )
  register: variable_values

- name: set variables
  set_fact:
    "{{item.0}}": "{{item.1}}"
  with_together:
    - "{{ variable_keys.stdout_lines }}"
    - "{{ variable_values.stdout_lines }}"
</code>```

If I have have, in myvars.sh:

```<code>FOO=bar
</code>```

And if in my playbook I have, after the above:

```<code>- debug:
    var: FOO
</code>```

I will see as output:

```<code>ok: [localhost] => {
    "FOO": "bar"
}
</code>```

Incidentally, I think all this mucking about with sed is fragile and may cause other problems down the road.  I would probably do something like this:

```<code>- name: Source Env Properties
  shell: |
    set -a
    . ./myvars.sh
    jq -n env
  register: vars_raw

- set_fact:
    shellvars: "{{ vars_raw.stdout|from_json }}"

- debug:
    var: shellvars.FOO
</code>```

This uses jq to export all available environment variables as JSON, and then assigns the result to the shellvars variable.  The set -a there assures that any variables set in myvars.sh are exported to the environment. If you don't have jq handy, you could use python:

```<code>- name: Source Env Properties
  shell: |
    set -a
    . ./myvars.sh
    python -c 'import json; import os; print(json.dumps(dict(os.environ)))'
  register: vars_raw

- set_fact:
    shellvars: "{{ vars_raw.stdout|from_json }}"

- debug:
    var: shellvars.FOO
</code>```

Body:
I am trying to convert bash environment variables that are sourced from a properties file on a remote machine. I am registering the keys and values to two register variables and then trying to loop through them using with_together and set_fact

Here is how I am sourcing my variables key/values

- name: Source Env Properties
  shell: . <source utility> && ( set -a posix ; set| sed 's,=.*,,' )
  register: variable_keys

- shell: . <source utility> && ( set -a posix ; set| sed 's,^.*=,,' )
  register: variable_values

After that I try to set_fact using the two registered values.

- name: set variables
  set_fact:
     "{{item.0}}:{{item.1}}"
  with_together:
    - "{{ variable_keys.stdout_lines }}"
    - "{{ variable_values.stdout_lines }}"

The output of the tasks seems like it should be working but when trying to use those variables it says they are not defined.

Can anyone tell me why this isn't working?

Body:
So, your first problem, as I alluded to in my comment, is that the syntax in your set_fact block is incorrect.  If you have this:

"{{item.0}}:{{item.1}}"

Then you have single string, not a key: value pair.  You would need to modify that to look like

- name: set variables
  set_fact:
    "{{item.0}}": "{{item.1}}"
  with_together:
    - "{{ variable_keys.stdout_lines }}"
    - "{{ variable_values.stdout_lines }}"

But that's only half the problem.  Your sed expressions may end up producing syntactically invalid output, because they will include bash function definitions. That is, if I run the first command in my local environment, the output includes all the cruft from shell functions for bash completions, git prompts, etc, like this:

scl ()
{
    local CMD
    if [ "$CMD"
        eval "module $@";
    else
        /usr/bin/scl "$@";
    fi
}

That's just going to break ansible:

failed: [localhost] (item=[u"'", u"'"]) => {"changed": false, "failed": true, "item": ["'", "'"], "msg": "The variable name ''' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}

You'll need to make sure you filter out that content.  I used this:

- name: Source Env Properties
  shell: . ./myvars.sh && ( set -a posix; set| sed -n '/^[A-Z]/ s,=.*,,p' )
  register: variable_keys

- shell: . ./myvars.sh && ( set -a posix; set| sed -n '/^[A-Z]/ s,^.*=,,p' )
  register: variable_values

- name: set variables
  set_fact:
    "{{item.0}}": "{{item.1}}"
  with_together:
    - "{{ variable_keys.stdout_lines }}"
    - "{{ variable_values.stdout_lines }}"

If I have have, in myvars.sh:

FOO=bar

And if in my playbook I have, after the above:

- debug:
    var: FOO

I will see as output:

ok: [localhost] => {
    "FOO": "bar"
}

Incidentally, I think all this mucking about with sed is fragile and may cause other problems down the road.  I would probably do something like this:

- name: Source Env Properties
  shell: |
    set -a
    . ./myvars.sh
    jq -n env
  register: vars_raw

- set_fact:
    shellvars: "{{ vars_raw.stdout|from_json }}"

- debug:
    var: shellvars.FOO

This uses jq to export all available environment variables as JSON, and then assigns the result to the shellvars variable.  The set -a there assures that any variables set in myvars.sh are exported to the environment. If you don't have jq handy, you could use python:

- name: Source Env Properties
  shell: |
    set -a
    . ./myvars.sh
    python -c 'import json; import os; print(json.dumps(dict(os.environ)))'
  register: vars_raw

- set_fact:
    shellvars: "{{ vars_raw.stdout|from_json }}"

- debug:
    var: shellvars.FOO


问:
jQuery pause function on hover?
I have a jQuery/JS function that is using setInterval to loop through some image slides I have.  It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it.  How do I go about doing that on the setInterval function?

```<code>var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);
</code>```

答:
```<code>(function () {
    var imgs = $('#your_div img'), index = 0, interval,

        interval_function = function () {
            imgs.eq(index).hide();
            index = (index + 1) % imgs.length;
            imgs.eq(index).show();
        };

    imgs.eq(0).show();
    interval = setInterval(interval_function, 5000);

    $('#your_div').hover(function () {
        clearInterval(interval);
    }, function () {
        interval = setInterval(interval_function, 5000);
    });
}());
</code>```

Example: http://jsfiddle.net/Zq7KB/3/

I reused some old code I wrote for a question the other day, but I figured it didn't matter that much. The trick is to store your interval in a variable that you keep in the background. Then, when you hover over the container, clear the interval. When you hover out of the container, re-set the interval. To get a better feel of how this works, change those 5000s to 1000s so it passes more quickly for testing.

Hope this helps.

Title: jQuery pause function on hover?

Body:
I have a jQuery/JS function that is using setInterval to loop through some image slides I have.  It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it.  How do I go about doing that on the setInterval function?

var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);

Body:
(function () {
    var imgs = $('#your_div img'), index = 0, interval,

        interval_function = function () {
            imgs.eq(index).hide();
            index = (index + 1) % imgs.length;
            imgs.eq(index).show();
        };

    imgs.eq(0).show();
    interval = setInterval(interval_function, 5000);

    $('#your_div').hover(function () {
        clearInterval(interval);
    }, function () {
        interval = setInterval(interval_function, 5000);
    });
}());

Example: http://jsfiddle.net/Zq7KB/3/

I reused some old code I wrote for a question the other day, but I figured it didn't matter that much. The trick is to store your interval in a variable that you keep in the background. Then, when you hover over the container, clear the interval. When you hover out of the container, re-set the interval. To get a better feel of how this works, change those 5000s to 1000s so it passes more quickly for testing.

Hope this helps.


答:
A better modeling of the data will be to create a class of the group which will have a name and a collection of animals in it. Then you can hold a collection of groups and query it.

If you want to stick with the dictionary then: As your question is to retrieve the key for a given value out of the list of values for that key, I'd organize the data the other way around:

```<code>var map = new Dictionary<string,string>
{
    ["Cheetah"] = "Cat",
    ["Lion"] = "Cat",
    //....
};
</code>```

Then you can search by your real key - which is the species and not the group:

```<code>if(map.TryGetValue("Lion", out var group)) { }
</code>```

As it is easier to construct the data by grouping to list of species you can:

```<code>var rawData = new List<(string group, List<string> species)>
{
    ("Cat", new List<string> { "Cheetah", "Lion" }),
    //...
};

var result = rawData.SelectMany(item => item.species.Select(s => (s, item.group)))
                    .ToDictionary(k => k.s, v => v.group);
</code>```

This works with C#7.0 named tuples. If you are using a previous version you can use anonymous types or "old fashion" tuples

For a pre C# 7.0 initialization of the collection:

```<code>var rawData = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" })
};
</code>```

Title: Filtering a Key Value from a Dictionary in C#

Body:
A better modeling of the data will be to create a class of the group which will have a name and a collection of animals in it. Then you can hold a collection of groups and query it.

If you want to stick with the dictionary then: As your question is to retrieve the key for a given value out of the list of values for that key, I'd organize the data the other way around:

var map = new Dictionary<string,string>
{
    ["Cheetah"] = "Cat",
    ["Lion"] = "Cat",
    //....
};

Then you can search by your real key - which is the species and not the group:

if(map.TryGetValue("Lion", out var group)) { }

As it is easier to construct the data by grouping to list of species you can:

var rawData = new List<(string group, List<string> species)>
{
    ("Cat", new List<string> { "Cheetah", "Lion" }),
    //...
};

var result = rawData.SelectMany(item => item.species.Select(s => (s, item.group)))
                    .ToDictionary(k => k.s, v => v.group);

This works with C#7.0 named tuples. If you are using a previous version you can use anonymous types or "old fashion" tuples

For a pre C# 7.0 initialization of the collection:

var rawData = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" })
};


问:
WPF: Grid with column/row margin/padding?
Is it easily possible to specify a margin and/or padding for rows or columns in a WPF Grid?

I could of course add extra columns to space things out, but this seems like a job for padding/margins (it will give much simplier XAML). Has someone derived from the standard Grid to add this functionality?

答:
in uwp (Windows10FallCreatorsUpdate version and above)</p>

```<code><Grid RowSpacing="3" ColumnSpacing="3">
</code>```

Body:
in uwp (Windows10FallCreatorsUpdate version and above)

<Grid RowSpacing="3" ColumnSpacing="3">


问:
sql inner join reference a table in subquery
The query below:

```<code>select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId
    join Yetkilendirme.Users yu
        on mi.CreatedBy = yu.ID
    join Muayene.Tani mt
        on mm.ID = mt.MuayeneId
where
    mm.IsDeleted <> 1
    and mi.IsDeleted <> 1
    and mt.IsDeleted <> 1
group by
    yu.Soyad,
    mt.ICD10Kodu
</code>```

returns the data below:

```<code>HALAÇ           J00 5
DEĞİRMENCİOĞLU  J00 12
GÖKALP          J02 22
DİKİLİLER       J03 14
</code>```

but actually I need the rate of the entity not the exact number it occurs so I need to divide it like this:

```<code>select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID)/count(select * from Muayene.Muayene where ID=mm.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId...
</code>```

but it doesn't work. It gives the error message:

the multipart identifier mi.ID couldn't be found

How can I make it work?

答:
You can't do it like this because you are not grouping mm.ID field. You should calculate the counts in seperated queries and then you can join them to calculate ratio;

```<code>select yu.Soyad, mt.ICD10Kodu, AASayisi, MMSayisi, (cast(AASayisi as float)/cast(MMSayisi as float)) As Ratio from (
select yu.ID as YUID, yu.Soyad, mt.ICD10Kodu, count(mi.ID) as AASayisi
from Muayene.Muayene mm
join Muayene.Ilac mi on mm.ID = mi.MuayeneId
join Yetkilendirme.Users yu on mi.CreatedBy = yu.ID
join Muayene.Tani mt on mm.ID = mt.MuayeneId
where mm.IsDeleted <> 1 and mi.IsDeleted <> 1 and mt.IsDeleted <> 1
group by yu.ID,yu.Soyad, mt.ICD10Kodu) miCountsQuery inner join (select yu.ID as YUID,yu.Soyad, count(mm.ID) as MMSayisi
from Muayene.Muayene mm
join Yetkilendirme.Users yu on mm.CreatedBy = yu.ID
where mm.IsDeleted <> 1
group by yu.ID,yu.Soyad) mmCountsQuery ON miCountsQuery.YUID = mmCountsQuery.YUID
</code>```

The query wasn't tested. Some modifications might be needed.

Body:
The query below:

select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId
    join Yetkilendirme.Users yu
        on mi.CreatedBy = yu.ID
    join Muayene.Tani mt
        on mm.ID = mt.MuayeneId
where
    mm.IsDeleted <> 1
    and mi.IsDeleted <> 1
    and mt.IsDeleted <> 1
group by
    yu.Soyad,
    mt.ICD10Kodu

returns the data below:

HALAÇ           J00 5
DEĞİRMENCİOĞLU  J00 12
GÖKALP          J02 22
DİKİLİLER       J03 14

but actually I need the rate of the entity not the exact number it occurs so I need to divide it like this:

select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID)/count(select * from Muayene.Muayene where ID=mm.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId...

but it doesn't work. It gives the error message:

the multipart identifier mi.ID couldn't be found

How can I make it work?

Body:
You can't do it like this because you are not grouping mm.ID field. You should calculate the counts in seperated queries and then you can join them to calculate ratio;

select yu.Soyad, mt.ICD10Kodu, AASayisi, MMSayisi, (cast(AASayisi as float)/cast(MMSayisi as float)) As Ratio from (
select yu.ID as YUID, yu.Soyad, mt.ICD10Kodu, count(mi.ID) as AASayisi
from Muayene.Muayene mm
join Muayene.Ilac mi on mm.ID = mi.MuayeneId
join Yetkilendirme.Users yu on mi.CreatedBy = yu.ID
join Muayene.Tani mt on mm.ID = mt.MuayeneId
where mm.IsDeleted <> 1 and mi.IsDeleted <> 1 and mt.IsDeleted <> 1
group by yu.ID,yu.Soyad, mt.ICD10Kodu) miCountsQuery inner join (select yu.ID as YUID,yu.Soyad, count(mm.ID) as MMSayisi
from Muayene.Muayene mm
join Yetkilendirme.Users yu on mm.CreatedBy = yu.ID
where mm.IsDeleted <> 1
group by yu.ID,yu.Soyad) mmCountsQuery ON miCountsQuery.YUID = mmCountsQuery.YUID

The query wasn't tested. Some modifications might be needed.


问:
How do you keep html semantically correct and and handle big css of complex designs like Big portals or News sites?
In personal and small business websites it's not so difficult but when we comes to New sites,Portals and E-commerce sites, where so many content comes on each pages, it's little hard.

How do you keep **HTML semantically correct and and handle big CSS of complex designs like Big portals or News sites?**

How to keep the HTML code semantically correct and Semantic naming convention for css classes and ID?

Is to use CSS grid Framework the best way to handle CSS in this scenario?

答: While in general you'll want to avoid "div soup", div and span have no meaning, and there's no reason you can't use them liberally in addition to "semantically correct" HTML if they help you organize.


问:
JavaScript function confusion?
I am trying to understand why does this code prints out a triangle.I wrote it,i don't know why the hell it works,and,how does it work</p>

```<code>function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
    line += "* ";
}
return line + "\n";

}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(width) {
var line = "";
for (i = 1 ; i <= width ; i++) {
    line += makeLine(i);
  }
return line;
}

console.log(buildTriangle(10));
</code>```

答:
makeLine(length) returns a line with a certain number of * (depending on the "length" passed as argument).

buildTriangle(width) calls the previous function several times passing numbers from 1 to whatever number you pass as "width" parameter (10 in your example).

Title: JavaScript function confusion?

Body:
I am trying to understand why does this code prints out a triangle.I wrote it,i don't know why the hell it works,and,how does it work

function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
    line += "* ";
}
return line + "\n";

}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(width) {
var line = "";
for (i = 1 ; i <= width ; i++) {
    line += makeLine(i);
  }
return line;
}

console.log(buildTriangle(10));


问:
How to get the number of distinct words by length in Spark (python)?

I have the following code that results in a list with tuples.

```<code> words \
  .map(lambda word: (word.lower(), 1))\
  .reduceByKey(lambda a, b: a + b)\
  .filter(lambda(x,y): y >= 3)
</code>```

The tuple list looks as followed:

```<code>[(u'pardon', 6),
 (u'four', 8),
 (u'sleep', 6),
 (u'lory', 7),
 (u'pardon', 6)]
</code>```

How can I extend the code, so I can get the number of words by length? It should look like this:

```<code>[(6,2),
 (7,1),
 (8,1)]
</code>```

答:
Replace _.tolower() with len(_):

```<code>word.map(lambda word: (len(word), 1))
</code>```

Body:
I have the following code that results in a list with tuples.

 words \
  .map(lambda word: (word.lower(), 1))\
  .reduceByKey(lambda a, b: a + b)\
  .filter(lambda(x,y): y >= 3)

The tuple list looks as followed:

[(u'pardon', 6),
 (u'four', 8),
 (u'sleep', 6),
 (u'lory', 7),
 (u'pardon', 6)]

How can I extend the code, so I can get the number of words by length? It should look like this:

[(6,2),
 (7,1),
 (8,1)]

Body:
Replace _.tolower() with len(_):

word.map(lambda word: (len(word), 1))


问:
How to compare an array of integers and display them from greatest to least in C++
I'm working on some exercises from the Cplusplus.com website in order to improve my programming and to learn and relearn some material from a class I have taken this year and the problem below is what I am working and specifically the last bolded portion.

Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10)
  Once the data has been entered the program must analyze the data and output which person ate the most pancakes for breakfast.

Modify the program so that it outputs a number of pancakes eaten of all 10 people like for example..

Person 4: ate 10 pancakes

Person 3: ate 7 pancakes

Person 8: ate 4 pancakes

etc...

Here is what I have so far

```<code>#include <iostream>

using namespace std;

void getPancakesEaten(int pancakes[]);
void comparePancakesEaten(int pancakes[]);
void displayOrder(int pancakes[]);

/**********************************************************************
* Gets the amount of Pancakes eaten
***********************************************************************/
void getPancakesEaten(int pancakes[])
{

    for(int i = 0; i < 10; i++)
    {
        cout << "Person " << i + 1 << ": ate ";
        cin >> pancakes[i];
    }

    cout << endl;
}

/**********************************************************************
* Compares the amount of pancakes eaten with each person
***********************************************************************/
void comparePancakesEaten(int pancakes[])
{
    if(pancakes[0] > pancakes[1] && pancakes[0] > pancakes[2] && pancakes[0] >               pancakes[3] && pancakes[0] > pancakes[4] && pancakes[0] > pancakes[5] && pancakes[0] > pancakes[6] && pancakes[0] > pancakes[7] && pancakes[0] > pancakes[8] && pancakes[9])
{
    cout << "Person 1 ate " << pancakes[0] << " pancakes" << endl;
}

else if(pancakes[1] > pancakes[0] && pancakes[1] > pancakes[2] && pancakes[1] > pancakes[3] && pancakes[1] > pancakes[4] && pancakes[1] > pancakes[5] && pancakes[1] > pancakes[6] && pancakes[1] > pancakes[7] && pancakes[1] > pancakes[8] && pancakes[1] > pancakes[9])
{
    cout << "Person 2 ate " << pancakes[1] << " pancakes" << endl;
}

else if(pancakes[2] > pancakes[0] && pancakes[2] > pancakes[1] && pancakes[2] > pancakes[3] && pancakes[2] > pancakes[4] && pancakes[2] > pancakes[5] && pancakes[2] > pancakes[6] && pancakes[2] > pancakes[7] && pancakes[2] > pancakes[8] && pancakes[2] > pancakes[9])
{
    cout << "Person 3 ate " << pancakes[2] << " pancakes" << endl;
}

else if(pancakes[3] > pancakes[0] && pancakes[3] > pancakes[2] && pancakes[3] > pancakes[1] && pancakes[3] > pancakes[4] && pancakes[3] > pancakes[5] && pancakes[3] > pancakes[6] && pancakes[3] > pancakes[7] && pancakes[3] > pancakes[8] && pancakes[3] > pancakes[9])
{
    cout << "Person 4 ate " << pancakes[3] << " pancakes" << endl;
}

else if(pancakes[4] > pancakes[0] && pancakes[4] > pancakes[2] && pancakes[4] > pancakes[3] && pancakes[4] > pancakes[1] && pancakes[4] > pancakes[5] && pancakes[4] > pancakes[6] && pancakes[4] > pancakes[7] && pancakes[4] > pancakes[8] && pancakes[4] > pancakes[9])
{
    cout << "Person 5 ate " << pancakes[4] << " pancakes" << endl;
}

else if(pancakes[5] > pancakes[0] && pancakes[5] > pancakes[2] && pancakes[5] > pancakes[3] && pancakes[5] > pancakes[4] && pancakes[5] > pancakes[1] && pancakes[5] > pancakes[6] && pancakes[5] > pancakes[7] && pancakes[5] > pancakes[8] && pancakes[5] > pancakes[9])
{
    cout << "Person 6 ate " << pancakes[5] << " pancakes" << endl;
}

else if(pancakes[6] > pancakes[0] && pancakes[6] > pancakes[2] && pancakes[6] > pancakes[3] && pancakes[6] > pancakes[4] && pancakes[6] > pancakes[5] && pancakes[6] > pancakes[1] && pancakes[6] > pancakes[7] && pancakes[6] > pancakes[8] && pancakes[6] > pancakes[9])
{
    cout << "Person 7 ate " << pancakes[6] << " pancakes" << endl;
}

else if(pancakes[7] > pancakes[0] && pancakes[7] > pancakes[2] && pancakes[7] > pancakes[3] && pancakes[7] > pancakes[4] && pancakes[7] > pancakes[5] && pancakes[7] > pancakes[6] && pancakes[7] > pancakes[1] && pancakes[7] > pancakes[8] && pancakes[7] > pancakes[9])
{
    cout << "Person 8 ate " << pancakes[7] << " pancakes" << endl;
}

else if(pancakes[8] > pancakes[0] && pancakes[8] >  pancakes[2] && pancakes[8] > pancakes[3] && pancakes[8] > pancakes[4] && pancakes[8] > pancakes[5] && pancakes[8] > pancakes[6] && pancakes[8] > pancakes[7] && pancakes[8] > pancakes[1] && pancakes[8] > pancakes[9])
{
    cout << "Person 9 ate " << pancakes[8] << " pancakes" << endl;
}

else if(pancakes[9] > pancakes[0] && pancakes[9] > pancakes[2] && pancakes[9] > pancakes[3] && pancakes[9] > pancakes[4] && pancakes[9] > pancakes[5] && pancakes[9] > pancakes[6] && pancakes[9] > pancakes[7] && pancakes[9] > pancakes[8] && pancakes[9] > pancakes[1])
{
    cout << "Person 10 ate " << pancakes[9] << " pancakes" << endl;
}

cout << "\n";
}

/**********************************************************************
* Displays the order in which person ate the most pancakes to the least
***********************************************************************/
void displayOrder(int pancakes[])
{
    for(int i = 9; i >= 0; i--)
    {
        for(int j = 0; j < 9; j++)
        {
            if(pancakes[j] > pancakes[j + 1])
            {
                int temp = pancakes[j + 1];

                pancakes[j + 1]= pancakes[j];

                pancakes[j]=temp;
            }
        }

    cout << "Person " << i + 1 << ": ate " << pancakes[i] << " pancake(s)" << endl;

   }

}

/**********************************************************************
* Runs the Entire Program
***********************************************************************/
int main()
{
    int pancakes[256];
    getPancakesEaten(pancakes);
    comparePancakesEaten(pancakes);
    displayOrder(pancakes);
}
</code>```

The problem I have running into is that when I try display the correct order the person associated with the number of pancakes is sometimes incorrect based on input for example.

```
Person 1: ate 12
Person 2: ate 22
Person 3: ate 3
Person 4: ate 4
Person 5: ate 5
Person 6: ate 6
Person 7: ate 7
Person 8: ate 8
Person 9: ate 9
Person 10: ate 10
Person 2 ate 22 pancakes
Person 10: ate 22 pancake(s)
Person 9: ate 12 pancake(s)
Person 8: ate 10 pancake(s)
Person 7: ate 9 pancake(s)
Person 6: ate 8 pancake(s)
Person 5: ate 7 pancake(s)
Person 4: ate 6 pancake(s)
Person 3: ate 5 pancake(s)
Person 2: ate 4 pancake(s)
Person 1: ate 3 pancake(s)
```

Why isn't value that I entered for "Person 2" showing at "Person 10" instead? Is it because of my for loop in my displayOrder function?

Body:
I'm working on some exercises from the Cplusplus.com website in order to improve my programming and to learn and relearn some material from a class I have taken this year and the problem below is what I am working and specifically the last bolded portion.

Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10)
  Once the data has been entered the program must analyze the data and output which person ate the most pancakes for breakfast.

Modify the program so that it outputs a number of pancakes eaten of all 10 people like for example..

Person 4: ate 10 pancakes

Person 3: ate 7 pancakes

Person 8: ate 4 pancakes

etc...

Here is what I have so far

#include <iostream>

using namespace std;

void getPancakesEaten(int pancakes[]);
void comparePancakesEaten(int pancakes[]);
void displayOrder(int pancakes[]);

/**********************************************************************
* Gets the amount of Pancakes eaten
***********************************************************************/
void getPancakesEaten(int pancakes[])
{

    for(int i = 0; i < 10; i++)
    {
        cout << "Person " << i + 1 << ": ate ";
        cin >> pancakes[i];
    }

    cout << endl;
}

/**********************************************************************
* Compares the amount of pancakes eaten with each person
***********************************************************************/
void comparePancakesEaten(int pancakes[])
{
    if(pancakes[0] > pancakes[1] && pancakes[0] > pancakes[2] && pancakes[0] >               pancakes[3] && pancakes[0] > pancakes[4] && pancakes[0] > pancakes[5] && pancakes[0] > pancakes[6] && pancakes[0] > pancakes[7] && pancakes[0] > pancakes[8] && pancakes[9])
{
    cout << "Person 1 ate " << pancakes[0] << " pancakes" << endl;
}

else if(pancakes[1] > pancakes[0] && pancakes[1] > pancakes[2] && pancakes[1] > pancakes[3] && pancakes[1] > pancakes[4] && pancakes[1] > pancakes[5] && pancakes[1] > pancakes[6] && pancakes[1] > pancakes[7] && pancakes[1] > pancakes[8] && pancakes[1] > pancakes[9])
{
    cout << "Person 2 ate " << pancakes[1] << " pancakes" << endl;
}

else if(pancakes[2] > pancakes[0] && pancakes[2] > pancakes[1] && pancakes[2] > pancakes[3] && pancakes[2] > pancakes[4] && pancakes[2] > pancakes[5] && pancakes[2] > pancakes[6] && pancakes[2] > pancakes[7] && pancakes[2] > pancakes[8] && pancakes[2] > pancakes[9])
{
    cout << "Person 3 ate " << pancakes[2] << " pancakes" << endl;
}

else if(pancakes[3] > pancakes[0] && pancakes[3] > pancakes[2] && pancakes[3] > pancakes[1] && pancakes[3] > pancakes[4] && pancakes[3] > pancakes[5] && pancakes[3] > pancakes[6] && pancakes[3] > pancakes[7] && pancakes[3] > pancakes[8] && pancakes[3] > pancakes[9])
{
    cout << "Person 4 ate " << pancakes[3] << " pancakes" << endl;
}

else if(pancakes[4] > pancakes[0] && pancakes[4] > pancakes[2] && pancakes[4] > pancakes[3] && pancakes[4] > pancakes[1] && pancakes[4] > pancakes[5] && pancakes[4] > pancakes[6] && pancakes[4] > pancakes[7] && pancakes[4] > pancakes[8] && pancakes[4] > pancakes[9])
{
    cout << "Person 5 ate " << pancakes[4] << " pancakes" << endl;
}

else if(pancakes[5] > pancakes[0] && pancakes[5] > pancakes[2] && pancakes[5] > pancakes[3] && pancakes[5] > pancakes[4] && pancakes[5] > pancakes[1] && pancakes[5] > pancakes[6] && pancakes[5] > pancakes[7] && pancakes[5] > pancakes[8] && pancakes[5] > pancakes[9])
{
    cout << "Person 6 ate " << pancakes[5] << " pancakes" << endl;
}

else if(pancakes[6] > pancakes[0] && pancakes[6] > pancakes[2] && pancakes[6] > pancakes[3] && pancakes[6] > pancakes[4] && pancakes[6] > pancakes[5] && pancakes[6] > pancakes[1] && pancakes[6] > pancakes[7] && pancakes[6] > pancakes[8] && pancakes[6] > pancakes[9])
{
    cout << "Person 7 ate " << pancakes[6] << " pancakes" << endl;
}

else if(pancakes[7] > pancakes[0] && pancakes[7] > pancakes[2] && pancakes[7] > pancakes[3] && pancakes[7] > pancakes[4] && pancakes[7] > pancakes[5] && pancakes[7] > pancakes[6] && pancakes[7] > pancakes[1] && pancakes[7] > pancakes[8] && pancakes[7] > pancakes[9])
{
    cout << "Person 8 ate " << pancakes[7] << " pancakes" << endl;
}

else if(pancakes[8] > pancakes[0] && pancakes[8] >  pancakes[2] && pancakes[8] > pancakes[3] && pancakes[8] > pancakes[4] && pancakes[8] > pancakes[5] && pancakes[8] > pancakes[6] && pancakes[8] > pancakes[7] && pancakes[8] > pancakes[1] && pancakes[8] > pancakes[9])
{
    cout << "Person 9 ate " << pancakes[8] << " pancakes" << endl;
}

else if(pancakes[9] > pancakes[0] && pancakes[9] > pancakes[2] && pancakes[9] > pancakes[3] && pancakes[9] > pancakes[4] && pancakes[9] > pancakes[5] && pancakes[9] > pancakes[6] && pancakes[9] > pancakes[7] && pancakes[9] > pancakes[8] && pancakes[9] > pancakes[1])
{
    cout << "Person 10 ate " << pancakes[9] << " pancakes" << endl;
}

cout << "\n";
}

/**********************************************************************
* Displays the order in which person ate the most pancakes to the least
***********************************************************************/
void displayOrder(int pancakes[])
{
    for(int i = 9; i >= 0; i--)
    {
        for(int j = 0; j < 9; j++)
        {
            if(pancakes[j] > pancakes[j + 1])
            {
                int temp = pancakes[j + 1];

                pancakes[j + 1]= pancakes[j];

                pancakes[j]=temp;
            }
        }

    cout << "Person " << i + 1 << ": ate " << pancakes[i] << " pancake(s)" << endl;

   }

}

/**********************************************************************
* Runs the Entire Program
***********************************************************************/
int main()
{
    int pancakes[256];
    getPancakesEaten(pancakes);
    comparePancakesEaten(pancakes);
    displayOrder(pancakes);
}

The problem I have running into is that when I try display the correct order the person associated with the number of pancakes is sometimes incorrect based on input for example.

Person 1: ate 12
Person 2: ate 22
Person 3: ate 3
Person 4: ate 4
Person 5: ate 5
Person 6: ate 6
Person 7: ate 7
Person 8: ate 8
Person 9: ate 9
Person 10: ate 10
Person 2 ate 22 pancakes
Person 10: ate 22 pancake(s)
Person 9: ate 12 pancake(s)
Person 8: ate 10 pancake(s)
Person 7: ate 9 pancake(s)
Person 6: ate 8 pancake(s)
Person 5: ate 7 pancake(s)
Person 4: ate 6 pancake(s)
Person 3: ate 5 pancake(s)
Person 2: ate 4 pancake(s)
Person 1: ate 3 pancake(s)

Why isn't value that I entered for "Person 2" showing at "Person 10" instead? Is it because of my for loop in my displayOrder function?

Body:
You need to sort your array before you then display it.  Try something more like this instead:

#include <iostream>
#include <algorithm>

using namespace std;

void getPancakesEaten(int pancakes[10]);
void displayOrder(int pancakes[10]);

/**********************************************************************
* Gets the amount of Pancakes eaten
***********************************************************************/
void getPancakesEaten(int pancakes[10])
{
    for(int i = 0; i < 10; i++)
    {
        cout << "Person " << i + 1 << ": ate ";
        cin >> pancakes[i];
    }

    cout << endl;
}

/**********************************************************************
* Displays the order in which person ate the most pancakes to the least
***********************************************************************/
void displayOrder(int pancakes[10])
{
    int order[10];
    for (int i = 0; i < 10; ++i)
        order[i] = i;

    sort(order, order+10, [&pancakes](int a, int b){ return pancakes[a] > pancakes[b]; });

    for(int i = 0; i < 10; ++i)
        cout << "Person " << order[i] + 1 << ": ate " << pancakes[order[i]] << " pancake(s)" << endl;
}

/**********************************************************************
* Runs the Entire Program
***********************************************************************/
int main()
{
    int pancakes[10];
    getPancakesEaten(pancakes);
    displayOrder(pancakes);
}

Live demo


问:
Why does key disappear from subclassed dict when iterating over `dict_keys`?
I ran across strange behavior in Python 3.6.3 when iterating over the keys of an object subclassed from dict. I already understand that the behavior of dict.keys() changed from Python 2 to Python 3 to return a dict_keys object so the shallow copy behavior seen is understandable. What I don't understand is why one of the elements in dict_keys can be found with an explicit search but doesn't appear when iterating over the dict_keys object.

Here's the MWE:

```<code>#!/usr/bin/env python

from __future__ import print_function

class chemdist(dict):
    def normalize_names(self, force_static=False):

        if force_static:
            raw_chems = tuple(self.keys())
        else:
            raw_chems = self.keys()

        print("raw_chems is " + repr(raw_chems))

        if 'Ar' in raw_chems:
            print("Found Argon!")

        for old_chem in raw_chems:
            print("Checking {:s}".format(old_chem))
            if old_chem.startswith('_'):
                new_chem = old_chem
            else:
                new_chem = '_' + old_chem

            if old_chem != new_chem:
                curr_keys = self.keys()
                if new_chem in curr_keys:
                    self[new_chem] += self[old_chem]
                else:
                    self[new_chem] = self[old_chem]

                del self[old_chem]

def main():
    h_dryair = {
        'N2' : 78.084,
        'O2' : 20.947,
        'Ar' :  0.934,
        'CO2' : 0.0350
    }

    print("Test 1: Not static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names()

    print("\n  Normalized:")
    print(cd_dryair)

    print("\n\nTest 2: Static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names(force_static=True)

    print("\n  Normalized:")
    print(cd_dryair)

main()
</code>```

And here are the results:

```<code>Test 1: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is dict_keys(['N2', 'O2', 'Ar', 'CO2'])
Found Argon!
Checking N2
Checking O2
Checking CO2
Checking _N2
Checking _O2
Checking _CO2

  Normalized:
{'Ar': 0.934, '_N2': 78.084, '_O2': 20.947, '_CO2': 0.035}

Test 2: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is ('N2', 'O2', 'Ar', 'CO2')
Found Argon!
Checking N2
Checking O2
Checking Ar
Checking CO2

  Normalized:
{'_N2': 78.084, '_O2': 20.947, '_Ar': 0.934, '_CO2': 0.035}
</code>```

In Test 1, the element 'Ar' is found by explicitly searching for it in raw_chems. However when iterating over raw_chems, the element 'Ar' never appears ("Checking Ar" never appears).

In Test 2, raw_chems is cast to a tuple and "Checking Ar" appears as expected.

Also, compare the final normalized object contents: in Test 1, the 'Ar' key has not been replaced with '_Ar' as it has in Test 2. 'Ar' is the only key in Test 1 that hasn't been prefixed with an underscore.

I have two guesses at the cause of this problem: dict_keys has some obvious-to-everyone-but-me behavior or some weirdness is happening because I'm subclassing dict. Possibly a combination of the two.

And before someone gratuitously tries to change the question I'm asking, the Big Picture problem I'm trying to solve is to rename the dict keys to a canonical form (HH, H2, and molecular hydrogen all represent the same thing). While that may be a more interesting issue for some to address, I'm asking about the disappearing key, so please focus on the x as stated instead of the y you imagine... :)

答: In python 3 dict.keys() is a view on the actual keys and changes, if the dictionary keys changes. You must not change the keys of a dictionary if you iterate over the keys.

Body:
I ran across strange behavior in Python 3.6.3 when iterating over the keys of an object subclassed from dict. I already understand that the behavior of dict.keys() changed from Python 2 to Python 3 to return a dict_keys object so the shallow copy behavior seen is understandable. What I don't understand is why one of the elements in dict_keys can be found with an explicit search but doesn't appear when iterating over the dict_keys object.

Here's the MWE:

#!/usr/bin/env python

from __future__ import print_function

class chemdist(dict):
    def normalize_names(self, force_static=False):

        if force_static:
            raw_chems = tuple(self.keys())
        else:
            raw_chems = self.keys()

        print("raw_chems is " + repr(raw_chems))

        if 'Ar' in raw_chems:
            print("Found Argon!")

        for old_chem in raw_chems:
            print("Checking {:s}".format(old_chem))
            if old_chem.startswith('_'):
                new_chem = old_chem
            else:
                new_chem = '_' + old_chem

            if old_chem != new_chem:
                curr_keys = self.keys()
                if new_chem in curr_keys:
                    self[new_chem] += self[old_chem]
                else:
                    self[new_chem] = self[old_chem]

                del self[old_chem]

def main():
    h_dryair = {
        'N2' : 78.084,
        'O2' : 20.947,
        'Ar' :  0.934,
        'CO2' : 0.0350
    }

    print("Test 1: Not static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names()

    print("\n  Normalized:")
    print(cd_dryair)

    print("\n\nTest 2: Static")
    cd_dryair = chemdist(h_dryair)

    print("  Unnormalized:")
    print(cd_dryair)

    print("\n  Normalizing:")
    cd_dryair.normalize_names(force_static=True)

    print("\n  Normalized:")
    print(cd_dryair)

main()

And here are the results:

Test 1: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is dict_keys(['N2', 'O2', 'Ar', 'CO2'])
Found Argon!
Checking N2
Checking O2
Checking CO2
Checking _N2
Checking _O2
Checking _CO2

  Normalized:
{'Ar': 0.934, '_N2': 78.084, '_O2': 20.947, '_CO2': 0.035}

Test 2: Not static
  Unnormalized:
{'N2': 78.084, 'O2': 20.947, 'Ar': 0.934, 'CO2': 0.035}

  Normalizing:
raw_chems is ('N2', 'O2', 'Ar', 'CO2')
Found Argon!
Checking N2
Checking O2
Checking Ar
Checking CO2

  Normalized:
{'_N2': 78.084, '_O2': 20.947, '_Ar': 0.934, '_CO2': 0.035}

In Test 1, the element 'Ar' is found by explicitly searching for it in raw_chems. However when iterating over raw_chems, the element 'Ar' never appears ("Checking Ar" never appears).

In Test 2, raw_chems is cast to a tuple and "Checking Ar" appears as expected.

Also, compare the final normalized object contents: in Test 1, the 'Ar' key has not been replaced with '_Ar' as it has in Test 2. 'Ar' is the only key in Test 1 that hasn't been prefixed with an underscore.

I have two guesses at the cause of this problem: dict_keys has some obvious-to-everyone-but-me behavior or some weirdness is happening because I'm subclassing dict. Possibly a combination of the two.

And before someone gratuitously tries to change the question I'm asking, the Big Picture problem I'm trying to solve is to rename the dict keys to a canonical form (HH, H2, and molecular hydrogen all represent the same thing). While that may be a more interesting issue for some to address, I'm asking about the disappearing key, so please focus on the x as stated instead of the y you imagine... :)


问:
How to implement a queue in a linked list in c?
I am given these structure declarations in order to implement a queue collection that uses a circular linked list.

```<code>typedef struct intnode {
int value;
struct intnode *next;
} intnode_t;

typedef struct {
intnode_t *rear;   // Points to the node at the tail of the
                   // queue's linked list
int size;          // The # of nodes in the queue's linked list
} intqueue_t;

intnode_t *intnode_construct(int value, intnode_t *next)
{
    intnode_t *p = malloc(sizeof(intnode_t));
    assert (p != NULL);
    p->value = value;
    p->next = next;
    return p;
}

/* Return a pointer to a new, empty queue.
 * Terminate (via assert) if memory for the queue cannot be allocated.
 */

intqueue_t *intqueue_construct(void)
{
intqueue_t *queue = malloc(sizeof(intqueue_t));
assert(queue != NULL);

    queue->rear = NULL;
    queue->size = 0;
    return queue;
}
</code>```

I'm trying to create a function that will enqueue at a specified value (append it to the rear of the queue), and I need to consider the two cases in which the queue is empty and when the queue has one or more elements. This is the code I have so far:

```<code>void intqueue_enqueue(intqueue_t *queue, int value)
{

    intnode_t *p = intnode_construct(value, NULL);

    if(queue->rear->next == NULL) {
    //the queue is empty
    queue->rear->next =p;
}     else {
    //the queue is not empty
    queue->rear=p;
}
queue->rear=p;
queue->size++;
}
</code>```

This code gives me a runtime error so I'm not sure whats wrong. In the code, I'm assuming queue->rear->next is the front, however I think this is where the problem might be. All help is greatly appreciated. Thanks!

UPDATE--

I've tried to rework the code and got this:

```<code>void intqueue_enqueue(intqueue_t *queue, int value)
{
assert(queue!=NULL);

  intnode_t *p = intnode_construct(value,NULL);

 if (queue->size==0){

    queue->rear=p;
    queue->size++;
    queue->rear->next=p;
    free(p);
    }
else {
    p->next = queue->rear;
    queue->rear=p;
    queue->size++;
    free(p);

    }
}
</code>```

This works only when it is empty but not when it is not empty.

答:
Circular Queue in Linked List

Your code is too large to read out, So here what I use to implement Circular Queue:

#include
    using namespace std;

```<code>// Structure of a Node
struct Node
{
    int data;
    struct Node* link;
};

struct Queue
{
    struct Node *front, *rear;
};

// Function to create Circular queue
void enQueue(Queue *q, int value)
{
    struct Node *temp = new Node;
    temp->data = value;
    if (q->front == NULL)
        q->front = temp;
    else
        q->rear->link = temp;

    q->rear = temp;
    q->rear->link = q->front;
}

// Function to delete element from Circular Queue
int deQueue(Queue *q)
{
    if (q->front == NULL)
    {
        printf ("Queue is empty");
        return INT_MIN;
    }

    // If this is the last node to be deleted
    int value; // Value to be dequeued
    if (q->front == q->rear)
    {
        value = q->front->data;
        free(q->front);
        q->front = NULL;
        q->rear = NULL;
    }
    else  // There are more than one nodes
    {
        struct Node *temp = q->front;
        value = temp->data;
        q->front = q->front->link;
        q->rear->link= q->front;
        free(temp);
    }

    return value ;
}

// Function displaying the elements of Circular Queue
void displayQueue(struct Queue *q)
{
    struct Node *temp = q->front;
    printf("\nElements in Circular Queue are: ");
    while (temp->link != q->front)
    {
        printf("%d ", temp->data);
        temp = temp->link;
    }
    printf("%d", temp->data);
}

/* Driver of the program */
int main()
{
    // Create a queue and initialize front and rear
    Queue *q = new Queue;
    q->front = q->rear = NULL;

    // Inserting elements in Circular Queue
    enQueue(q, 14);
    enQueue(q, 22);
    enQueue(q, 6);

    // Display elements present in Circular Queue
    displayQueue(q);

    // Deleting elements from Circular Queue
    printf("\nDeleted value = %d", deQueue(q));
    printf("\nDeleted value = %d", deQueue(q));

    // Remaining elements in Circular Queue
    displayQueue(q);

    enQueue(q, 9);
    enQueue(q, 20);
    displayQueue(q);

    return 0;
}
</code>```

Body:
I am given these structure declarations in order to implement a queue collection that uses a circular linked list.

typedef struct intnode {
int value;
struct intnode *next;
} intnode_t;

typedef struct {
intnode_t *rear;   // Points to the node at the tail of the
                   // queue's linked list
int size;          // The # of nodes in the queue's linked list
} intqueue_t;

intnode_t *intnode_construct(int value, intnode_t *next)
{
    intnode_t *p = malloc(sizeof(intnode_t));
    assert (p != NULL);
    p->value = value;
    p->next = next;
    return p;
}

/* Return a pointer to a new, empty queue.
 * Terminate (via assert) if memory for the queue cannot be allocated.
 */

intqueue_t *intqueue_construct(void)
{
intqueue_t *queue = malloc(sizeof(intqueue_t));
assert(queue != NULL);

    queue->rear = NULL;
    queue->size = 0;
    return queue;
}

I'm trying to create a function that will enqueue at a specified value (append it to the rear of the queue), and I need to consider the two cases in which the queue is empty and when the queue has one or more elements. This is the code I have so far:

void intqueue_enqueue(intqueue_t *queue, int value)
{

    intnode_t *p = intnode_construct(value, NULL);

    if(queue->rear->next == NULL) {
    //the queue is empty
    queue->rear->next =p;
}     else {
    //the queue is not empty
    queue->rear=p;
}
queue->rear=p;
queue->size++;
}

This code gives me a runtime error so I'm not sure whats wrong. In the code, I'm assuming queue->rear->next is the front, however I think this is where the problem might be. All help is greatly appreciated. Thanks!

UPDATE--

I've tried to rework the code and got this:

void intqueue_enqueue(intqueue_t *queue, int value)
{
assert(queue!=NULL);

  intnode_t *p = intnode_construct(value,NULL);

 if (queue->size==0){

    queue->rear=p;
    queue->size++;
    queue->rear->next=p;
    free(p);
    }
else {
    p->next = queue->rear;
    queue->rear=p;
    queue->size++;
    free(p);

    }
}

This works only when it is empty but not when it is not empty.

Body:
Circular Queue in Linked List

Your code is too large to read out, So here what I use to implement Circular Queue:

#include
    using namespace std;

// Structure of a Node
struct Node
{
    int data;
    struct Node* link;
};

struct Queue
{
    struct Node *front, *rear;
};

// Function to create Circular queue
void enQueue(Queue *q, int value)
{
    struct Node *temp = new Node;
    temp->data = value;
    if (q->front == NULL)
        q->front = temp;
    else
        q->rear->link = temp;

    q->rear = temp;
    q->rear->link = q->front;
}

// Function to delete element from Circular Queue
int deQueue(Queue *q)
{
    if (q->front == NULL)
    {
        printf ("Queue is empty");
        return INT_MIN;
    }

    // If this is the last node to be deleted
    int value; // Value to be dequeued
    if (q->front == q->rear)
    {
        value = q->front->data;
        free(q->front);
        q->front = NULL;
        q->rear = NULL;
    }
    else  // There are more than one nodes
    {
        struct Node *temp = q->front;
        value = temp->data;
        q->front = q->front->link;
        q->rear->link= q->front;
        free(temp);
    }

    return value ;
}

// Function displaying the elements of Circular Queue
void displayQueue(struct Queue *q)
{
    struct Node *temp = q->front;
    printf("\nElements in Circular Queue are: ");
    while (temp->link != q->front)
    {
        printf("%d ", temp->data);
        temp = temp->link;
    }
    printf("%d", temp->data);
}

/* Driver of the program */
int main()
{
    // Create a queue and initialize front and rear
    Queue *q = new Queue;
    q->front = q->rear = NULL;

    // Inserting elements in Circular Queue
    enQueue(q, 14);
    enQueue(q, 22);
    enQueue(q, 6);

    // Display elements present in Circular Queue
    displayQueue(q);

    // Deleting elements from Circular Queue
    printf("\nDeleted value = %d", deQueue(q));
    printf("\nDeleted value = %d", deQueue(q));

    // Remaining elements in Circular Queue
    displayQueue(q);

    enQueue(q, 9);
    enQueue(q, 20);
    displayQueue(q);

    return 0;
}


问:
Please give some approach to achieve the data set for the following data set
In my table there is 5 distinct event 1,2,3,4,5. In attendee column there are attendees who attained these events. and in isThisuserHost column there is 0 and 1 flag. 1 for host who host the event and 1 for attendee who attain the event.I need to show the event where host is 2 and attendee is 4. In this table we can see that event 1,2,and 4 is those rows where host is 2 and attendee is 4. How to extract the result using a single query?

答:
Try the following query:</p>

```<code>select distinct eventid
from mytable m1
where 2 in (select attendee
            from mytable m2
            where m2.eventid = m1.eventid
            and isTheuserHost = 1
           )
and   4 in (select attendee
            from mytable m3
            where m3.eventid = m1.eventid
            and isTheuserHost = 0
           )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try the following query:

select distinct eventid
from mytable m1
where 2 in (select attendee
            from mytable m2
            where m2.eventid = m1.eventid
            and isTheuserHost = 1
           )
and   4 in (select attendee
            from mytable m3
            where m3.eventid = m1.eventid
            and isTheuserHost = 0
           )