问:
Apache Beam Spark Runner Issues
We are trying to submit a Spark job through YARN with the following command:

```<code>spark-submit --conf spark.yarn.stagingDir=/path/to/stage  --verbose --class com.my.class --jars /path/to/jar1,path/to/jar2 /path/to/main/jar/application.jar
</code>```

The application is being populated in the YARN scheduler however it never appears to start the Application Master container.  The trace is:

```<code>17/12/04 11:21:32 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
17/12/04 11:27:16 ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: Yarn application has already ended! It might have been killed or unable to launch application master.
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.waitForApplication(YarnClientSchedulerBackend.scala:85)
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:62)
    at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:156)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:509)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.createSparkContext(SparkContextFactory.java:98)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.getSparkContext(SparkContextFactory.java:68)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:197)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:86)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)
    at com.my.class.main(myclass.java:202)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
17/12/04 11:27:16 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to request executors before the AM has registered!
17/12/04 11:27:16 WARN MetricsSystem: Stopping a MetricsSystem that is not running
Exception in thread "main" org.apache.spark.SparkException: Yarn application has already ended! It might have been killed or unable to launch application master.
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.waitForApplication(YarnClientSchedulerBackend.scala:85)
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:62)
    at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:156)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:509)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.createSparkContext(SparkContextFactory.java:98)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.getSparkContext(SparkContextFactory.java:68)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:197)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:86)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)
    at at com.my.class.main(myclass.java:202)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

We are able to run the sample Spark Pi job to completion without errors.

Version:

```<code>$ spark-submit --version
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.1.0-mapr-1703
      /_/

Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_101
</code>```

We think the issue may be with how we are setting up our pipeline:

```<code>    PipelineOptions options = PipelineOptionsFactory.create();
    options.setRunner(SparkRunner.class);
    Pipeline p = Pipeline.create(options);
</code>```

We run our Pipeline with:

```<code>p.run(options);
</code>```

The pipeline was running successfully with the DirectRunner.

We made sure to include beam-runners-spark as a Maven Dependency.

答: Apache Beam only supports Apache Spark 1.6.3 currently.  We are currently using Apache Spark 2.1 so it is not working.</p>

Title: Apache Beam Spark Runner Issues

Body:
We are trying to submit a Spark job through YARN with the following command:

spark-submit --conf spark.yarn.stagingDir=/path/to/stage  --verbose --class com.my.class --jars /path/to/jar1,path/to/jar2 /path/to/main/jar/application.jar

The application is being populated in the YARN scheduler however it never appears to start the Application Master container.  The trace is:

17/12/04 11:21:32 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
17/12/04 11:27:16 ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: Yarn application has already ended! It might have been killed or unable to launch application master.
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.waitForApplication(YarnClientSchedulerBackend.scala:85)
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:62)
    at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:156)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:509)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.createSparkContext(SparkContextFactory.java:98)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.getSparkContext(SparkContextFactory.java:68)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:197)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:86)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)
    at com.my.class.main(myclass.java:202)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
17/12/04 11:27:16 WARN YarnSchedulerBackend$YarnSchedulerEndpoint: Attempted to request executors before the AM has registered!
17/12/04 11:27:16 WARN MetricsSystem: Stopping a MetricsSystem that is not running
Exception in thread "main" org.apache.spark.SparkException: Yarn application has already ended! It might have been killed or unable to launch application master.
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.waitForApplication(YarnClientSchedulerBackend.scala:85)
    at org.apache.spark.scheduler.cluster.YarnClientSchedulerBackend.start(YarnClientSchedulerBackend.scala:62)
    at org.apache.spark.scheduler.TaskSchedulerImpl.start(TaskSchedulerImpl.scala:156)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:509)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.createSparkContext(SparkContextFactory.java:98)
    at org.apache.beam.runners.spark.translation.SparkContextFactory.getSparkContext(SparkContextFactory.java:68)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:197)
    at org.apache.beam.runners.spark.SparkRunner.run(SparkRunner.java:86)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)
    at at com.my.class.main(myclass.java:202)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

We are able to run the sample Spark Pi job to completion without errors.

Version:

$ spark-submit --version
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.1.0-mapr-1703
      /_/

Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_101

We think the issue may be with how we are setting up our pipeline:

    PipelineOptions options = PipelineOptionsFactory.create();
    options.setRunner(SparkRunner.class);
    Pipeline p = Pipeline.create(options);

We run our Pipeline with:

p.run(options);

The pipeline was running successfully with the DirectRunner.

We made sure to include beam-runners-spark as a Maven Dependency.


来源: stackexchange

问:
Troubleshooting .NET Binding Redirects in Publisher Policy Files
How can you trouble-shoot exactly why an Assembly Binding Redirect from a Publisher Policy File is not being followed? (Fusion is showing me that it's NOT, but not WHY)

Background

Microsoft SharePoint makes extensive use of assembly binding redirects between versions e.g. v12.0 (SharePoint 2007) > v14.0 (2010)

Suddenly on one particular server, this has stopped working. (usual Windows updates, but so have other servers, no other changes of note I think). Still working on supposedly identical machines.

Digging out Fusion Log Viewer shows where this IS working (cut down for brevity)

```<code>*** Assembly Binder Log Entry ***
...
The operation was successful.
...
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Publisher policy file is found at C:\WINDOWS\assembly\GAC_MSIL\Policy.12.0.Microsoft.SharePoint\14.0.0.0__71e9bce111e9429c\Policy.12.0.Microsoft.SharePoint.config.
LOG: Publisher policy file redirect is found: 12.0.0.0 redirected to 14.0.0.0.
LOG: Post-policy reference: Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL
</code>```

On the server that IS NOT working

```<code>*** Assembly Binder Log Entry ***
...
The operation failed.
...
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Post-policy reference: Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c
LOG: GAC Lookup was unsuccessful.
</code>```

Both servers have the policy file in the GAC as shown with gacutil -l

```<code>Policy.12.0.Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL
</code>```

答:
Not answering the question as such which was "How to troubleshoot [further than the info Fusion gives you]" but this is what I did to solve this particular problem.

Found a copy of the Publisher Policy File assembly at

```<code>C:\Program Files\Common Files\microsoft shared\Web Server Extensions\14\Policy\Policy.12.0.Microsoft.SharePoint.dll
</code>```

Removed it from the GAC with

```<code>gacutil /u Policy.12.0.Microsoft.SharePoint
</code>```

Reinstalled with

```<code>gacutil /i Policy.12.0.Microsoft.SharePoint
</code>```

Works immediately.

No idea what broke it in the first place though.

ContentLicense: CC BY-SA 3.0

Body:
How can you trouble-shoot exactly why an Assembly Binding Redirect from a Publisher Policy File is not being followed? (Fusion is showing me that it's NOT, but not WHY)

Background

Microsoft SharePoint makes extensive use of assembly binding redirects between versions e.g. v12.0 (SharePoint 2007) > v14.0 (2010)

Suddenly on one particular server, this has stopped working. (usual Windows updates, but so have other servers, no other changes of note I think). Still working on supposedly identical machines.

Digging out Fusion Log Viewer shows where this IS working (cut down for brevity)

*** Assembly Binder Log Entry ***
...
The operation was successful.
...
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Publisher policy file is found at C:\WINDOWS\assembly\GAC_MSIL\Policy.12.0.Microsoft.SharePoint\14.0.0.0__71e9bce111e9429c\Policy.12.0.Microsoft.SharePoint.config.
LOG: Publisher policy file redirect is found: 12.0.0.0 redirected to 14.0.0.0.
LOG: Post-policy reference: Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL

On the server that IS NOT working

*** Assembly Binder Log Entry ***
...
The operation failed.
...
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Post-policy reference: Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c
LOG: GAC Lookup was unsuccessful.

Both servers have the policy file in the GAC as shown with gacutil -l

Policy.12.0.Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL

Body:
Not answering the question as such which was "How to troubleshoot [further than the info Fusion gives you]" but this is what I did to solve this particular problem.

Found a copy of the Publisher Policy File assembly at

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\14\Policy\Policy.12.0.Microsoft.SharePoint.dll

Removed it from the GAC with

gacutil /u Policy.12.0.Microsoft.SharePoint

Reinstalled with

gacutil /i Policy.12.0.Microsoft.SharePoint

Works immediately.

No idea what broke it in the first place though.


问:
I've got an error when running 'ng new angular-src' which 'You cannot use the new command inside an Angular CLI project.'
package.json

```<code>{
 "name": "meanauthapp",
  "version": "1.0.0",
  "description": "mean stack application",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app"
  },
  "dependencies": {
    "express": "*",
    "mongoose": "*",
    "bcryptjs": "*",
    "cors": "*",
    "jsonwebtoken": "*",
    "body-parser": "*",
    "passport": "*",
    "passport-jwt": "*"
  },
  "author": "ip",
  "license": "ISC",
  "devDependencies": {
    "@angular/cli": "^1.5.5"
  }
}
</code>```

答: I've solved this problem by deleting 'package.json' file and 'node_module' folder from the application folder.</p>

Body:
package.json

{
 "name": "meanauthapp",
  "version": "1.0.0",
  "description": "mean stack application",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app"
  },
  "dependencies": {
    "express": "*",
    "mongoose": "*",
    "bcryptjs": "*",
    "cors": "*",
    "jsonwebtoken": "*",
    "body-parser": "*",
    "passport": "*",
    "passport-jwt": "*"
  },
  "author": "ip",
  "license": "ISC",
  "devDependencies": {
    "@angular/cli": "^1.5.5"
  }
}


问:
Bubble sort in c linked list

I need to do is read in an input file into a linked list. Part of the file is:

NameA, 25

NameB, 33

NameC, 23

NameD, 39

And after i need to sort by the number (bubble sort) and write it to another file.

Here is what i have:

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

struct node{
    char name[20];
    int number;
    struct node *next;
    struct node *prev;
}*head;

int main(void) {

    struct node *temp;
    temp = malloc(sizeof(struct node));
    temp->next = NULL;
    head = temp;

    FILE *ifp;
    char fnamer[100] = "";
    char line[128];
//    printf("\n\nPlease Enter the Full Path of the file: \n");
//    scanf("%s",&fnamer);

    ifp = fopen("mintaadatok.txt", "r");
    if (ifp == NULL) {
        printf("\n%s\" File NOT FOUND!", fnamer);
        exit(1);
    }

    int c = 0;

    char buffer[1024];
    memset(buffer, 0, 1024);
    while (c < 15) {
        fgets(buffer, 1024, ifp);
        sscanf(buffer, "%19[^,], %d", temp->name, &temp->number);
        printf("%d %s %d\n", c, temp->name, temp->number);
        temp->next = malloc(sizeof(struct node));
        temp = temp->next;
        temp->next = NULL;
        c++;
    }

    int i,step;
    for (temp = head; temp; temp = temp->next) {
        printf("%s", temp->name);
        printf("%d\n", temp->number);
        for(step=0;step<10-1;++step)
            for(i=0;i<10-step-1;++i)
            {
                temp->next = malloc(sizeof(struct node));
                if(temp->number>temp->next)
                {
                    temp=temp->number;
                    temp->number=temp->next;
                    temp->next=temp;
                }
            }
    }
    printf("In ascending order: ");
}
```

Can you help me to sort these data?

答:
We beginners should help each other.:)

I did not look through all your code. However it is obviously incorrect for example due to the incorrect order of allocations of nodes in this loop

```<code>while (c < 15) {
    fgets(buffer, 1024, ifp);
    sscanf(buffer, "%19[^,], %d", temp->name, &temp->number);
    printf("%d %s %d\n", c, temp->name, temp->number);
    temp->next = malloc(sizeof(struct node));
    temp = temp->next;
    temp->next = NULL;
    c++;
}
</code>```

So the last node will have data members with indeterminate values except the data member next.

I am trying to answer your question how to write a bubble sort function for a singly-linked list.

To write a bubble sort function for a singly-linked list is not an easy task for such beginners as you and me. For example you need to write correctly a swap function for nodes of the list.

Here you are.

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

struct node
{
    char name[20];
    int id;
    struct node *next;
};

int push_back( struct node **head, const char *name, int id )
{
    struct node *tmp = malloc( sizeof( struct node ) );
    int success = tmp != NULL;

    if ( success )
    {
        while ( *head != NULL ) head = &( *head )->next;

        strcpy( tmp->name, name );
        tmp->id = id;
        tmp->next = NULL;

        *head = tmp;
    }

    return success;
}

void display( struct node **head )
{
    for ( struct node *current = *head; current != NULL; current = current->next )
    {
        printf( "{ %s, %d } ", current->name, current->id );
    }
}

void swap( struct node **current )
{
    struct node *tmp = ( *current )->next->next;
    ( *current )->next->next = *current;
    *current = ( *current )->next;
    ( *current )->next->next = tmp;
}

void bubble_sort( struct node **head, int cmp( const void *, const void * ) )
{
    if ( *head != NULL )
    {
        for ( struct node *last = NULL, *swapped = NULL; ( *head )->next != last; last = swapped )
        {
            swapped = ( *head )->next;

            for ( struct node **first = head; ( *first )->next != last; first = &( *first )->next )
            {
                if ( cmp( ( *first )->next, *first ) < 0 )
                {
                    swap( first );
                    swapped = ( *first )->next;
                }
            }
        }
    }
}

int cmp_id( const void *a, const void *b )
{
    const struct node *left  = a;
    const struct node *right = b;

    return ( right->id < left->id ) - ( left->id < right->id );
}

int cmp_name( const void *a, const void *b )
{
    const struct node *left  = a;
    const struct node *right = b;

    return strcmp( left->name, right->name );
}

int main(void)
{
    struct node *head = NULL;

    push_back( &head, "NameA", 25 );
    push_back( &head, "NameB", 33 );
    push_back( &head, "NameC", 23 );
    push_back( &head, "NameD", 39 );

    display( &head );
    putchar( '\n' );

    bubble_sort( &head, cmp_id );

    display( &head );
    putchar( '\n' );

    bubble_sort( &head, cmp_name );

    display( &head );
    putchar( '\n' );

    return 0;
}
</code>```

The program output is

```<code>{ NameA, 25 } { NameB, 33 } { NameC, 23 } { NameD, 39 }
{ NameC, 23 } { NameA, 25 } { NameB, 33 } { NameD, 39 }
{ NameA, 25 } { NameB, 33 } { NameC, 23 } { NameD, 39 }
</code>```

In the demonstrative program at first the list is sorted by IDs and then by names.

Thus all you need now is to build correctly the list from data in the used file.

Title: Bubble sort in c linked list

Body:
I need to do is read in an input file into a linked list. Part of the file is:

NameA, 25

NameB, 33

NameC, 23

NameD, 39

And after i need to sort by the number (bubble sort) and write it to another file.

Here is what i have:

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

struct node{
    char name[20];
    int number;
    struct node *next;
    struct node *prev;
}*head;

int main(void) {

    struct node *temp;
    temp = malloc(sizeof(struct node));
    temp->next = NULL;
    head = temp;

    FILE *ifp;
    char fnamer[100] = "";
    char line[128];
//    printf("\n\nPlease Enter the Full Path of the file: \n");
//    scanf("%s",&fnamer);

    ifp = fopen("mintaadatok.txt", "r");
    if (ifp == NULL) {
        printf("\n%s\" File NOT FOUND!", fnamer);
        exit(1);
    }

    int c = 0;

    char buffer[1024];
    memset(buffer, 0, 1024);
    while (c < 15) {
        fgets(buffer, 1024, ifp);
        sscanf(buffer, "%19[^,], %d", temp->name, &temp->number);
        printf("%d %s %d\n", c, temp->name, temp->number);
        temp->next = malloc(sizeof(struct node));
        temp = temp->next;
        temp->next = NULL;
        c++;
    }

    int i,step;
    for (temp = head; temp; temp = temp->next) {
        printf("%s", temp->name);
        printf("%d\n", temp->number);
        for(step=0;step<10-1;++step)
            for(i=0;i<10-step-1;++i)
            {
                temp->next = malloc(sizeof(struct node));
                if(temp->number>temp->next)
                {
                    temp=temp->number;
                    temp->number=temp->next;
                    temp->next=temp;
                }
            }
    }
    printf("In ascending order: ");
}

Can you help me to sort these data?

Body:
We beginners should help each other.:)

I did not look through all your code. However it is obviously incorrect for example due to the incorrect order of allocations of nodes in this loop

while (c < 15) {
    fgets(buffer, 1024, ifp);
    sscanf(buffer, "%19[^,], %d", temp->name, &temp->number);
    printf("%d %s %d\n", c, temp->name, temp->number);
    temp->next = malloc(sizeof(struct node));
    temp = temp->next;
    temp->next = NULL;
    c++;
}

So the last node will have data members with indeterminate values except the data member next.

I am trying to answer your question how to write a bubble sort function for a singly-linked list.

To write a bubble sort function for a singly-linked list is not an easy task for such beginners as you and me. For example you need to write correctly a swap function for nodes of the list.

Here you are.

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

struct node
{
    char name[20];
    int id;
    struct node *next;
};

int push_back( struct node **head, const char *name, int id )
{
    struct node *tmp = malloc( sizeof( struct node ) );
    int success = tmp != NULL;

    if ( success )
    {
        while ( *head != NULL ) head = &( *head )->next;

        strcpy( tmp->name, name );
        tmp->id = id;
        tmp->next = NULL;

        *head = tmp;
    }

    return success;
}

void display( struct node **head )
{
    for ( struct node *current = *head; current != NULL; current = current->next )
    {
        printf( "{ %s, %d } ", current->name, current->id );
    }
}

void swap( struct node **current )
{
    struct node *tmp = ( *current )->next->next;
    ( *current )->next->next = *current;
    *current = ( *current )->next;
    ( *current )->next->next = tmp;
}

void bubble_sort( struct node **head, int cmp( const void *, const void * ) )
{
    if ( *head != NULL )
    {
        for ( struct node *last = NULL, *swapped = NULL; ( *head )->next != last; last = swapped )
        {
            swapped = ( *head )->next;

            for ( struct node **first = head; ( *first )->next != last; first = &( *first )->next )
            {
                if ( cmp( ( *first )->next, *first ) < 0 )
                {
                    swap( first );
                    swapped = ( *first )->next;
                }
            }
        }
    }
}

int cmp_id( const void *a, const void *b )
{
    const struct node *left  = a;
    const struct node *right = b;

    return ( right->id < left->id ) - ( left->id < right->id );
}

int cmp_name( const void *a, const void *b )
{
    const struct node *left  = a;
    const struct node *right = b;

    return strcmp( left->name, right->name );
}

int main(void)
{
    struct node *head = NULL;

    push_back( &head, "NameA", 25 );
    push_back( &head, "NameB", 33 );
    push_back( &head, "NameC", 23 );
    push_back( &head, "NameD", 39 );

    display( &head );
    putchar( '\n' );

    bubble_sort( &head, cmp_id );

    display( &head );
    putchar( '\n' );

    bubble_sort( &head, cmp_name );

    display( &head );
    putchar( '\n' );

    return 0;
}

The program output is

{ NameA, 25 } { NameB, 33 } { NameC, 23 } { NameD, 39 }
{ NameC, 23 } { NameA, 25 } { NameB, 33 } { NameD, 39 }
{ NameA, 25 } { NameB, 33 } { NameC, 23 } { NameD, 39 }

In the demonstrative program at first the list is sorted by IDs and then by names.

Thus all you need now is to build correctly the list from data in the used file.


问:
Generating new random number in python?
So i'm trying to create this really really simple game in python where the person types a number and if it matches the number that the computer generated the user is prompted with a message saying it got the right number and if its wrong a message saying its wrong, now I cant quite figure it out what I did wrong here because when I run this, I try different numbers multiple times and it always displays me the message that I didnt guess the right number, could anyone tell me what I am doing wrong here since I have no idea what the problem is?

```<code>import random

number = random.randint(0,10)
user_number = input()

while user_number != number:
  if user_number == number:
    print("GREAT! You guessed the right number! :)")
  else:
    print("AWW! You guessed the wrong number, try again! :)")
  input()
</code>```

EDIT I have a problem, how would I make my script generate a different number everytime the user inputs something, because what I have right now generates a number and that number never changes (btw thanks to Anton vBR for this updates version that I tweaked a bit):

```<code>import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(0,10)]
random = 2

while random > 1:
while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
if user_number == number:
    print("GREAT! You guessed the right number! :)")
else:
    print("AWW! You guessed the wrong number, try again! :)")
</code>```

答:
It will never say you are correct because the while loop says that as long as the number you input is different from the random number, it does the if loop.
Deleting the while loop should be fine.
If you want to keep it though you cold turn it into a function.</p>

Title: Generating new random number in python?

Body:
So i'm trying to create this really really simple game in python where the person types a number and if it matches the number that the computer generated the user is prompted with a message saying it got the right number and if its wrong a message saying its wrong, now I cant quite figure it out what I did wrong here because when I run this, I try different numbers multiple times and it always displays me the message that I didnt guess the right number, could anyone tell me what I am doing wrong here since I have no idea what the problem is?

import random

number = random.randint(0,10)
user_number = input()

while user_number != number:
  if user_number == number:
    print("GREAT! You guessed the right number! :)")
  else:
    print("AWW! You guessed the wrong number, try again! :)")
  input()

EDIT I have a problem, how would I make my script generate a different number everytime the user inputs something, because what I have right now generates a number and that number never changes (btw thanks to Anton vBR for this updates version that I tweaked a bit):

import random

number = random.randint(0,10)
user_number = None
valid_num = [str(i) for i in range(0,10)]
random = 2

while random > 1:
while True:
    user_number = input("Enter a number between 1-10: ")
    if user_number in valid_num:
        user_number = int(user_number)
        break
    else:
        print("Not valid!")
if user_number == number:
    print("GREAT! You guessed the right number! :)")
else:
    print("AWW! You guessed the wrong number, try again! :)")


问:
How to know that fitToView() has finished completely
I want to know that fitToView() finished completely.

Some program procedures do not work after fitToView() without setTimeout().
For example, the following code not work.

```<code>const dbid = [1141]
this.viewer.select(dbid)
this.viewer.fitToView(dbid, viewer.model)
zoom() //This will not work

//code from:
function zoom (){
    var nav = viewer.navigation
    var pos = nav.getPosition()
    var target = nav.getTarget()
    var viewdir = new THREE.Vector3()
    viewdir.subVectors (pos, target).normalize()
    // zooms out by 100 along the view direction
    viewdir.multiplyScalar (1000)
    pos.add(viewdir)
    nav.setPosition(pos)
}
</code>```

The following code work well.

```<code>this.viewer.fitToView(dbid, viewer.model)
setTimeout(function(){
    zoom() //This will work fine
}, 2000)
</code>```

However, I don't want to use the setTimeout as much as possible.

Is there a way to know that fitToView () is finished completely?

答:
If you use version 3.2.1 of the viewer a new event Autodesk.Viewing.CAMERA_TRANSITION_COMPLETED, it will be fired while following transitions are finished:

Go Home transition
Focus / Fit to View transition
Restore State transition
Named Views transition
Any other camera transitions

// Hook the event

```<code>viewer.addEventListener(Autodesk.Viewing.CAMERA_TRANSITION_COMPLETED, function(){
console.log('camera is no longer moving');
</code>```

});

// Trigger an action that will move the camera and fire the event

```<code>viewer.fitToView();
</code>```

You can see more about the Viewer Version changes here.
https://developer.autodesk.com/en/docs/viewer/v2/overview/changelog/3.2.1/

Body:
I want to know that fitToView() finished completely.

Some program procedures do not work after fitToView() without setTimeout().
For example, the following code not work.

const dbid = [1141]
this.viewer.select(dbid)
this.viewer.fitToView(dbid, viewer.model)
zoom() //This will not work

//code from:
function zoom (){
    var nav = viewer.navigation
    var pos = nav.getPosition()
    var target = nav.getTarget()
    var viewdir = new THREE.Vector3()
    viewdir.subVectors (pos, target).normalize()
    // zooms out by 100 along the view direction
    viewdir.multiplyScalar (1000)
    pos.add(viewdir)
    nav.setPosition(pos)
}

The following code work well.

this.viewer.fitToView(dbid, viewer.model)
setTimeout(function(){
    zoom() //This will work fine
}, 2000)

However, I don't want to use the setTimeout as much as possible.

Is there a way to know that fitToView () is finished completely?

Body:
If you use version 3.2.1 of the viewer a new event Autodesk.Viewing.CAMERA_TRANSITION_COMPLETED, it will be fired while following transitions are finished:

Go Home transition
Focus / Fit to View transition
Restore State transition
Named Views transition
Any other camera transitions

// Hook the event

viewer.addEventListener(Autodesk.Viewing.CAMERA_TRANSITION_COMPLETED, function(){
console.log('camera is no longer moving');

});

// Trigger an action that will move the camera and fire the event

viewer.fitToView();

You can see more about the Viewer Version changes here.
https://developer.autodesk.com/en/docs/viewer/v2/overview/changelog/3.2.1/


问:
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?

I made this application to send out a number of SMS messages from my phone, but how do I change it to send one at a time?

I am trying to make this send a SMS message and wait for the reply code to get back before sending the next one:

```<code>import android.telephony.gsm.SmsManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.util.Log;
import android.widget.Button;

import java.io.*;
import android.util.LogPrinter;

import java.io.*;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
import android.os.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;
import java.io.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

public class JSSMS extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(JSSMS.this, "Starting SMS", Toast.LENGTH_LONG)
                        .show();

                String message = "Hello This Is John, Please save my new number";
                String number;
                try {
                    BufferedReader buffreader = new BufferedReader(
                            new FileReader(Environment
                                    .getExternalStorageDirectory().toString()
                                    + "/numbers.txt"));
                    int i = 0;
                    while ((number = buffreader.readLine()) != null) {
                        Toast.makeText(JSSMS.this, "Sending text to:" + number,
                                Toast.LENGTH_SHORT).show();
                        sendSMS(number, message);
                    }

                    buffreader.close();
                } catch (java.io.FileNotFoundException e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();

                } catch (Exception e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();
                }

                Toast.makeText(JSSMS.this, "DONE!!", Toast.LENGTH_LONG).show();
            }
        });
    }

    // ---Sends an SMS message to another device.---
    private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

        // ---When the SMS has been sent---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));

        // ---When the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }
}
</code>```

答:
Look at the sendSms() method in this class.

When you call sendTextMessage(), you can pass a "sent" and a "delivered" intent. Target these intents back to your own application. You can have a callback so to speak when the SMS is sent or delivered.

If you look at the AndroidManifest.xml file in that same project as the references source file, you can see there are two receivers defined that register for "sms_sent" (and "sms_received") intents. If you look at the method I mentioned, you can see that before calling sendTextMessage() it creates two intents with the action "sms_sent" and "sms_delivered". This is how you get notified when an SMS is done sending.

Body:
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?

I made this application to send out a number of SMS messages from my phone, but how do I change it to send one at a time?

I am trying to make this send a SMS message and wait for the reply code to get back before sending the next one:

import android.telephony.gsm.SmsManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.util.Log;
import android.widget.Button;

import java.io.*;
import android.util.LogPrinter;

import java.io.*;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
import android.os.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;
import java.io.*;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

public class JSSMS extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(JSSMS.this, "Starting SMS", Toast.LENGTH_LONG)
                        .show();

                String message = "Hello This Is John, Please save my new number";
                String number;
                try {
                    BufferedReader buffreader = new BufferedReader(
                            new FileReader(Environment
                                    .getExternalStorageDirectory().toString()
                                    + "/numbers.txt"));
                    int i = 0;
                    while ((number = buffreader.readLine()) != null) {
                        Toast.makeText(JSSMS.this, "Sending text to:" + number,
                                Toast.LENGTH_SHORT).show();
                        sendSMS(number, message);
                    }

                    buffreader.close();
                } catch (java.io.FileNotFoundException e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();

                } catch (Exception e) {
                    Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();
                }

                Toast.makeText(JSSMS.this, "DONE!!", Toast.LENGTH_LONG).show();
            }
        });
    }

    // ---Sends an SMS message to another device.---
    private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

        // ---When the SMS has been sent---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));

        // ---When the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }
}


问:
Python os.path.dirname and os.path.sep in Java?
Python has os.path.dirname and os.path.sep.  How can I get these values in Java?</p>

答:
Did a bit of googling on what os.path.dirname and os.path.sep actually are

os.path.dirname(path) would be filePath.split(System.getProperty("path.separator"))[0]

os.path.sep would be System.getProperty("file.separator")


问:
Angular Reusable Modules and Components
What is the right/best way to share reusable code with Angular 2+? I'm currently using Angular 4, VSCode, TypeScript, npm, and Angular CLI.  I'm a senior C# developer with some Angular 1.3 apps I want to upgrade.  I'm working to get up to speed on Angular 2+.  I'm currently focused on how to rightly structure larger applications that can benefit from reuse.

I have worked through a PluralSite course (Building a Responsive SPA Framework with Angular) and have a simple site working (just front-end).  I like the conceptual separation between the "SPA framework" and the app and can see that it would be very nice to evolve/extend and reuse the framework.

I'm trying to figure out how to separate the SPA framework and then make use of it in multiple applications and thus only maintain a single copy of the SPA framework code.  If I can successfully gain the separation and reuse that I'm after, I will likely focus quite much on building reusable code and that typically comprises 60%+ of enterprise scale applications.  I have provided some more detail and some specific questions below.

I have been able to successfully "reference" (and thus import) the TypeScript code of the SPA framework from within a new application, but I'm not able to build successfully or run.  I don't have any useful output to share at this point, but what I do see occurring leads me to believe that I'm not close to the right approach.

The file structures are separate, meaning that the SPA framework folder structure does not exist within the application folder structure.  Following the PluralSite course resulted in a structure where the app and the SPA framework were "at the same level" (peer folders) within the project structure.  The Typescript build (driven by the Angular CLI) occurred simultaneously and referenced a single "node_modules" folder.

QUESTIONS

How can I develop and build the SPA framework code (and other similarly "sharable" components) as a separate project and having separate node_modules dependencies (I'm assuming this would be desirable)?  I'm assuming that the SPA framework would be able to build independently, but the app would have a dependency on the SPA framework.  I want to be able to create a new "app 2" and not have to duplicate the code for the SPA framework.

I am assuming that when I eventually build app1 or app2 (and so on... 3, 4, 5, etc.) that the builds will reference the node_module dependencies of the app, and that I won't be (when I build the app) building the SPA framework independently and separately.

Essentially looking for a way to manage the code separately and leverage the SPA framework (and other reusable code) without having to embed the code and maintain variants.

Any assistance would be appreciated.

答:
Here's how I've achieved what you're looking for.

Create a new angular project (I suggest using angular-cli but you don't have to)

Add your code that you want to be shared across your apps here. For example, I created a shared components project.

Follow the Angular Package Format to maintain consistency.

I use ng-packagr to build and package my project. (https://github.com/dherges/ng-packagr)

Publish your project to NPM (or even a private NPM repository)

In your applications now you can just npm install YOUR_SHARED_PROJECT_NAME to include the shared project in your application

Title: Angular Reusable Modules and Components


问:
Try loop inside for loop date parsing Python
so I have this list of items

```<code>Cool beans 12/13/2016  12:00:00 AM
12/15/2016 0:00
10/28/2016 0:00
11/22/2006 0:00
3/31/2017 0:00
1/23/2017 0:00
9/2/2016 0:00
8/18/2016 0:00
2/23/2017 0:00
8/3/2016 0:00
5/11/2010 0:00
10/11/2016 0:00
4/25/2017 0:00
8/29/2016 0:00
5/31/2017 0:00
4/14/2017 0:00
4/6/2016 0:00
12/11/2014 0:00
1/31/2017 0:00
10/12/2010 0:00
</code>```

Im using the following function to parse the dates

```<code>def try_parsing_date(text):
    for fmt in ('%m/%d/%Y', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%Y/%m/%d', '%Y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M'):
        try:
            return datetime.strptime(text, fmt).strftime('%Y/%m/%d')
        except ValueError:
            pass
    raise ValueError('no valid date format)
</code>```

On top of raising the value error is there a way where I can just either change the text to some other date or just make the function continue? In the first entry of my list I added the words cool beans and I know that will raise a value error, but instead of stopping the code, I want nothing to be returned or I want the code to pass over this value or I want to change the value and then rerun the function, any of these solutions will suffice but I dont know how to do it.

答:
The issue with your current approach is that, once you've exhausted all your attempts to get a correct string format for your datetime, you automatically raise ValueError('no valid date format). Instead, you can either return the string unchanged, or you could return a default date string.

For the latter:

```<code>def try_parsing_date(text):
    for fmt in ('%m/%d/%Y', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%Y/%m/%d', '%Y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M'):
        try:
            return datetime.strptime(text, fmt).strftime('%Y/%m/%d')
        except ValueError:
            pass
    return '1900/01/01'
</code>```

Alternatively, a function that does not return anything will automatically return None to the caller, so you could simply have:

```<code>def try_parsing_date(text):
    for fmt in ('%m/%d/%Y', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%Y/%m/%d', '%Y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M'):
        try:
            return datetime.strptime(text, fmt).strftime('%Y/%m/%d')
        except ValueError:
            pass
</code>```

And then handle it outside of the function with:

```<code>if not try_parsing_date(some_string): # OR if try_parsing_date(some_string) is None:
    # Do something here
</code>```

Body:
so I have this list of items

Cool beans 12/13/2016  12:00:00 AM
12/15/2016 0:00
10/28/2016 0:00
11/22/2006 0:00
3/31/2017 0:00
1/23/2017 0:00
9/2/2016 0:00
8/18/2016 0:00
2/23/2017 0:00
8/3/2016 0:00
5/11/2010 0:00
10/11/2016 0:00
4/25/2017 0:00
8/29/2016 0:00
5/31/2017 0:00
4/14/2017 0:00
4/6/2016 0:00
12/11/2014 0:00
1/31/2017 0:00
10/12/2010 0:00

Im using the following function to parse the dates

def try_parsing_date(text):
    for fmt in ('%m/%d/%Y', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%Y/%m/%d', '%Y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M'):
        try:
            return datetime.strptime(text, fmt).strftime('%Y/%m/%d')
        except ValueError:
            pass
    raise ValueError('no valid date format)

On top of raising the value error is there a way where I can just either change the text to some other date or just make the function continue? In the first entry of my list I added the words cool beans and I know that will raise a value error, but instead of stopping the code, I want nothing to be returned or I want the code to pass over this value or I want to change the value and then rerun the function, any of these solutions will suffice but I dont know how to do it.

Body:
The issue with your current approach is that, once you've exhausted all your attempts to get a correct string format for your datetime, you automatically raise ValueError('no valid date format). Instead, you can either return the string unchanged, or you could return a default date string.

For the latter:

def try_parsing_date(text):
    for fmt in ('%m/%d/%Y', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%Y/%m/%d', '%Y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M'):
        try:
            return datetime.strptime(text, fmt).strftime('%Y/%m/%d')
        except ValueError:
            pass
    return '1900/01/01'

Alternatively, a function that does not return anything will automatically return None to the caller, so you could simply have:

def try_parsing_date(text):
    for fmt in ('%m/%d/%Y', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%Y/%m/%d', '%Y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M'):
        try:
            return datetime.strptime(text, fmt).strftime('%Y/%m/%d')
        except ValueError:
            pass

And then handle it outside of the function with:

if not try_parsing_date(some_string): # OR if try_parsing_date(some_string) is None:
    # Do something here


问:
What does a=z++ mean as a increment in a for loop statement?
I came across a for loop statement in a C++ code, like this:

```<code>for (i=N, z=head; i>0;  a=z++, i--) {}
</code>```

The type of z, head and a is a pointer to an array. a=z++ here really confused me. Could anyone give me some guidance on what a=z++ does in this for loop? And what is the relationship between z and a?

答:
Looks like you need to freshen up your C++ grammar.

In any context (loop or no loop) a = z++ means 'increment the value of z, and use the pre-incremented value of z to assign it to a.

In other words, in world of integers, if a is 100 and z is 10, after this executes z is 11, and a is 10.

In case those are pointers within arrays, the same logic applies - if z points to tenth element, after this statement a points to tenth, and z points to eleventh.

Body:
I came across a for loop statement in a C++ code, like this:

for (i=N, z=head; i>0;  a=z++, i--) {}

The type of z, head and a is a pointer to an array. a=z++ here really confused me. Could anyone give me some guidance on what a=z++ does in this for loop? And what is the relationship between z and a?


问:
Mysql - access denied + "Too many connections"
I have just started developing Java application and using MySQL. The application was working before, but basically after I restarted the computer, it stopped working saying "Too many connection".

I know I have done something wrong when I was closing the connection, but I can't figured it out. If you can please point me where I am doing wrong, please.

```<code>    public class ProductFrame extends javax.swing.JFrame {

    /**
     * Creates new form ProductFrame
     */
    public ProductFrame() {
        initComponents();
        Show_Products_In_JTable();

    }

    public Connection getConnection()
    {

        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/smart-mart","root","");
            return con;
        } catch (SQLException ex) {
            Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

        public boolean checkInputs()
    {
        if(
              txt_name.getText() == null
           || txt_price.getText() == null
           || txt_quantity.getText() == null
            || txt_arrdate.getText() == null
            || txt_minreq.getText() == null
            || txt_maxreq.getText() == null
                || txt_staff.getText() == null

          ){
            return false;
        }
        else{
            try{
                Float.parseFloat(txt_price.getText());
                return true;
            }catch(Exception ex)
            {
                return false;
            }
        }
    }

   //** Display Date in the ItemTable ** //
        //** Step 1- Create an arraylist and fill it with date **//

        public ArrayList<Product> getProductList ()
        {
            ArrayList<Product> productList  = new ArrayList<Product>();
            Connection con = getConnection();
            String query = "SELECT * FROM product";

            Statement st;
            ResultSet rs;

        try {
            st = con.createStatement();
             rs = st.executeQuery(query);
              Product product;

   Show_Products_In_JTable();

              while (rs.next())
              {
                  product  = new Product (rs.getInt("id"),rs.getString("name"), Float.parseFloat(rs.getString("price")),rs.getInt("quantity"), rs.getString("arrdate"), rs.getInt("minreq"),rs.getInt("maxreq"), rs.getString("staff"));
                  productList.add(product);
                  con.close();
              }
        } catch (SQLException ex) {
            Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);

        }
        return  productList;
        }

        //** Stept 2- Populate the table ** //

    public void Show_Products_In_JTable()
    {
        ArrayList<Product> list = getProductList();
        DefaultTableModel model = (DefaultTableModel) J_Table_Products.getModel();

        Object[] row = new Object [8];
        for(int i = 0; i<list.size();i++)
        {
        row[0]=list.get(i).getId();
        row[1]=list.get(i).getName();
        row[2]=list.get(i).getPrice();
        row[3]=list.get(i).getQuantity();
        row[4]=list.get(i).getArrDate();
        row[5]=list.get(i).getMinReq();
        row[6]=list.get(i).getMaxReq();
        row[7]=list.get(i).getStaff();

        model.addRow(row);

    }
    }

  // Show Data In Inputs
    public void ShowItem(int index)
    {
            txt_id.setText(Integer.toString(getProductList().get(index).getId()));
            txt_name.setText(getProductList().get(index).getName());
            txt_price.setText(Float.toString(getProductList().get(index).getPrice()));
            txt_quantity.setText(Integer.toString(getProductList().get(index).getQuantity()));
            txt_arrdate.setText(getProductList().get(index).getArrDate());
            txt_minreq.setText(Integer.toString(getProductList().get(index).getMinReq()));
            txt_maxreq.setText(Integer.toString(getProductList().get(index).getMaxReq()));
            txt_staff.setText(getProductList().get(index).getStaff());
    }

    private void btn_insertActionPerformed(java.awt.event.ActionEvent evt) {
      if (checkInputs() && txt_name !=null){

          try {
           Connection con = getConnection();
          PreparedStatement ps;
              ps = con.prepareStatement("INSERT INTO product(name, price, quantity, arrdate, minreq, maxreq, staff)"+"values(?,?,?,?,?,?,?)");
               ps.setString(1, txt_name.getText());
                ps.setString(2, txt_price.getText());
                ps.setString(3, txt_quantity.getText());
                ps.setString(4, txt_arrdate.getText());
                ps.setString(5 , txt_minreq.getText());
                ps.setString(6 , txt_maxreq.getText());
                ps.setString(7, txt_staff.getText());

                ps.executeUpdate();

                Show_Products_In_JTable();
                JOptionPane.showMessageDialog(null, "Data Inserted");

                ps.close();
          } catch (SQLException ex) {
              JOptionPane.showMessageDialog(null, ex.getMessage());
          }

      }
      else{
          JOptionPane.showMessageDialog(null, "One or more field empty");
      }

          System.out.println("Name=>" + txt_name.getText());
          System.out.println("Price=>" + txt_price.getText());
          System.out.println("Quantity=>" + txt_quantity.getText());
          System.out.println("Arrdate=>" + txt_arrdate.getText());
          System.out.println("MinReq=>" + txt_minreq.getText());
          System.out.println("MaxReq=>" + txt_maxreq.getText());
           System.out.println("Staff=>" + txt_staff.getText());

    }

    private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) {
if (checkInputs() && txt_id.getText () !=null)
{
       String UpdateQuery = null;
    PreparedStatement ps = null;
    Connection con = getConnection ();

    try {

    UpdateQuery = "UPDATE product SET name=?, price=?,quantity=?, arrdate=?, minreq=?,maxreq=?, staff=? WHERE id=?";
    ps = con.prepareStatement(UpdateQuery);
                   ps.setString(1, txt_name.getText());
                ps.setString(2, txt_price.getText());
                ps.setString(3, txt_quantity.getText());
                ps.setString(4, txt_arrdate.getText());
                ps.setString(5 , txt_minreq.getText());
                ps.setString(6 , txt_maxreq.getText());
                ps.setString(7, txt_staff.getText());
                ps.setInt(8, Integer.parseInt(txt_id.getText()));

        ps.executeUpdate();
        ps.close();
    } catch (SQLException ex) {
        Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}else{
    JOptionPane.showMessageDialog(null, "One or more fields are Empty");
}
    }

    private void btn_deleteActionPerformed(java.awt.event.ActionEvent evt) {

        if (!txt_id.getText().equals(""))

        {

            try {
                Connection con = getConnection();
                PreparedStatement ps = con.prepareStatement("DELETE FROM product WHERE id = ?");
                int id = Integer.parseInt(txt_id.getText());
                ps.setInt(1, id);
                ps.executeUpdate();

                JOptionPane.showMessageDialog(null, "Item Deleted!");
                ps.close();
            } catch (SQLException ex) {
                Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, "Item Not Deleted!");
                 ex.printStackTrace();

                    } finally {

}

        }
        else{
            JOptionPane.showMessageDialog(null, " Product not found. Please enter the product ID!");
        }

    }

    private void J_Table_ProductsMouseClicked(java.awt.event.MouseEvent evt) {
        int index = J_Table_Products.getSelectedRow();
        ShowItem(index);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ProductFrame().setVisible(true);
            }
        });
    }
</code>```

C.

答:
You are creating a new connection each time that you are you invoking the method getConnection but you don't close it and lose the reference each time that the program is getting out of the function context, so the connection will be opened until the program is running. This situation provokes this issue (too many connections).

Close the connection one you have used it,  or keep a reference to just one opened connection to to reuse it and avoid the process of Open-Use-Close.

Body:
I have just started developing Java application and using MySQL. The application was working before, but basically after I restarted the computer, it stopped working saying "Too many connection".

I know I have done something wrong when I was closing the connection, but I can't figured it out. If you can please point me where I am doing wrong, please.

    public class ProductFrame extends javax.swing.JFrame {

    /**
     * Creates new form ProductFrame
     */
    public ProductFrame() {
        initComponents();
        Show_Products_In_JTable();

    }

    public Connection getConnection()
    {

        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/smart-mart","root","");
            return con;
        } catch (SQLException ex) {
            Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

        public boolean checkInputs()
    {
        if(
              txt_name.getText() == null
           || txt_price.getText() == null
           || txt_quantity.getText() == null
            || txt_arrdate.getText() == null
            || txt_minreq.getText() == null
            || txt_maxreq.getText() == null
                || txt_staff.getText() == null

          ){
            return false;
        }
        else{
            try{
                Float.parseFloat(txt_price.getText());
                return true;
            }catch(Exception ex)
            {
                return false;
            }
        }
    }

   //** Display Date in the ItemTable ** //
        //** Step 1- Create an arraylist and fill it with date **//

        public ArrayList<Product> getProductList ()
        {
            ArrayList<Product> productList  = new ArrayList<Product>();
            Connection con = getConnection();
            String query = "SELECT * FROM product";

            Statement st;
            ResultSet rs;

        try {
            st = con.createStatement();
             rs = st.executeQuery(query);
              Product product;

   Show_Products_In_JTable();

              while (rs.next())
              {
                  product  = new Product (rs.getInt("id"),rs.getString("name"), Float.parseFloat(rs.getString("price")),rs.getInt("quantity"), rs.getString("arrdate"), rs.getInt("minreq"),rs.getInt("maxreq"), rs.getString("staff"));
                  productList.add(product);
                  con.close();
              }
        } catch (SQLException ex) {
            Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);

        }
        return  productList;
        }

        //** Stept 2- Populate the table ** //

    public void Show_Products_In_JTable()
    {
        ArrayList<Product> list = getProductList();
        DefaultTableModel model = (DefaultTableModel) J_Table_Products.getModel();

        Object[] row = new Object [8];
        for(int i = 0; i<list.size();i++)
        {
        row[0]=list.get(i).getId();
        row[1]=list.get(i).getName();
        row[2]=list.get(i).getPrice();
        row[3]=list.get(i).getQuantity();
        row[4]=list.get(i).getArrDate();
        row[5]=list.get(i).getMinReq();
        row[6]=list.get(i).getMaxReq();
        row[7]=list.get(i).getStaff();

        model.addRow(row);

    }
    }

  // Show Data In Inputs
    public void ShowItem(int index)
    {
            txt_id.setText(Integer.toString(getProductList().get(index).getId()));
            txt_name.setText(getProductList().get(index).getName());
            txt_price.setText(Float.toString(getProductList().get(index).getPrice()));
            txt_quantity.setText(Integer.toString(getProductList().get(index).getQuantity()));
            txt_arrdate.setText(getProductList().get(index).getArrDate());
            txt_minreq.setText(Integer.toString(getProductList().get(index).getMinReq()));
            txt_maxreq.setText(Integer.toString(getProductList().get(index).getMaxReq()));
            txt_staff.setText(getProductList().get(index).getStaff());
    }

    private void btn_insertActionPerformed(java.awt.event.ActionEvent evt) {
      if (checkInputs() && txt_name !=null){

          try {
           Connection con = getConnection();
          PreparedStatement ps;
              ps = con.prepareStatement("INSERT INTO product(name, price, quantity, arrdate, minreq, maxreq, staff)"+"values(?,?,?,?,?,?,?)");
               ps.setString(1, txt_name.getText());
                ps.setString(2, txt_price.getText());
                ps.setString(3, txt_quantity.getText());
                ps.setString(4, txt_arrdate.getText());
                ps.setString(5 , txt_minreq.getText());
                ps.setString(6 , txt_maxreq.getText());
                ps.setString(7, txt_staff.getText());

                ps.executeUpdate();

                Show_Products_In_JTable();
                JOptionPane.showMessageDialog(null, "Data Inserted");

                ps.close();
          } catch (SQLException ex) {
              JOptionPane.showMessageDialog(null, ex.getMessage());
          }

      }
      else{
          JOptionPane.showMessageDialog(null, "One or more field empty");
      }

          System.out.println("Name=>" + txt_name.getText());
          System.out.println("Price=>" + txt_price.getText());
          System.out.println("Quantity=>" + txt_quantity.getText());
          System.out.println("Arrdate=>" + txt_arrdate.getText());
          System.out.println("MinReq=>" + txt_minreq.getText());
          System.out.println("MaxReq=>" + txt_maxreq.getText());
           System.out.println("Staff=>" + txt_staff.getText());

    }

    private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) {
if (checkInputs() && txt_id.getText () !=null)
{
       String UpdateQuery = null;
    PreparedStatement ps = null;
    Connection con = getConnection ();

    try {

    UpdateQuery = "UPDATE product SET name=?, price=?,quantity=?, arrdate=?, minreq=?,maxreq=?, staff=? WHERE id=?";
    ps = con.prepareStatement(UpdateQuery);
                   ps.setString(1, txt_name.getText());
                ps.setString(2, txt_price.getText());
                ps.setString(3, txt_quantity.getText());
                ps.setString(4, txt_arrdate.getText());
                ps.setString(5 , txt_minreq.getText());
                ps.setString(6 , txt_maxreq.getText());
                ps.setString(7, txt_staff.getText());
                ps.setInt(8, Integer.parseInt(txt_id.getText()));

        ps.executeUpdate();
        ps.close();
    } catch (SQLException ex) {
        Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}else{
    JOptionPane.showMessageDialog(null, "One or more fields are Empty");
}
    }

    private void btn_deleteActionPerformed(java.awt.event.ActionEvent evt) {

        if (!txt_id.getText().equals(""))

        {

            try {
                Connection con = getConnection();
                PreparedStatement ps = con.prepareStatement("DELETE FROM product WHERE id = ?");
                int id = Integer.parseInt(txt_id.getText());
                ps.setInt(1, id);
                ps.executeUpdate();

                JOptionPane.showMessageDialog(null, "Item Deleted!");
                ps.close();
            } catch (SQLException ex) {
                Logger.getLogger(ProductFrame.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, "Item Not Deleted!");
                 ex.printStackTrace();

                    } finally {

}

        }
        else{
            JOptionPane.showMessageDialog(null, " Product not found. Please enter the product ID!");
        }

    }

    private void J_Table_ProductsMouseClicked(java.awt.event.MouseEvent evt) {
        int index = J_Table_Products.getSelectedRow();
        ShowItem(index);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ProductFrame().setVisible(true);
            }
        });
    }

C.


问:
How do you get the footer to stay at the bottom of a Web page?
I have a simple 2-column layout with a footer that clears both the right and left div in my markup.  My problem is that I can't get the footer to stay at the bottom of the page in all browsers.  It works if the content pushes the footer down, but that's not always the case. </p>

答:
A similar solution to @gcedo but without the need of adding an intermediate content in order to push the footer down. We can simply add margin-top:auto to the footer and it will be pushed to the bottom of the page regardless his height or the height of the content above.

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  margin:0;
}

.content {
  padding: 50px;
  background: red;
}

.footer {
  margin-top: auto;
  padding:10px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  some content here
</div>
<footer class="footer">
  some content
</footer></code>```

OwnerDisplayName: Bill the Lizard

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Jeff Atwood

Body:
A similar solution to @gcedo but without the need of adding an intermediate content in order to push the footer down. We can simply add margin-top:auto to the footer and it will be pushed to the bottom of the page regardless his height or the height of the content above.

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  margin:0;
}

.content {
  padding: 50px;
  background: red;
}

.footer {
  margin-top: auto;
  padding:10px;
  background: green;
}

<div class="content">
  some content here
</div>
<footer class="footer">
  some content
</footer>


问:
SQL- how to retrieve by similar dates
Okay, so I have a table with a user_id column and a submitted_dtm column.

I want to find instances where users submitted multiple records within 1 day of each other, and count how many times that has happened.

I've tried something like

```<code>select * from table_t t where
(select count(*) from table_t t2 where
t.user_id = t2.user_id and
t.pk!=t2.pk and
t.submitted_dtm between t2.submitted_dtm-.5 and t2.submitted_dtm+.5)>0;
</code>```

The problem is that this query returns a result for each record in a date group.  Instead, I just want a result per date group. Ideally, I'd just get the count in that group.

That is, if I have 6 records:

```<code>user_id     submitted_dtm
--------------------------
1            12/04/2017 1:15
1            12/04/2017 5:50
2            11/25/2017 2:00
2            11/25/2017 3:25
2            11/25/2017 6:05
2            10/06/2017 4:00
</code>```

I want 2 results, a count of 2 and a count of 3.

Is it possible to do this in sql?

答:
Following up on Dessma's answer.

```<code>select user_id, trunc(submitted_dtm), count(1)
  from table_t
 group by user_id, trunc(submitted_dtm)
having count(1) > 1;
</code>```

Sqlfiddle

Title: SQL- how to retrieve by similar dates

Body:
Okay, so I have a table with a user_id column and a submitted_dtm column.

I want to find instances where users submitted multiple records within 1 day of each other, and count how many times that has happened.

I've tried something like

select * from table_t t where
(select count(*) from table_t t2 where
t.user_id = t2.user_id and
t.pk!=t2.pk and
t.submitted_dtm between t2.submitted_dtm-.5 and t2.submitted_dtm+.5)>0;

The problem is that this query returns a result for each record in a date group.  Instead, I just want a result per date group. Ideally, I'd just get the count in that group.

That is, if I have 6 records:

user_id     submitted_dtm
--------------------------
1            12/04/2017 1:15
1            12/04/2017 5:50
2            11/25/2017 2:00
2            11/25/2017 3:25
2            11/25/2017 6:05
2            10/06/2017 4:00

I want 2 results, a count of 2 and a count of 3.

Is it possible to do this in sql?

Body:
Following up on Dessma's answer.

select user_id, trunc(submitted_dtm), count(1)
  from table_t
 group by user_id, trunc(submitted_dtm)
having count(1) > 1;

Sqlfiddle


问:
How significant is .NET 3.5 SP1 for WCF/REST?
I just worked through a book on WCF and was surprised that it didn't even mention REST at all.

Was REST an afterthought for WCF that was added in .NET 3.5 SP1 and hence not baked in well or is it well integrated?

I assume that Silverlight and XBAPs can consume WCF with no problem or do they have some limitation due to their sandbox environments? I've been reading that some people are having problems getting WCF to play well with XBAP and I would assume there are similar problems with Silverlight.

答:
Many of the constraints to apply to a REST system will be difficult, if not impossible, to implement with WCF REST. The programming model has leaky abstractions (different methods for json / xml), doesn't support multiple media types (only xml and json), relies too much on uri parameters for method selection, etc. And it doesn't integrate with asp.net in any way, aka there's a difference between the service /customer handled by WCF and the /customer that should return html.

Not that you couldn't implement all those yourself, but you'll soon end up with something that replaces nearly everything that WCF Rest has out of the box.

OwnerDisplayName: Edward Tanguay

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Fabian Steeg


问:
Rails + Authlogic @current_user problem - "Show" method no longer works
I implemented Authlogic in my rails app which works and tests great. Users can login, logout, etc.

However, since I changed my methods in the users_controller to use the @current_user variable, none of my user methods or forms (other than "index" strangely...) work!

For example, this "Show" methods works and shows the user profile for any user (Note: I want to eventually restrict this to the currently logged in user somehow):

```<code>def show
    @user = User.find(params[:id])
end
</code>```

If I follow the show method as shown in the Authlogic rails cast and the official example to:

```<code>def show
    @user = @current_user
end
</code>```

I get all kinds of undefined method METHOD for nil:NilClass errors. It seems as the though the @current_user variable doesn't contain any of the user's information.

I assume the @current_user is pulling info from the current_user method as defined in the application controller below:

```<code>def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end
</code>```

What am I missing? My hunch is that there is no mapping between the User object from the user model and the current_user method. Any help would be greatly appreciated!

Thanks in advance!

~Dan

答:
Shouldn't it be just

```<code>def show
    @user = current_user
end
</code>```

without the @?

Body:
I implemented Authlogic in my rails app which works and tests great. Users can login, logout, etc.

However, since I changed my methods in the users_controller to use the @current_user variable, none of my user methods or forms (other than "index" strangely...) work!

For example, this "Show" methods works and shows the user profile for any user (Note: I want to eventually restrict this to the currently logged in user somehow):

def show
    @user = User.find(params[:id])
end

If I follow the show method as shown in the Authlogic rails cast and the official example to:

def show
    @user = @current_user
end

I get all kinds of undefined method METHOD for nil:NilClass errors. It seems as the though the @current_user variable doesn't contain any of the user's information.

I assume the @current_user is pulling info from the current_user method as defined in the application controller below:

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

What am I missing? My hunch is that there is no mapping between the User object from the user model and the current_user method. Any help would be greatly appreciated!

Thanks in advance!

~Dan

Body:
Shouldn't it be just

def show
    @user = current_user
end

without the @?


问:
I don't understand incompatible type error in assignment
Can someone explain why I have the flow error

```<code>object type (This type is incompatible with object type Indexable signature is incompatible:)
</code>```

for the assignment in the last line of

```<code>const plain: { [key: string]: string } = { prop: '' };
type TestType = { [key: string]: string | number };
const testVar: TestType = plain;
</code>```

I have no error if I remove the type specification for plain...

Many thanks !

答:
Vladimir Kurchatkin answered to this question in the issue I opened on github (https://github.com/facebook/flow/issues/5458) :

Objects are invariant by default. You can make it covariant like this:

```<code>const plain: { [key: string]: string } = { prop: '' };
type TestType = { +[key: string]: string | number };
const testVar: TestType = plain;
</code>```

Body:
Can someone explain why I have the flow error

object type (This type is incompatible with object type Indexable signature is incompatible:)

for the assignment in the last line of

const plain: { [key: string]: string } = { prop: '' };
type TestType = { [key: string]: string | number };
const testVar: TestType = plain;

I have no error if I remove the type specification for plain...

Many thanks !

Body:
Vladimir Kurchatkin answered to this question in the issue I opened on github (https://github.com/facebook/flow/issues/5458) :

Objects are invariant by default. You can make it covariant like this:

const plain: { [key: string]: string } = { prop: '' };
type TestType = { +[key: string]: string | number };
const testVar: TestType = plain;


问:
Understanding Delete [] c++
Before all let me say that i have already search for an answer, and i can't find any that explains to me why i'm having problems.

Im a student and im now learning C++

So before tell me to not use C++ in this way, let me say to you that it is for learning purposes and understanding of some comcepts.

Program crashes at very last statement. delete[] tempVector;
I cant understand why it happens since delete[] vector; works just fine.

The error: play with arr.exe has triggered a breakpoint

Please help me to understand what im doing wrong.

Thank you a lot.

```<code>class BetterArray
{
private:

    int* vector;
    int count;

public:

    BetterArray(int value);
    BetterArray(int* vec, int size);
    ~BetterArray();

    void add(int value);

    int* getArray();

};

BetterArray::BetterArray(int value)
{
   count = 1;

   vector = new int[1];
   vector[0] = value;
 }

void BetterArray::add(int value){

    int* tempVector = new int[count + 1];

    for (int i = 0; i < count; i++)
        tempVector[i] = vector[i];

    tempVector[count] = value;

    count++;

    delete[] vector;

    vector = tempVector;

    delete[] tempVector; // programa crahses here.
}
</code>```

答:
Crash on delete is often a result of a heap corruption. When you assign the tempVector pointer to vector both pointer point to the same memory location. So deleting tempVector  also deletes vector. vector now points to unassigned memory.

Now assuming you write to vector, you are writing to unassigned memory which will corrupt the heap. What happens after this is undefined behaviour but if the heap manager detects the corruption, it will often just crash.

Title: Understanding Delete [] c++

Body:
Before all let me say that i have already search for an answer, and i can't find any that explains to me why i'm having problems.

Im a student and im now learning C++

So before tell me to not use C++ in this way, let me say to you that it is for learning purposes and understanding of some comcepts.

Program crashes at very last statement. delete[] tempVector;
I cant understand why it happens since delete[] vector; works just fine.

The error: play with arr.exe has triggered a breakpoint

Please help me to understand what im doing wrong.

Thank you a lot.

class BetterArray
{
private:

    int* vector;
    int count;

public:

    BetterArray(int value);
    BetterArray(int* vec, int size);
    ~BetterArray();

    void add(int value);

    int* getArray();

};

BetterArray::BetterArray(int value)
{
   count = 1;

   vector = new int[1];
   vector[0] = value;
 }

void BetterArray::add(int value){

    int* tempVector = new int[count + 1];

    for (int i = 0; i < count; i++)
        tempVector[i] = vector[i];

    tempVector[count] = value;

    count++;

    delete[] vector;

    vector = tempVector;

    delete[] tempVector; // programa crahses here.
}


问:
Add a default value to form submission in Laravel
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

```<code>    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');
</code>```

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

答:
You can set the default value of an input if it's null, like so:

```<code>$shipment->shipment_billing_status = request("shipment_billing_status", 1);
</code>```

If request("shipment_billing_status") is null, it'll set $shipment->shipment_billing_status to 1. I don't think this works for "" (input being sent but set to an empty value), so you may have to handle as such:

```<code>$billingStatus = request("shipment_billing_status");
if(!$billingStatus || $billingStatus == ""){
   $shipment->shipment_billing_status = 1;
} else {
   $shipment->shipment_billing_status = $billingStatus;
}
</code>```

This should handle cases of sending the value in the POST data or omitting it completely.

Body:
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

Body:
You can set the default value of an input if it's null, like so:

$shipment->shipment_billing_status = request("shipment_billing_status", 1);

If request("shipment_billing_status") is null, it'll set $shipment->shipment_billing_status to 1. I don't think this works for "" (input being sent but set to an empty value), so you may have to handle as such:

$billingStatus = request("shipment_billing_status");
if(!$billingStatus || $billingStatus == ""){
   $shipment->shipment_billing_status = 1;
} else {
   $shipment->shipment_billing_status = $billingStatus;
}

This should handle cases of sending the value in the POST data or omitting it completely.


答:
for bubble sorting a linked list,you first require a head pointer then two more pointers and the implementation will be same as that of bubble sort but with slight differences as linked list element can not be accessed by directly by a index you have to use the following two pointers for comparing values as you do for arrays in bubble sort.

```<code>    pptr=head;  //for the previou element
    ptr=head->next;//for the next element

   if(pptr->value > ptr->value)  //comparing the value in linked list
</code>```

don't forget to increment two pointers.

Title: Bubble sort in c linked list

Body:
I need to do is read in an input file into a linked list. Part of the file is:

NameA, 25

NameB, 33

NameC, 23

NameD, 39

And after i need to sort by the number (bubble sort) and write it to another file.

Here is what i have:

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

struct node{
    char name[20];
    int number;
    struct node *next;
    struct node *prev;
}*head;

int main(void) {

    struct node *temp;
    temp = malloc(sizeof(struct node));
    temp->next = NULL;
    head = temp;

    FILE *ifp;
    char fnamer[100] = "";
    char line[128];
//    printf("\n\nPlease Enter the Full Path of the file: \n");
//    scanf("%s",&fnamer);

    ifp = fopen("mintaadatok.txt", "r");
    if (ifp == NULL) {
        printf("\n%s\" File NOT FOUND!", fnamer);
        exit(1);
    }

    int c = 0;

    char buffer[1024];
    memset(buffer, 0, 1024);
    while (c < 15) {
        fgets(buffer, 1024, ifp);
        sscanf(buffer, "%19[^,], %d", temp->name, &temp->number);
        printf("%d %s %d\n", c, temp->name, temp->number);
        temp->next = malloc(sizeof(struct node));
        temp = temp->next;
        temp->next = NULL;
        c++;
    }

    int i,step;
    for (temp = head; temp; temp = temp->next) {
        printf("%s", temp->name);
        printf("%d\n", temp->number);
        for(step=0;step<10-1;++step)
            for(i=0;i<10-step-1;++i)
            {
                temp->next = malloc(sizeof(struct node));
                if(temp->number>temp->next)
                {
                    temp=temp->number;
                    temp->number=temp->next;
                    temp->next=temp;
                }
            }
    }
    printf("In ascending order: ");
}

Can you help me to sort these data?

Body:
for bubble sorting a linked list,you first require a head pointer then two more pointers and the implementation will be same as that of bubble sort but with slight differences as linked list element can not be accessed by directly by a index you have to use the following two pointers for comparing values as you do for arrays in bubble sort.

    pptr=head;  //for the previou element
    ptr=head->next;//for the next element

   if(pptr->value > ptr->value)  //comparing the value in linked list

don't forget to increment two pointers.