问:
Passing Array of arrays to subroutine in Perl
I'm trying to create a subroutine which will pass an array of arrays to a subroutine so commands can be run in different directories in parallel.

Basically, each first index is for each command-directory pair.  The second index has two variables: directory and the command itself.

For example,

```<code>my @commands;
$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > avemaria.txt';#command
</code>```

however, I cannot figure out how to reference the data in a subroutine, I have tried every possible combination of "[]{}" I can think of in many different locations.  I've read the perl documentation in https://perldoc.perl.org/perldsc.html but can't see how it applies here.

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

use strict; use warnings; use Cwd;
my $TOP_DIRECTORY = getcwd();
local $SIG{__WARN__} = sub {#kill the program if there are any warnings
    my $message = shift;
    my $fail_filename = "$TOP_DIRECTORY/$0.FAIL";
    open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
    printf $fh ("$message @ %s\n", getcwd());
    close $fh;
    die "$message\n";
};#http://perlmaven.com/how-to-capture-and-save-warnings-in-perl

sub execute {
    my $command = shift;
    print "Executing Command: $command\n";
    if (system($command) != 0) {
        my $fail_filename = "$TOP_DIRECTORY/$0.fail";
        open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
        print $fh "$command failed.\n";
        close $fh;
        print "$command failed.\n";
        die;
    }
}

sub run_parallel {
    my $command_array_reference = shift;
    unless ((ref $command_array_reference) =~ m/ARRAY/) {
        print "run_parallel requires an array reference as input.\n";
        die;
    }
    use Parallel::ForkManager;
    my $manager = new Parallel::ForkManager(4);
    my $START_DIRECTORY = getwd();
    foreach my $command (0..scalar @{ $command_array_reference }-1) {
        $manager->start and next;
        my $dir = @$command_array_reference[$command][0];
        chdir $dir or die "Can't chdir to $dir: $!";
        execute( @$command_array_reference[$command][1] );
        chdir $START_DIRECTORY or die "Can't chdir to $START_DIRECTORY: $!";
        $manager->finish;
    }
    $manager->wait_all_children;#necessary after all lists
}

my @commands;

$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > aveMaria.txt';#command

$commands[1][0] = 'tmp2';#directory
$commands[1][1] = 'echo "IN HOC SIGNO VINCES" > xp.txt';#command

run_parallel(\@commands);
</code>```

this particular configuration produces the error

```<code>703404669@ssxfisctimga004:~/Scripts$ perl parallelForkManager_dir.pl
syntax error at parallelForkManager_dir.pl line 38, near "]["
Global symbol "$dir" requires explicit package name at parallelForkManager_dir.pl line 39.
Global symbol "$dir" requires explicit package name at parallelForkManager_dir.pl line 39.
syntax error at parallelForkManager_dir.pl line 40, near "]["
Execution of parallelForkManager_dir.pl aborted due to compilation errors.
</code>```

how can I read the directory-command pairs in the subroutine?

答:
If you are in doubt about a data structure, Data::Dumper is your friend.

```<code>use Data::Dumper;

# with your @commands
print Dumper \@commands;
</code>```

This prints

```<code>$VAR1 = [
      [
        'tmp1',
        'echo "ave Maria" > aveMaria.txt'
      ],
      [
        'tmp2',
        'echo "IN HOC SIGNO VINCES" > xp.txt'
      ]
    ];
</code>```

Now we know that there is an array reference with array references inside. The first level of reference is the backslash in your \@commands. It creates a reference to the array. The second reference is each array ref inside that.

In Perl, you cannot have an array inside an array, only references to arrays. The way you are assigning them is correct short-hand, but probably confused you.

```<code>$commands[0][0]   = 'tmp1';
$commands[0]->[0] = 'tmp1'; # equivalent
</code>```

The -> is the dereference operator. It's not required for a multi-dimensional data structure, because they are always references beyond the first

Now in your sub you've got:

```<code>my $command_array_reference = \@commands;
</code>```

To get to the values, use the arrows. You can omit most of them, but the first one is required.

```<code>my $dir = $command_array_reference->[0]->[0];
my $cmd = $command_array_reference->[0]->[1];
</code>```

If you want to get the whole thing as a list, dereference the first level like this, which tells Perl that what's inside of $foo->[0] is an array ref:

```<code>my ($dir, $cmd) = @{ $command_array_reference->[0] };
</code>```

I suggest you take a look at perlreftut, perlref and maybe perllol.

Body:
I'm trying to create a subroutine which will pass an array of arrays to a subroutine so commands can be run in different directories in parallel.

Basically, each first index is for each command-directory pair.  The second index has two variables: directory and the command itself.

For example,

my @commands;
$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > avemaria.txt';#command

however, I cannot figure out how to reference the data in a subroutine, I have tried every possible combination of "[]{}" I can think of in many different locations.  I've read the perl documentation in https://perldoc.perl.org/perldsc.html but can't see how it applies here.

#!/usr/bin/env perl

use strict; use warnings; use Cwd;
my $TOP_DIRECTORY = getcwd();
local $SIG{__WARN__} = sub {#kill the program if there are any warnings
    my $message = shift;
    my $fail_filename = "$TOP_DIRECTORY/$0.FAIL";
    open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
    printf $fh ("$message @ %s\n", getcwd());
    close $fh;
    die "$message\n";
};#http://perlmaven.com/how-to-capture-and-save-warnings-in-perl

sub execute {
    my $command = shift;
    print "Executing Command: $command\n";
    if (system($command) != 0) {
        my $fail_filename = "$TOP_DIRECTORY/$0.fail";
        open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
        print $fh "$command failed.\n";
        close $fh;
        print "$command failed.\n";
        die;
    }
}

sub run_parallel {
    my $command_array_reference = shift;
    unless ((ref $command_array_reference) =~ m/ARRAY/) {
        print "run_parallel requires an array reference as input.\n";
        die;
    }
    use Parallel::ForkManager;
    my $manager = new Parallel::ForkManager(4);
    my $START_DIRECTORY = getwd();
    foreach my $command (0..scalar @{ $command_array_reference }-1) {
        $manager->start and next;
        my $dir = @$command_array_reference[$command][0];
        chdir $dir or die "Can't chdir to $dir: $!";
        execute( @$command_array_reference[$command][1] );
        chdir $START_DIRECTORY or die "Can't chdir to $START_DIRECTORY: $!";
        $manager->finish;
    }
    $manager->wait_all_children;#necessary after all lists
}

my @commands;

$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > aveMaria.txt';#command

$commands[1][0] = 'tmp2';#directory
$commands[1][1] = 'echo "IN HOC SIGNO VINCES" > xp.txt';#command

run_parallel(\@commands);

this particular configuration produces the error

703404669@ssxfisctimga004:~/Scripts$ perl parallelForkManager_dir.pl
syntax error at parallelForkManager_dir.pl line 38, near "]["
Global symbol "$dir" requires explicit package name at parallelForkManager_dir.pl line 39.
Global symbol "$dir" requires explicit package name at parallelForkManager_dir.pl line 39.
syntax error at parallelForkManager_dir.pl line 40, near "]["
Execution of parallelForkManager_dir.pl aborted due to compilation errors.

how can I read the directory-command pairs in the subroutine?

Body:
If you are in doubt about a data structure, Data::Dumper is your friend.

use Data::Dumper;

# with your @commands
print Dumper \@commands;

This prints

$VAR1 = [
      [
        'tmp1',
        'echo "ave Maria" > aveMaria.txt'
      ],
      [
        'tmp2',
        'echo "IN HOC SIGNO VINCES" > xp.txt'
      ]
    ];

Now we know that there is an array reference with array references inside. The first level of reference is the backslash in your \@commands. It creates a reference to the array. The second reference is each array ref inside that.

In Perl, you cannot have an array inside an array, only references to arrays. The way you are assigning them is correct short-hand, but probably confused you.

$commands[0][0]   = 'tmp1';
$commands[0]->[0] = 'tmp1'; # equivalent

The -> is the dereference operator. It's not required for a multi-dimensional data structure, because they are always references beyond the first

Now in your sub you've got:

my $command_array_reference = \@commands;

To get to the values, use the arrows. You can omit most of them, but the first one is required.

my $dir = $command_array_reference->[0]->[0];
my $cmd = $command_array_reference->[0]->[1];

If you want to get the whole thing as a list, dereference the first level like this, which tells Perl that what's inside of $foo->[0] is an array ref:

my ($dir, $cmd) = @{ $command_array_reference->[0] };

I suggest you take a look at perlreftut, perlref and maybe perllol.


来源: stackexchange

问:
Render shapefile with no projection in leaflet map
I want to render a shapefile inside of a leaflet map.

This shapefile has no projection so I'm trying to give it one.

```<code>  directions <- readOGR("./directions/", "directions")
  proj4string(directions) <- CRS("+proj=longlat +datum=WGS84 +no_defs")
</code>```

And after that I try to add it to my map like this:

```<code>  map <- leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%

    addPolygons(data=directions,weight=1,col = 'black') %>%

    setView(lng = -3.8196207,
            lat = 40.4678698,
            zoom = 10)
</code>```

The problem is that I get an error saying:

Geographical CRS given to non-conformant data:  450781.167295 4485221.863980

I tried using other projections as CRS like

```<code>  proj4string(directions) <- CRS("+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs")
</code>```

which does not give me an error but the shapefile is not getting rendered either.

I don't really understand why that happens and how I can fix it.

BTW: I got this shapefile from a spanish website where traffic and airquality data gets published

答:
You were very close. What you need to do is convert the projection from UTM Zone 17N to longitude and latitude projection.

```<code>library(sp)
library(rgdal)
library(leaflet)

# Read the shapefile
directions <- readOGR("directions", "directions")
# Set the projection to be UTM zone 30N
proj4string(directions) <- CRS("+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs")
# Conduct project transformation from UTM zone 30N to long-lat
directions_longlat <- spTransform(directions, CRS("+proj=longlat +datum=WGS84 +no_defs"))

map <- leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data = directions_longlat, weight=1, col = 'black') %>%
  setView(lng = -3.8196207,
          lat = 40.4678698,
          zoom = 10)
map
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to render a shapefile inside of a leaflet map.

This shapefile has no projection so I'm trying to give it one.

  directions <- readOGR("./directions/", "directions")
  proj4string(directions) <- CRS("+proj=longlat +datum=WGS84 +no_defs")

And after that I try to add it to my map like this:

  map <- leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%

    addPolygons(data=directions,weight=1,col = 'black') %>%

    setView(lng = -3.8196207,
            lat = 40.4678698,
            zoom = 10)

The problem is that I get an error saying:

Geographical CRS given to non-conformant data:  450781.167295 4485221.863980

I tried using other projections as CRS like

  proj4string(directions) <- CRS("+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs")

which does not give me an error but the shapefile is not getting rendered either.

I don't really understand why that happens and how I can fix it.

BTW: I got this shapefile from a spanish website where traffic and airquality data gets published

Body:
You were very close. What you need to do is convert the projection from UTM Zone 17N to longitude and latitude projection.

library(sp)
library(rgdal)
library(leaflet)

# Read the shapefile
directions <- readOGR("directions", "directions")
# Set the projection to be UTM zone 30N
proj4string(directions) <- CRS("+proj=utm +zone=30 +ellps=GRS80 +units=m +no_defs")
# Conduct project transformation from UTM zone 30N to long-lat
directions_longlat <- spTransform(directions, CRS("+proj=longlat +datum=WGS84 +no_defs"))

map <- leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data = directions_longlat, weight=1, col = 'black') %>%
  setView(lng = -3.8196207,
          lat = 40.4678698,
          zoom = 10)
map


问:
goroutines deadlock when using channels
Im new to go lang and I am trying to write a simple recursive algorithm which will use  goroutines. I am using channels to receive output from goroutine, but when I try to do so I receive "fatal error: all goroutines are asleep - deadlock!" error. If I comment out channels code everything runs fine.
This is my code:

```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    numbers := []int{2, -1, 10, 4, 3, 6, 22}

    ch := make(chan []int)

    wg := &sync.WaitGroup{}
    wg.Add(1)
    go testFunc(numbers, ch, wg)
    wg.Wait()

    result := <-ch

    fmt.Println("Result: ", result)
}

func testFunc(numbers []int, ch chan []int, wg *sync.WaitGroup) {
    defer wg.Done()
    ch <- numbers
}
</code>```

What I am doing wrong  ? I am assigning value to channel in goroutine and reading it in main. Isn't that enough to communicate?

答:
Communication on the unbuffered channel ch succeeds only when both a sender and receiver are ready.

The main function waits on the wait group before receiving the value.  The goroutine attempts to send on the channel before call wg.Done. It's a deadlock.

One fix is to use a buffered channel:

```<code>     ch := make(chan []int, 1)
</code>```

Another fix is to receive on the channel before calling wg.Wait().

```<code>result := <-ch
wg.Wait()
</code>```

Yet another fix is to delete all lines using the wait group. It's not needed in this specific example.

Title: goroutines deadlock when using channels

Body:
Im new to go lang and I am trying to write a simple recursive algorithm which will use  goroutines. I am using channels to receive output from goroutine, but when I try to do so I receive "fatal error: all goroutines are asleep - deadlock!" error. If I comment out channels code everything runs fine.
This is my code:

package main

import (
    "fmt"
    "sync"
)

func main() {
    numbers := []int{2, -1, 10, 4, 3, 6, 22}

    ch := make(chan []int)

    wg := &sync.WaitGroup{}
    wg.Add(1)
    go testFunc(numbers, ch, wg)
    wg.Wait()

    result := <-ch

    fmt.Println("Result: ", result)
}

func testFunc(numbers []int, ch chan []int, wg *sync.WaitGroup) {
    defer wg.Done()
    ch <- numbers
}

What I am doing wrong  ? I am assigning value to channel in goroutine and reading it in main. Isn't that enough to communicate?

Body:
Communication on the unbuffered channel ch succeeds only when both a sender and receiver are ready.

The main function waits on the wait group before receiving the value.  The goroutine attempts to send on the channel before call wg.Done. It's a deadlock.

One fix is to use a buffered channel:

     ch := make(chan []int, 1)

Another fix is to receive on the channel before calling wg.Wait().

result := <-ch
wg.Wait()

Yet another fix is to delete all lines using the wait group. It's not needed in this specific example.


问:
How to setup external load balancer or Proxy on Windows Docker Swarm?
I'm new to Docker, need expose multiple container on different domain. Whether I need to setup external load balancer or proxy?

And also for production setup have to deploy container on which networking overlay or anyother?

Anyone please clear me on this on Windows Docker Production?

答:
First you have to realize what all that buzzwords means.

When using docker swarm mode, we're takling about

using overlay networks

using services

then scaling, service discovery and load balancing are included and handled by docker swarm.

On a single docker machine, we're talking about

using bridge networks

using run command

Whether I need to setup external load balancer or proxy?

In the end you only need a external load balancer for all your instances. Remember, every node (doesn't matter if it's a manager or worker) can be used as entry point where you can reach every service.

But that requires a reverse proxy (doesn't matter if it's apache, nginx, haproxy ...take what you're familar with) is configured and reployed in global mode.


问:
OpenGL depth test not working as expected
I have a simple program to use depth test.   It is not working as expected.   The program draws X, Y axis and a sphere near the origin.
If I don't turn on the GL_DEPTH_TEST, the sphere is drawn over the axis.   If I turn on the GL_DEPTH_TEST, the axis are drawn over the sphere which I was not expecting.   Can someone tell me what I did
wrong ?</p>

```<code>void
glwid::initializeGL()
{
    glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
}

void
glwid::resizeGL(int width, int height)
{
    glViewport( 0, 0, (GLint)width, (GLint)height );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glEnable (GL_DEPTH_TEST);
}

void
glwid::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt (0, 0, 100, 0, 0, 0, 0, 1, 0);

    //
    // X axis
    //
    glBegin( GL_LINES );
    qglColor( green );
    glVertex3f (-100.0,  0, 0. );
    glVertex3f (100.0, 0, 0. );
    glEnd();

    //
    // Y axis
    //
    glBegin( GL_LINES );
    qglColor( red );
    glVertex3f (0.0, 100.0, 0. );
    glVertex3f (0.0, -100, 0. );
    glEnd();

    //
    // sun
    //
    glTranslated (5, 0, 20);
    GLUquadricObj *sphere_quadric = gluNewQuadric();
    glColor3ub (255, 255, 0);
    gluQuadricDrawStyle(sphere_quadric, (GLenum)GLU_SMOOTH);
    gluSphere(sphere_quadric, 10, 36, 36);
}
</code>```

答:
Your axis starts at Z location 0. The Sphere is at Z location 20 (farther away from the "camera") therefore the axis is in-front of the sphere and is being shown.

As you currently have it setup, as Z values go up they move away from the screen. As they go down, they are going closer to the screen.

You have two options: Disable depth testing while drawing your axis (therefore it will always be behind everything). Or move your axis to Z position 100 or so and scale it up to make it look the same size. Option one is probably better.

Simply wrapping your axis drawing routines in glDisable(GL_DEPTH_TEST); and glEnable (GL_DEPTH_TEST);  should do the trick

ContentLicense: CC BY-SA 2.5

Body:
I have a simple program to use depth test.   It is not working as expected.   The program draws X, Y axis and a sphere near the origin.
If I don't turn on the GL_DEPTH_TEST, the sphere is drawn over the axis.   If I turn on the GL_DEPTH_TEST, the axis are drawn over the sphere which I was not expecting.   Can someone tell me what I did
wrong ?

void
glwid::initializeGL()
{
    glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
}

void
glwid::resizeGL(int width, int height)
{
    glViewport( 0, 0, (GLint)width, (GLint)height );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    gluPerspective ( 90, (GLint)width/ (GLint)height, 0.0, 200.0 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glEnable (GL_DEPTH_TEST);
}

void
glwid::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt (0, 0, 100, 0, 0, 0, 0, 1, 0);

    //
    // X axis
    //
    glBegin( GL_LINES );
    qglColor( green );
    glVertex3f (-100.0,  0, 0. );
    glVertex3f (100.0, 0, 0. );
    glEnd();

    //
    // Y axis
    //
    glBegin( GL_LINES );
    qglColor( red );
    glVertex3f (0.0, 100.0, 0. );
    glVertex3f (0.0, -100, 0. );
    glEnd();

    //
    // sun
    //
    glTranslated (5, 0, 20);
    GLUquadricObj *sphere_quadric = gluNewQuadric();
    glColor3ub (255, 255, 0);
    gluQuadricDrawStyle(sphere_quadric, (GLenum)GLU_SMOOTH);
    gluSphere(sphere_quadric, 10, 36, 36);
}


问:
Visual Studio Code find selected text in files

In Visual Studio Code:

I would like to: select text in editor, press hotkey "for find in files", press return:

result: find all instances of selected text in files

(So I would need the currently selected text copy pasted into the search input field)

答:
The default keybinding for search ctrl+shift+f works - it uses the command:
"-workbench.action.findInFilesWithSelectedText"

I had a custom key binding and mapped to
    "command": "-workbench.action.findInFiles"


问:
REST equivalent of CreateEnvelopeFromTemplates?
The SOAP method CreateEnvelopeFromTemplates takes a list of TemplateReference objects which allows me to create a 1-1 mapping of documents in my ECM system to DocuSign Templates. This has worked great up until now and has allowed me to build an envelope creation algorithm without having to know how many documents are involved in a specific use case.

SOAP however does not support the new Payment tabs. In trying to find a REST replacement for this API call I haven't been able to find a way to create an envelope where each document references a different Template. The envelopes: create method for example only allows for one templateID in the envelopeDefinition. Is there a way to port the functionality I've built over to REST?

BONUS QUESTION: Why does the DocuSign backend differentiate between SOAP and REST created envelopes when applying Templates? I didn't expect to be able to programatically create Payment tabs on an envelope with SOAP, but I'm surprised specifying a Template with Payment tabs using SOAP prevents those tabs from working.

This is my SOAP call with non-functional referencing a Template with non-functional Payment tabs:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <CreateEnvelopeFromTemplates xmlns="http://www.docusign.net/API/3.0">
            <TemplateReferences>
                <TemplateReference>
                    <TemplateLocation>Server</TemplateLocation>
                    <Template>8E556CD1-D343-4C07-9401-D88B00A67671</Template>
                    <Document>
                        <ID>90267</ID>
                        <Name>DS - Template Mapping - 12/4/2017 John Payme2 (90267)</Name>
                        <PDFBytes>omitted</PDFBytes>
                        <FileExtension>pdf</FileExtension>
                    </Document>
                    <RoleAssignments>
                        <RoleAssignment>
                            <RoleName>Payer</RoleName>
                            <RecipientID>37974046</RecipientID>
                        </RoleAssignment>
                    </RoleAssignments>
                    <Sequence>1</Sequence>
                </TemplateReference>
            </TemplateReferences>
            <Recipients>
                <Recipient>
                    <ID>37974046</ID>
                    <UserName>John Payme2</UserName>
                    <Email>ANDREW.MORTON@HYLAND.COM</Email>
                    <Type>Signer</Type>
                    <AccessCode />
                    <RequireIDLookup>false</RequireIDLookup>
                    <RoutingOrder>1</RoutingOrder>
                    <Note/>
                    <RoleName>Payer</RoleName>
                </Recipient>
            </Recipients>
            <EnvelopeInformation>
                <AccountId>9cace92e-1384-4cf7-9b4c-a2bd70aab9a1</AccountId>
            </EnvelopeInformation>
            <ActivateEnvelope>true</ActivateEnvelope>
        </CreateEnvelopeFromTemplates>
    </soap:Body>
</soap:Envelope>
</code>```

答:
What you are looking for is called Composite Templates in the REST API.  Composite templates are a very powerful feature though they can get complex pretty quickly - using CTs you can do things like combine a template and a document in the same envelope, or combine multiple templates, etc.

One of the better resources on composite templates is the features page on Templates found in the Developer Center, which has a section for composite templates:
https://www.docusign.com/developer-center/explore/features/templates#composite

There's a section in the Envelopes:create API documentation that talks about composite templates.

Example Usage:

Here's a quick sample from one of the above resources, in this example two templates are combined into one single envelope:

```<code>{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}
</code>```

Body:
The SOAP method CreateEnvelopeFromTemplates takes a list of TemplateReference objects which allows me to create a 1-1 mapping of documents in my ECM system to DocuSign Templates. This has worked great up until now and has allowed me to build an envelope creation algorithm without having to know how many documents are involved in a specific use case.

SOAP however does not support the new Payment tabs. In trying to find a REST replacement for this API call I haven't been able to find a way to create an envelope where each document references a different Template. The envelopes: create method for example only allows for one templateID in the envelopeDefinition. Is there a way to port the functionality I've built over to REST?

BONUS QUESTION: Why does the DocuSign backend differentiate between SOAP and REST created envelopes when applying Templates? I didn't expect to be able to programatically create Payment tabs on an envelope with SOAP, but I'm surprised specifying a Template with Payment tabs using SOAP prevents those tabs from working.

This is my SOAP call with non-functional referencing a Template with non-functional Payment tabs:

    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <CreateEnvelopeFromTemplates xmlns="http://www.docusign.net/API/3.0">
            <TemplateReferences>
                <TemplateReference>
                    <TemplateLocation>Server</TemplateLocation>
                    <Template>8E556CD1-D343-4C07-9401-D88B00A67671</Template>
                    <Document>
                        <ID>90267</ID>
                        <Name>DS - Template Mapping - 12/4/2017 John Payme2 (90267)</Name>
                        <PDFBytes>omitted</PDFBytes>
                        <FileExtension>pdf</FileExtension>
                    </Document>
                    <RoleAssignments>
                        <RoleAssignment>
                            <RoleName>Payer</RoleName>
                            <RecipientID>37974046</RecipientID>
                        </RoleAssignment>
                    </RoleAssignments>
                    <Sequence>1</Sequence>
                </TemplateReference>
            </TemplateReferences>
            <Recipients>
                <Recipient>
                    <ID>37974046</ID>
                    <UserName>John Payme2</UserName>
                    <Email>ANDREW.MORTON@HYLAND.COM</Email>
                    <Type>Signer</Type>
                    <AccessCode />
                    <RequireIDLookup>false</RequireIDLookup>
                    <RoutingOrder>1</RoutingOrder>
                    <Note/>
                    <RoleName>Payer</RoleName>
                </Recipient>
            </Recipients>
            <EnvelopeInformation>
                <AccountId>9cace92e-1384-4cf7-9b4c-a2bd70aab9a1</AccountId>
            </EnvelopeInformation>
            <ActivateEnvelope>true</ActivateEnvelope>
        </CreateEnvelopeFromTemplates>
    </soap:Body>
</soap:Envelope>

Body:
What you are looking for is called Composite Templates in the REST API.  Composite templates are a very powerful feature though they can get complex pretty quickly - using CTs you can do things like combine a template and a document in the same envelope, or combine multiple templates, etc.

One of the better resources on composite templates is the features page on Templates found in the Developer Center, which has a section for composite templates:
https://www.docusign.com/developer-center/explore/features/templates#composite

There's a section in the Envelopes:create API documentation that talks about composite templates.

Example Usage:

Here's a quick sample from one of the above resources, in this example two templates are combined into one single envelope:

{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}


问:
Hide JQ Error Messages from Curl command
I'm running the following curl command:

```<code>installer_to_delete=$(curl -s -u username:password "URL/api/search/dates?dateFields=created&from=${Two_Years_Ago}&today&repos=npm-local-lrn" | jq -r '.results[].uri'|sed 's=/api/storage==')

if [[ $installer_to_delete == "" ]]
then
    echo "No installers found"
else
    for installer in $installer_to_delete
    do
    echo $installer
    done
fi
</code>```

The error/output for this is:

```<code>assertion "cb == jq_util_input_next_input_cb" failed: file "/usr/src/ports/jq/jq-1.5-3.x86_64/src/jq-1.5/util.c", line 371, function: jq_util_input_get_position
</code>```

It shows this output whenever the Curl command can't find a file. How can I silence the JQ error from popping up whenever it can't find a file?

答:
One (not so hot) option would be to redirect STDERR to /dev/null:

```<code>jq  -r '.results[].uri' 2> /dev/null
</code>```

Since there is clearly a possibility of error, a better option might be to break up the pipeline into steps so you can handle different errors as appropriate along the way.

By the way, that assertion indicates there's some kind of bug in jq itself. Would you be able to show us the corresponding output of curl?

Body:
I'm running the following curl command:

installer_to_delete=$(curl -s -u username:password "URL/api/search/dates?dateFields=created&from=${Two_Years_Ago}&today&repos=npm-local-lrn" | jq -r '.results[].uri'|sed 's=/api/storage==')

if [[ $installer_to_delete == "" ]]
then
    echo "No installers found"
else
    for installer in $installer_to_delete
    do
    echo $installer
    done
fi

The error/output for this is:

assertion "cb == jq_util_input_next_input_cb" failed: file "/usr/src/ports/jq/jq-1.5-3.x86_64/src/jq-1.5/util.c", line 371, function: jq_util_input_get_position

It shows this output whenever the Curl command can't find a file. How can I silence the JQ error from popping up whenever it can't find a file?

Body:
One (not so hot) option would be to redirect STDERR to /dev/null:

jq  -r '.results[].uri' 2> /dev/null

Since there is clearly a possibility of error, a better option might be to break up the pipeline into steps so you can handle different errors as appropriate along the way.

By the way, that assertion indicates there's some kind of bug in jq itself. Would you be able to show us the corresponding output of curl?


问:
How can I speed up this SQL update query?
The A table is huge (50+ millions rows) table. So this update method is too slow for MSSQL server. In addition to it runs in a store procedure's while loop. I think this solution is not quite effective.

Has Somebody any good idea to solve this problem?

Thanks!

A table's definition

```<code>CREATE TABLE [dbo].[A](
    [E_NUM] [int] NOT NULL,
    [ID] [char](1) NOT NULL,
    [NUM] [int] NOT NULL,
    [h_out] [smallint] NOT NULL,
    [TAG] [smallint] NOT NULL,
    [TAG1] [smallint] NOT NULL,

 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(
    [E_NUM] ASC,
    [ID] ASC,
    [NUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

B table's definition

```<code>CREATE TABLE [dbo].[B](
    [NUM] [int] NOT NULL,
    [NUM2] [int] NOT NULL,
    [TYPE] [char](1) NOT NULL,
    [R_DATE] [datetime] NULL,
    [Note] [varchar](100) NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(
    [NUM] ASC,
    [NUM2] ASC,
    [TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

UPDATE

```<code> UPDATE A_1
 SET A_1.TAG1 = -1
 FROM A
 INNER JOIN B ON A.NUM = B.NUM
 INNER JOIN A AS A_1 ON B.NUM2 = A_1.NUM
 WHERE A.TAG1 = -1 AND A.TAG = -1 AND B.TYPE='X'
 AND  A.E_num = A_1.E_num AND A.ID=A_1.[ID];
</code>```

答:
The Primary Keys(PKs are clustered by default) in MS SQL Server have very high performance(in compared with Oracle). So using correct PK and avoid updating them is important.

When joining tables it is better to target one table and narrow it by where clause and then use PK to reach records in the other tables. You can find out which table selected(targeted) by MS SQL Server by using execution plan.

I think you must declare a combined index on TAG and TAG1 columns in table A to target the table A. If A.TAG1 = -1 AND A.TAG = -1 criteria narrow down table A correctly for example lower than 10000 rows have this value.

Body:
The A table is huge (50+ millions rows) table. So this update method is too slow for MSSQL server. In addition to it runs in a store procedure's while loop. I think this solution is not quite effective.

Has Somebody any good idea to solve this problem?

Thanks!

A table's definition

CREATE TABLE [dbo].[A](
    [E_NUM] [int] NOT NULL,
    [ID] [char](1) NOT NULL,
    [NUM] [int] NOT NULL,
    [h_out] [smallint] NOT NULL,
    [TAG] [smallint] NOT NULL,
    [TAG1] [smallint] NOT NULL,

 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(
    [E_NUM] ASC,
    [ID] ASC,
    [NUM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

B table's definition

CREATE TABLE [dbo].[B](
    [NUM] [int] NOT NULL,
    [NUM2] [int] NOT NULL,
    [TYPE] [char](1) NOT NULL,
    [R_DATE] [datetime] NULL,
    [Note] [varchar](100) NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(
    [NUM] ASC,
    [NUM2] ASC,
    [TYPE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

UPDATE

 UPDATE A_1
 SET A_1.TAG1 = -1
 FROM A
 INNER JOIN B ON A.NUM = B.NUM
 INNER JOIN A AS A_1 ON B.NUM2 = A_1.NUM
 WHERE A.TAG1 = -1 AND A.TAG = -1 AND B.TYPE='X'
 AND  A.E_num = A_1.E_num AND A.ID=A_1.[ID];


问:
How do you turn a FileSet into a list of Files in a Mojo
I'm writing my first Maven Mojo, in it I'm wanting to take a file set and process all the files it refers to.

In pseudo code what I'd like to do...

```<code>void myCode(org.apache.maven.model.FileSet fileSet) {
    List<java.io.File> files = FileSetTransformer.toFileList(fileSet);
    for (File f : files) {
        doSomething(f);
    }
}
</code>```

So what I'm wanting is the real code for "FileSetTransformer.toFileList", it seems to me like a very common thing to want to do but I can't seem to find out how to do it.

答: See the javadoc for Maven FileSet and use the getDirectory() and getIncludes() methods. This is an example of an existing maven mojo that does something simular. </p>

Body:
I'm writing my first Maven Mojo, in it I'm wanting to take a file set and process all the files it refers to.

In pseudo code what I'd like to do...

void myCode(org.apache.maven.model.FileSet fileSet) {
    List<java.io.File> files = FileSetTransformer.toFileList(fileSet);
    for (File f : files) {
        doSomething(f);
    }
}

So what I'm wanting is the real code for "FileSetTransformer.toFileList", it seems to me like a very common thing to want to do but I can't seem to find out how to do it.


问:
Comparison between two tables
I am trying to pull in an ID number and name from one table that checks to see if the same ID number does not exist in another table. I am getting the error:

Subquery returned more than 1 value.

Below is my query.

```<code>Select Table1.ID,
       Table1.Name
  From Table1
 Where Table1.ID not in ((select (Table2.ID)
                            from Table2 )
                         COLLATE SQL_Latin1_General_CP1_CS_AS)
</code>```

答:
The best performing query for a non-existence test is to ... use NOT-exists.
The worktable does not need to collect all rows of the LEFT JOIN just to PRUNE later using the WHERE clause.  The first existence match aborts the table1 row.

```<code>Select Table1.ID,
       Table1.Name
  From Table1
 Where NOT EXISTS (SELECT *
                   from Table2
                   WHERE Table2.ID = TABLE1.ID)
</code>```

Title: Comparison between two tables

Body:
I am trying to pull in an ID number and name from one table that checks to see if the same ID number does not exist in another table. I am getting the error:

Subquery returned more than 1 value.

Below is my query.

Select Table1.ID,
       Table1.Name
  From Table1
 Where Table1.ID not in ((select (Table2.ID)
                            from Table2 )
                         COLLATE SQL_Latin1_General_CP1_CS_AS)

Body:
The best performing query for a non-existence test is to ... use NOT-exists.
The worktable does not need to collect all rows of the LEFT JOIN just to PRUNE later using the WHERE clause.  The first existence match aborts the table1 row.

Select Table1.ID,
       Table1.Name
  From Table1
 Where NOT EXISTS (SELECT *
                   from Table2
                   WHERE Table2.ID = TABLE1.ID)


问:
When using XElement Value, is it possible to get the non-concatenated text for a parent node?
Say you have an XElement that looks like this

```<code>    <name>
    TESTING
      <given>GIVENNAME2</given>
      <family>FAMILYNAME</family>
    </name>

var descend = elements.ElementAt(i).DescendantsAndSelf();
            foreach (XElement x in descend)
            {
                string g = x.Value;
            }
</code>```

Result for name element is

```<code>    TESTING
      GIVENNAME2FAMILYNAME
</code>```

When I try to get the value of individual elements, it works for children nodes like given and family, but when I try to get the text contained in the parent element, Value returns that text, plus the concatenated text of all the child nodes.   Does anyone know how to get just the text 'TESTING' as a discrete value form the parent node? And ignore the text of the child nodes?

Not only do I need to read, but I need to change the value as well, which is why I need it as a discrete value.

答:
```<code>    /// <summary>
    /// This method is used to get the individual inner value of the specified element.
    /// </summary>
    /// <param name="element">Contains the XElement to retrieve a value.</param>
    /// <returns>Returns only the inner value of the element specified.</returns>
    /// <remarks>
    /// XElement.Value returns a concatenated string of all child element values. This is bad if
    /// only the inner text value of the specified element is required.
    /// </remarks>
    public static string InnerValue(this XElement element)
    {
        // get the last child node of NodeType = Text...
        var textNode = element.Nodes().OfType<XText>().LastOrDefault();

        // return the value of the text node if found
        return textNode != null ? textNode.Value : string.Empty;
    }
</code>```

Body:
Say you have an XElement that looks like this

    <name>
    TESTING
      <given>GIVENNAME2</given>
      <family>FAMILYNAME</family>
    </name>

var descend = elements.ElementAt(i).DescendantsAndSelf();
            foreach (XElement x in descend)
            {
                string g = x.Value;
            }

Result for name element is

    TESTING
      GIVENNAME2FAMILYNAME

When I try to get the value of individual elements, it works for children nodes like given and family, but when I try to get the text contained in the parent element, Value returns that text, plus the concatenated text of all the child nodes.   Does anyone know how to get just the text 'TESTING' as a discrete value form the parent node? And ignore the text of the child nodes?

Not only do I need to read, but I need to change the value as well, which is why I need it as a discrete value.


问:
Kivy: TextInput border radius
I would like to know if it was possible in python & Kivy, to customize TextInput widgets like in HTML/CSS. Is there any way to do that directly into my CustomTextInput(TextInput) class ?

I want my TextInput looks like this:

答:
Of course you can, but it's a bit more complicated in kivy:

test.kv:

```<code>#:import C kivy.utils.get_color_from_hex

<MyTextInput@TextInput>:
    font_size: '14dp'
    background_color: 0,0,0,0
    cursor_color: C('#ffffff')
    canvas.before:
        Color:
            rgba: C('#ffffff')
    canvas.after:
        Color:
            rgb: C('#0f192e')
        Ellipse:
            angle_start:180
            angle_end:360
            pos:(self.pos[0] - self.size[1]/2.0, self.pos[1])
            size: (self.size[1], self.size[1])
        Ellipse:
            angle_start:360
            angle_end:540
            pos: (self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1])
            size: (self.size[1], self.size[1])
        Color:
            rgba: C('#3f92db')
        Line:
            points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]
        Line:
            points: self.pos[0], self.pos[1] + self.size[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1]
        Line:
            ellipse: self.pos[0] - self.size[1]/2.0, self.pos[1], self.size[1], self.size[1], 180, 360
        Line:
            ellipse: self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1], self.size[1], self.size[1], 360, 540

BoxLayout:
    orientation:'vertical'
    BoxLayout:
        size_hint_y: 20
        canvas.before:
            Color:
                rgba: C('#3f92db')
            Rectangle:
                pos:self.pos
                size:self.size
    BoxLayout:
        orientation: 'vertical'
        size_hint_y: 80
        canvas:
            Color:
                rgba: C('#18294a')
            Rectangle:
                pos:self.pos
                size:self.size
        BoxLayout:
            size_hint_y: 10
        BoxLayout:
            size_hint_y: 20
            orientation:'vertical'
            Label:
                size_hint_y: 8
                text: 'Password'
                color: C('#ffffff')
                font_size:'20dp'
                padding: 5,5
                text_size: self.size
                halign: 'center'
                valign: 'center'
            BoxLayout:
                size_hint_y: 8
                BoxLayout:
                    size_hint_x: 25
                BoxLayout:
                    size_hint_x: 50
                    canvas.before:
                        Color:
                            rgba: C('#0f192e')
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    MyTextInput:
                BoxLayout:
                    size_hint_x: 25
        BoxLayout:
            size_hint_y: 10
        BoxLayout:
            size_hint_y: 20
            orientation:'vertical'
            Label:
                size_hint_y: 8
                text: 'Confirm'
                color: C('#ffffff')
                font_size:'20dp'
                padding: 5,5
                text_size: self.size
                halign: 'center'
                valign: 'center'
            BoxLayout:
                size_hint_y: 8
                BoxLayout:
                    size_hint_x: 25
                BoxLayout:
                    size_hint_x: 50
                    canvas.before:
                        Color:
                            rgba: C('#0f192e')
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    MyTextInput:
                BoxLayout:
                    size_hint_x: 25
        BoxLayout:
            size_hint_y: 40
</code>```

python file:

```<code>from kivy.app import App

class TestApp(App):
    pass

if __name__ == '__main__':
    TestApp().run()
</code>```

output:

Title: Kivy: TextInput border radius

Body:
Of course you can, but it's a bit more complicated in kivy:

test.kv:

#:import C kivy.utils.get_color_from_hex

<MyTextInput@TextInput>:
    font_size: '14dp'
    background_color: 0,0,0,0
    cursor_color: C('#ffffff')
    canvas.before:
        Color:
            rgba: C('#ffffff')
    canvas.after:
        Color:
            rgb: C('#0f192e')
        Ellipse:
            angle_start:180
            angle_end:360
            pos:(self.pos[0] - self.size[1]/2.0, self.pos[1])
            size: (self.size[1], self.size[1])
        Ellipse:
            angle_start:360
            angle_end:540
            pos: (self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1])
            size: (self.size[1], self.size[1])
        Color:
            rgba: C('#3f92db')
        Line:
            points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]
        Line:
            points: self.pos[0], self.pos[1] + self.size[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1]
        Line:
            ellipse: self.pos[0] - self.size[1]/2.0, self.pos[1], self.size[1], self.size[1], 180, 360
        Line:
            ellipse: self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1], self.size[1], self.size[1], 360, 540

BoxLayout:
    orientation:'vertical'
    BoxLayout:
        size_hint_y: 20
        canvas.before:
            Color:
                rgba: C('#3f92db')
            Rectangle:
                pos:self.pos
                size:self.size
    BoxLayout:
        orientation: 'vertical'
        size_hint_y: 80
        canvas:
            Color:
                rgba: C('#18294a')
            Rectangle:
                pos:self.pos
                size:self.size
        BoxLayout:
            size_hint_y: 10
        BoxLayout:
            size_hint_y: 20
            orientation:'vertical'
            Label:
                size_hint_y: 8
                text: 'Password'
                color: C('#ffffff')
                font_size:'20dp'
                padding: 5,5
                text_size: self.size
                halign: 'center'
                valign: 'center'
            BoxLayout:
                size_hint_y: 8
                BoxLayout:
                    size_hint_x: 25
                BoxLayout:
                    size_hint_x: 50
                    canvas.before:
                        Color:
                            rgba: C('#0f192e')
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    MyTextInput:
                BoxLayout:
                    size_hint_x: 25
        BoxLayout:
            size_hint_y: 10
        BoxLayout:
            size_hint_y: 20
            orientation:'vertical'
            Label:
                size_hint_y: 8
                text: 'Confirm'
                color: C('#ffffff')
                font_size:'20dp'
                padding: 5,5
                text_size: self.size
                halign: 'center'
                valign: 'center'
            BoxLayout:
                size_hint_y: 8
                BoxLayout:
                    size_hint_x: 25
                BoxLayout:
                    size_hint_x: 50
                    canvas.before:
                        Color:
                            rgba: C('#0f192e')
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    MyTextInput:
                BoxLayout:
                    size_hint_x: 25
        BoxLayout:
            size_hint_y: 40

python file:

from kivy.app import App

class TestApp(App):
    pass

if __name__ == '__main__':
    TestApp().run()

output:


问:
Get GitHub account using StackExchange API
I am trying to use the StackExchange API to retrieve the GitHub link a user has set in his profile.

I am talking about this one:

However I'm not finding methods to retrieve that data. I'm also not sure whether the API offers access to that data.

Here are some documentations I found:

https://api.stackexchange.com/docs/users

https://api.stackexchange.com/2.2/users/?order=desc&sort=reputation&site=stackoverflow

So can I use this API to retrieve the GitHub account of a user?

答:
The StackExchange API does not offer access to that data.

As you already have posted

https://api.stackexchange.com/2.2/users/2411243?site=stackoverflow

is all information you can get from a user.

The official documentation lists all available fields and explains them. A GitHub field is not among them. Here is the complete documentation listing all available methods.

You will need to use different APIs or techniques to retrieve that data.


问:
entitiy framework .Skip not working correctly
i'm trying to make the navigation arrows in jqGrid working.
MVC 3 RC2, Entity Framework 4, .NET Framework 4, jqGrid 3.8.2

The Problem is, that i'm getting not record from 1 to 10, 11 to 20 and so on. It seems that the .skip method is not working correctly.

jqGrid calls the ActionResult with the right parameters.

Maybe you have an idea?

Regards,

float

```<code>    //
    // Post: /Admin/IndexGridData
    // Gibt ein JSON Result mit allen Aufträgen für das jqGrid zurück
    [HttpPost]
    public ActionResult IndexGridData(string sidx, string sord, int page, int rows)
    {

        // Ermittlung der Zusatzinformationen die das Grid anzeigt (Anzahl Aufträge, momentan angezeigte Aufträge
        int start = (page -1) * rows;
        int summeauftraege = _db.Auftrag.Where(x => x.AuftragStatus != "storno").Count();
        int totalPages = (int)Math.Ceiling((float)summeauftraege / (float)rows);

        var auftraege = (from auftrag in _db.Auftrag
                     .Include("KT_AuftragStatus")
                     .Include("KT_Bearbeitungsort")
                     .Include("AuftragPartner")
                         select new
                         {
                             Titel = auftrag.Titel,
                             Auftrag_GUID = auftrag.Auftrag_GUID,
                             Bearbeitungsort = auftrag.KT_Bearbeitungsort.Text,
                             AuftragStatus = auftrag.KT_AuftragStatus.Text,
                         }).Where(x => x.AuftragStatus != "storniert").OrderBy(x => x.Titel)
                     .Skip(start)
                     .Take(rows)
                     .AsEnumerable().ToList();

        // Sortierung des Grids anwenden
        if (sidx == "Titel" && sord == "asc")
        {
            auftraege = auftraege.OrderBy(x => x.Titel).AsEnumerable().ToList();
        }
        else if (sidx == "Titel" && sord == "desc")
        {
            auftraege = auftraege.OrderByDescending(x => x.Titel).AsEnumerable().ToList();
        }else if (sidx == "Bearbeitungsort" && sord == "asc")
        {
            auftraege = auftraege.OrderBy(x => x.Bearbeitungsort).AsEnumerable().ToList();
        }
        else if (sidx == "Bearbeitungsort" && sord == "desc")
        {
            auftraege = auftraege.OrderByDescending(x => x.Bearbeitungsort).AsEnumerable().ToList();
        }
        else if (sidx == "AuftragStatus" && sord == "asc")
        {
            auftraege = auftraege.OrderBy(x => x.AuftragStatus).AsEnumerable().ToList();
        }
        else if (sidx == "AuftragStatus" && sord == "desc")
        {
            auftraege = auftraege.OrderByDescending(x => x.AuftragStatus).AsEnumerable().ToList();
        }

        // Erstellung des JSON Objekts welches die einzelnen Aufträge enthält
        var jsonauftraege = new object[auftraege.Count()];
        for (int i = 0; i < auftraege.Count; i++)
        {
            jsonauftraege[i] = new
            {
                id = auftraege[i].KA_Auftrag_GUID,
                cell = new[] {
                "Details",
                "Bearbeiten",
                (auftraege[i].Titel != null) ? auftraege[i].Titel.ToString(): " ",
               (auftraege[i].Bearbeitungsort != null) ? auftraege[i].Bearbeitungsort.ToString(): " ",
                (auftraege[i].AuftragStatus != null) ? auftraege[i].AuftragStatus.ToString(): " ",
            }
            };
        }

        // Erstellung des JSON Results welches das Grid versteht
        var result = new JsonResult();
        result.Data = new { page = page, records = summeauftraege, rows = jsonauftraege, total = totalPages };

        return Json(result.Data);
    }
</code>```

答: .OrderBy() on the outer query is required to come before .Skip(). As far as I can see, doing it the way you have it should not even work. If it works at all you're probably in object space, not L2E. You must order before you skip or take.

Body:
i'm trying to make the navigation arrows in jqGrid working.
MVC 3 RC2, Entity Framework 4, .NET Framework 4, jqGrid 3.8.2

The Problem is, that i'm getting not record from 1 to 10, 11 to 20 and so on. It seems that the .skip method is not working correctly.

jqGrid calls the ActionResult with the right parameters.

Maybe you have an idea?

Regards,

float

    //
    // Post: /Admin/IndexGridData
    // Gibt ein JSON Result mit allen Aufträgen für das jqGrid zurück
    [HttpPost]
    public ActionResult IndexGridData(string sidx, string sord, int page, int rows)
    {

        // Ermittlung der Zusatzinformationen die das Grid anzeigt (Anzahl Aufträge, momentan angezeigte Aufträge
        int start = (page -1) * rows;
        int summeauftraege = _db.Auftrag.Where(x => x.AuftragStatus != "storno").Count();
        int totalPages = (int)Math.Ceiling((float)summeauftraege / (float)rows);

        var auftraege = (from auftrag in _db.Auftrag
                     .Include("KT_AuftragStatus")
                     .Include("KT_Bearbeitungsort")
                     .Include("AuftragPartner")
                         select new
                         {
                             Titel = auftrag.Titel,
                             Auftrag_GUID = auftrag.Auftrag_GUID,
                             Bearbeitungsort = auftrag.KT_Bearbeitungsort.Text,
                             AuftragStatus = auftrag.KT_AuftragStatus.Text,
                         }).Where(x => x.AuftragStatus != "storniert").OrderBy(x => x.Titel)
                     .Skip(start)
                     .Take(rows)
                     .AsEnumerable().ToList();

        // Sortierung des Grids anwenden
        if (sidx == "Titel" && sord == "asc")
        {
            auftraege = auftraege.OrderBy(x => x.Titel).AsEnumerable().ToList();
        }
        else if (sidx == "Titel" && sord == "desc")
        {
            auftraege = auftraege.OrderByDescending(x => x.Titel).AsEnumerable().ToList();
        }else if (sidx == "Bearbeitungsort" && sord == "asc")
        {
            auftraege = auftraege.OrderBy(x => x.Bearbeitungsort).AsEnumerable().ToList();
        }
        else if (sidx == "Bearbeitungsort" && sord == "desc")
        {
            auftraege = auftraege.OrderByDescending(x => x.Bearbeitungsort).AsEnumerable().ToList();
        }
        else if (sidx == "AuftragStatus" && sord == "asc")
        {
            auftraege = auftraege.OrderBy(x => x.AuftragStatus).AsEnumerable().ToList();
        }
        else if (sidx == "AuftragStatus" && sord == "desc")
        {
            auftraege = auftraege.OrderByDescending(x => x.AuftragStatus).AsEnumerable().ToList();
        }

        // Erstellung des JSON Objekts welches die einzelnen Aufträge enthält
        var jsonauftraege = new object[auftraege.Count()];
        for (int i = 0; i < auftraege.Count; i++)
        {
            jsonauftraege[i] = new
            {
                id = auftraege[i].KA_Auftrag_GUID,
                cell = new[] {
                "Details",
                "Bearbeiten",
                (auftraege[i].Titel != null) ? auftraege[i].Titel.ToString(): " ",
               (auftraege[i].Bearbeitungsort != null) ? auftraege[i].Bearbeitungsort.ToString(): " ",
                (auftraege[i].AuftragStatus != null) ? auftraege[i].AuftragStatus.ToString(): " ",
            }
            };
        }

        // Erstellung des JSON Results welches das Grid versteht
        var result = new JsonResult();
        result.Data = new { page = page, records = summeauftraege, rows = jsonauftraege, total = totalPages };

        return Json(result.Data);
    }


问:
How to check if all inputs are not empty with JQuery in order to show div
I have a form where, after the user answer every question in it, he clicks a button and a div is shown. How can I show a div when all inputs are filled?

The div can ONLY be shown after EVERY FIELD is filled!!

The div is shown when the user clicks the button

答:
Well, I'm not sure what you've tried, but I'd start with something like this. Loop over the inputs of the form, and then check if they're empty. Then you can show or hide your div in a few different ways. This may help get you started.</p>

```<code>$(function(){
    $("form#formID :input").each(function(){
           var input = $(this);
           if (!input.val()){
              alert('empty input');
              return false;
           }
    });
    //do some logic
    $('#target_div).hide();
})
</code>```

Body:
Well, I'm not sure what you've tried, but I'd start with something like this. Loop over the inputs of the form, and then check if they're empty. Then you can show or hide your div in a few different ways. This may help get you started.

$(function(){
    $("form#formID :input").each(function(){
           var input = $(this);
           if (!input.val()){
              alert('empty input');
              return false;
           }
    });
    //do some logic
    $('#target_div).hide();
})


问:
EFCore transaction rollback behavior if process is killed
Currently I have a base class for integration tests using NUnit on a .net Core 2 project (EFCore 2.01).  In this project we create a transaction on setup and do a rollback on tear down to isolate the tests.

```<code>public class BaseTestsWithRollbackPerTest : BaseTests
{
    [SetUp]
    public void Setup()
    {
        this.Transaction = this.ApplicationContext.Database.BeginTransaction();
    }

    [TearDown]
    public void TearDown()
    {
        this.Transaction.Rollback();
    }
}
</code>```

One of my colleges brought up a concern that we may have lingering transactions if someone may to abort a test or shut off their PC/VS2017 hangs etc.

I have checked and the database and XACT_Abort is switched off and this is a long existing database so I may not be able to change that setting.

My question is what is the standard process for EFCore with this? Will it abort the transaction or keep it going?  Are there any settings that I have not been able to find?  Any help would be greatly appreciated.

答: If a transaction is never committed, it will timeout and the SQLServer will perform a rollback. The SQLServer will handle this, not EF.</p>

Body:
Currently I have a base class for integration tests using NUnit on a .net Core 2 project (EFCore 2.01).  In this project we create a transaction on setup and do a rollback on tear down to isolate the tests.

public class BaseTestsWithRollbackPerTest : BaseTests
{
    [SetUp]
    public void Setup()
    {
        this.Transaction = this.ApplicationContext.Database.BeginTransaction();
    }

    [TearDown]
    public void TearDown()
    {
        this.Transaction.Rollback();
    }
}

One of my colleges brought up a concern that we may have lingering transactions if someone may to abort a test or shut off their PC/VS2017 hangs etc.

I have checked and the database and XACT_Abort is switched off and this is a long existing database so I may not be able to change that setting.

My question is what is the standard process for EFCore with this? Will it abort the transaction or keep it going?  Are there any settings that I have not been able to find?  Any help would be greatly appreciated.


问:
ASP.NET grid view does not retain spaces
ASP.NET grid view does not retain spaces and next line created by Enter keys, when loaded from database.

I have a multiline textbox, when I save and load the same text in Grid, the grid removes all spaces and enter key's next line. it loads up all together like the example below.

Multiline text box :

This is a default property that when one presses
Enter key in the textbox the form gets submitted in other words
there is a postback.

So many people asked on forums.
1. How to disable enter key in textbox?

Grid view pulls up like this:

This is a default property that when one presses Enter key in the textbox the form gets submitted in other words there is a postback. So many people asked on forums. 1. How to disable enter key in textbox?

Please suggest how to retain spaces.
Thank you.

答:
It depends how line breaks etc are actually stored. In my case I can use .Replace() inside the gridview on Eval.:

```<code><asp:Label ID="lblOptionNotes" runat="server"
    Text='<%# Eval("OptionNotes").ToString().Replace("\r\n", "<br />") %>'>
</asp:Label>
</code>```

which replaces carriage returns and new lines with html line breaks.

Body:
It depends how line breaks etc are actually stored. In my case I can use .Replace() inside the gridview on Eval.:

<asp:Label ID="lblOptionNotes" runat="server"
    Text='<%# Eval("OptionNotes").ToString().Replace("\r\n", "<br />") %>'>
</asp:Label>

which replaces carriage returns and new lines with html line breaks.


问:
SQL UNION and MERGE
I'm having multiple select statements involving many tables and Joins. All the select statements have the same Headers. I'm trying to combine all this into a single result set. So which approach is better SQL UNION or MERGE?
I know UNION is A+B. So if a column is NULL in Table A and it has a value in TABLE B then UNION will give me two rows right? So if I want to combine all the rows into a single row based on the id should I use MERGE? I have an option to do this in SQL or SSIS.

```<code>SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
</code>```

TableA

```<code>+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
|  1 | AAA  | HeartRate |
|  2 |      | Systolic  |
|  3 |      | Diastolic |
+----+------+-----------+
</code>```

TableB

```<code>+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
+----+------+---------------+
</code>```

Expected Result

```<code>+----+------+---------------+
| ID | Name | VitalName     |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
|  3 |      | Diastolic     |
+----+------+---------------+
</code>```

答:
UNION and MERGE totally different concepts and both not solves your problem. But can use FULL JOIN for making this.

```<code>DECLARE @TableA TABLE (ID INT,  Name VARCHAR(10), VitalName VARCHAR(10))
INSERT INTO @TableA VALUES
(1,'AAA','HeartRate'),
(2,NULL,'Systolic'),
(3,NULL,'Diastolic')

DECLARE @TableB TABLE ( ID INT,  Name VARCHAR(10), VitalReadings VARCHAR(10))

INSERT INTO @TableB VALUES
(1,'AAA','HeartRate'),
(2,'BBB','Systolic')

SELECT
    A.ID,
    COALESCE(A.Name, B.Name) Name,
    COALESCE(A.VitalName, B.VitalReadings) VitalName
FROM
    @TableA A
    FULL JOIN @TableB B ON A.ID = B.ID
</code>```

Result:

```<code>ID          Name       VitalName
----------- ---------- ----------
1           AAA        HeartRate
2           BBB        Systolic
3           NULL       Diastolic
</code>```

Title: SQL UNION and MERGE

Body:
I'm having multiple select statements involving many tables and Joins. All the select statements have the same Headers. I'm trying to combine all this into a single result set. So which approach is better SQL UNION or MERGE?
I know UNION is A+B. So if a column is NULL in Table A and it has a value in TABLE B then UNION will give me two rows right? So if I want to combine all the rows into a single row based on the id should I use MERGE? I have an option to do this in SQL or SSIS.

SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B

TableA

+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
|  1 | AAA  | HeartRate |
|  2 |      | Systolic  |
|  3 |      | Diastolic |
+----+------+-----------+

TableB

+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
+----+------+---------------+

Expected Result

+----+------+---------------+
| ID | Name | VitalName     |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
|  3 |      | Diastolic     |
+----+------+---------------+

Body:
UNION and MERGE totally different concepts and both not solves your problem. But can use FULL JOIN for making this.

DECLARE @TableA TABLE (ID INT,  Name VARCHAR(10), VitalName VARCHAR(10))
INSERT INTO @TableA VALUES
(1,'AAA','HeartRate'),
(2,NULL,'Systolic'),
(3,NULL,'Diastolic')

DECLARE @TableB TABLE ( ID INT,  Name VARCHAR(10), VitalReadings VARCHAR(10))

INSERT INTO @TableB VALUES
(1,'AAA','HeartRate'),
(2,'BBB','Systolic')

SELECT
    A.ID,
    COALESCE(A.Name, B.Name) Name,
    COALESCE(A.VitalName, B.VitalReadings) VitalName
FROM
    @TableA A
    FULL JOIN @TableB B ON A.ID = B.ID

Result:

ID          Name       VitalName
----------- ---------- ----------
1           AAA        HeartRate
2           BBB        Systolic
3           NULL       Diastolic


问:
Why does scanf() in this program fail to get input?
First question, why when I run this program does it fail to get user data regarding "scanf(" %d", &books[ctr]->pages);" ? Instead of getting user data it restarts the loop.

Second question, can someone explain why getchar(); is used at the end of the first loop. As stated in the book it says "Clears newline input" but that doesn't really make sense to me. Does this have anything to do with the problem I am having.

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

struct bookInfo {
        char title[40];
        char auth[25];
        float price;
        int pages;
};

int main()
{
    int ctr;
    struct bookInfo * books[3];

    //get info on books

    for (ctr = 0; ctr < 3; ctr++)
    {
        books[ctr] = (struct bookInfo*)malloc(sizeof(struct bookInfo));
        printf("What is the name of the book #%d?\n", (ctr+1));
        fgets(books[ctr]->title, 40, stdin);
        puts("Who is the author? ");
        fgets(books[ctr]->auth, 25, stdin);
        puts("How much did the book cost? ");
        scanf(" $%f", &books[ctr]->price);
        puts("How many pages are in the book? ");
        scanf(" %d", &books[ctr]->pages);
        getchar();
    }

    //print new header and then loop through and print info

    printf("\n\nHere is the collection of books: \n");
    for (ctr = 0; ctr < 3; ctr++)
    {
        printf("#%d: %s by %s", (ctr + 1), books[ctr]->title, books[ctr]->auth);
        printf("\nIt is %d pages and costs $%.2f", books[ctr]->pages, books[ctr]->price);
        printf("\n\n");
    }

    return(0);
}
</code>```

I expect this program to gather how many pages are in the book before completing the loop and asking for info regarding the book #2. However....

When I run the program this is what I get...

What is the name of the book #1?

good book

Who is the author?   good author

How much did the book cost?

50

How many pages are in the book?

What is the name of the book #2?

bad book

Who is the author?

答:
The problem here is, you never checked the reurn value of scanf()!!

Thus, following the inputs you have shown, for a scanning statement (i.e., the format string) like

```<code> scanf(" $%f", &books[ctr]->price);
</code>```

an input of 50 will cause a matching failure. Thus, scanf() will return failure and the input will then remain in the input buffer to be consumed by the next successful call to scanf(). In your case, the immediate next conversion specification seems to match exactly the input, so you get the behavior that scanf() never waits for the user input.

Related, quoting C11, chapter §7.21.6.2/P6,

A directive that is an ordinary multibyte character is executed by reading the next
  characters of the stream. If any of those characters differ from the ones composing the
  directive, the directive fails and the differing and subsequent characters remain unread. [....]

Body:
First question, why when I run this program does it fail to get user data regarding "scanf(" %d", &books[ctr]->pages);" ? Instead of getting user data it restarts the loop.

Second question, can someone explain why getchar(); is used at the end of the first loop. As stated in the book it says "Clears newline input" but that doesn't really make sense to me. Does this have anything to do with the problem I am having.

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

struct bookInfo {
        char title[40];
        char auth[25];
        float price;
        int pages;
};

int main()
{
    int ctr;
    struct bookInfo * books[3];

    //get info on books

    for (ctr = 0; ctr < 3; ctr++)
    {
        books[ctr] = (struct bookInfo*)malloc(sizeof(struct bookInfo));
        printf("What is the name of the book #%d?\n", (ctr+1));
        fgets(books[ctr]->title, 40, stdin);
        puts("Who is the author? ");
        fgets(books[ctr]->auth, 25, stdin);
        puts("How much did the book cost? ");
        scanf(" $%f", &books[ctr]->price);
        puts("How many pages are in the book? ");
        scanf(" %d", &books[ctr]->pages);
        getchar();
    }

    //print new header and then loop through and print info

    printf("\n\nHere is the collection of books: \n");
    for (ctr = 0; ctr < 3; ctr++)
    {
        printf("#%d: %s by %s", (ctr + 1), books[ctr]->title, books[ctr]->auth);
        printf("\nIt is %d pages and costs $%.2f", books[ctr]->pages, books[ctr]->price);
        printf("\n\n");
    }

    return(0);
}

I expect this program to gather how many pages are in the book before completing the loop and asking for info regarding the book #2. However....

When I run the program this is what I get...

What is the name of the book #1?

good book

Who is the author?   good author

How much did the book cost?

50

How many pages are in the book?

What is the name of the book #2?

bad book

Who is the author?

Body:
The problem here is, you never checked the reurn value of scanf()!!

Thus, following the inputs you have shown, for a scanning statement (i.e., the format string) like

 scanf(" $%f", &books[ctr]->price);

an input of 50 will cause a matching failure. Thus, scanf() will return failure and the input will then remain in the input buffer to be consumed by the next successful call to scanf(). In your case, the immediate next conversion specification seems to match exactly the input, so you get the behavior that scanf() never waits for the user input.

Related, quoting C11, chapter §7.21.6.2/P6,

A directive that is an ordinary multibyte character is executed by reading the next
  characters of the stream. If any of those characters differ from the ones composing the
  directive, the directive fails and the differing and subsequent characters remain unread. [....]


问:
How can I save a key value from external API in django models?
My idea is that I want to create sort of save/like button in my app.

In my services.py and views.py I call and display the API data and
the API result looks like that

```<code>[
    {'rating':4,
     'name': 'Whatever name there is',
     'id': 'whatever ID there is',
    }
]
</code>```

is there a way to save an ID part to my models and how can I implement this? considering that each time I use api, the API result might change.

答:
You don't specify how the model and view look like, but I will improvise

models.py

```<code>class SomeModel(models.Model):
  extra_id = models.InetgerField()
  raiting = models.IntegerField()
  name = models.TextField()
</code>```

views.py

```<code>from app.models import SomeModel

def save_json(request):
  the_json = {
     'rating':4,
     'name': 'Whatever name there is',
     'id': 'whatever ID there is',
  }

  some_model = SomeModel.objects.create(
    extra_id=int(the_json['id']),
    name=the_json['name'],
    raiting=int(the_json['raiting'])
  )

  # and later if you want make operation on model.
  some_model = SomeModel.objects.get(extra_id=759)
  # for example...
  some_model.raiting = 4
  some_model.save()
</code>```

Body:
My idea is that I want to create sort of save/like button in my app.

In my services.py and views.py I call and display the API data and
the API result looks like that

[
    {'rating':4,
     'name': 'Whatever name there is',
     'id': 'whatever ID there is',
    }
]

is there a way to save an ID part to my models and how can I implement this? considering that each time I use api, the API result might change.

Body:
You don't specify how the model and view look like, but I will improvise

models.py

class SomeModel(models.Model):
  extra_id = models.InetgerField()
  raiting = models.IntegerField()
  name = models.TextField()

views.py

from app.models import SomeModel

def save_json(request):
  the_json = {
     'rating':4,
     'name': 'Whatever name there is',
     'id': 'whatever ID there is',
  }

  some_model = SomeModel.objects.create(
    extra_id=int(the_json['id']),
    name=the_json['name'],
    raiting=int(the_json['raiting'])
  )

  # and later if you want make operation on model.
  some_model = SomeModel.objects.get(extra_id=759)
  # for example...
  some_model.raiting = 4
  some_model.save()


问:
Code will not stop when the for loop is broken
I have tried searching for an answer but i have not found anything. I'm making this 2d game in c# where i want the player to be pulled down by the force which increases by gravity each time the function in called (inside a while loop). For some reason the code will not stop when the for loop is broken.</p>

```<code>private void PhysicsLoop()
{
    NowX = Convert.ToInt32(Math.Floor(Convert.ToDecimal(Player.x / 32)));
    NowY = Convert.ToInt32(Math.Floor(Convert.ToDecimal(Player.y / 32)));

    if (Block[NowX,NowY + 2].Collides == false)
    {
        Falling = true;
    }

    if (Falling == true)
    {
        force += Gravity;
        for (int i = 0; i <= force; i++)
        {
            if (Block[NowX, NowY + 2].Collides == true)
            {
                Falling = false;
                break;
            }
            else
            {
                Player.y += 1;
            }
        }
    }
    else
    {

    }
}
</code>```

答:
I'm not sure what platform you're trying to program on, whether it be Console, Winforms, XNA, or whatever else it may be, however, I will try and help you with this.

I noticed you have two values that you kind of set for comparison, these being NowX and NowY. I also notice that you are converting to a decimal, thn back to an Int32.

So my first suggestion that you check is the the objects you are colliding with aren't somehow set to a decimal, float, or double value. Because if they are, then your Collision most likely will never be true, thus getting the infinite loop.

My second thought is that I notice in your if statement that you have the code Player.y += 1 but nowhere do you have something that makes the y value decrease, so maybe the code loop is breaking, just that since the y value is always raised, the loop is always raising it since the first time the Blocks y value might have been 1, and player.y was 2, then the second time around Blocks was still 1 and player.y was 7 or something similar to that.

You might Edit your question and add some more code to the question, like maybe what starts or calls PhysicsLoop, or the Collides method code.

If ever I needed jumping physics in some sort of game, I would follow the same kind of code that was used for good ol' Mario and have an enum with constants to manage the jump physics

```<code>enum JumpValues
{
    float StartingVelocity = 1.0F;
    float StartingToSlow = 0.5F;
    float PeakOfJump = 0.0F;
    float StartingToFall = -0.5F;
    float MaxFallSpeed = -1.0F;
}
</code>```

then use a separate thread to manage the players y value and run through the motions of the enum JumpValues.

I don't know if this helps you or even kind of lets you see where to start looking for errors, but I hope it helps. Good Luck Coding :)

Body:
I have tried searching for an answer but i have not found anything. I'm making this 2d game in c# where i want the player to be pulled down by the force which increases by gravity each time the function in called (inside a while loop). For some reason the code will not stop when the for loop is broken.

private void PhysicsLoop()
{
    NowX = Convert.ToInt32(Math.Floor(Convert.ToDecimal(Player.x / 32)));
    NowY = Convert.ToInt32(Math.Floor(Convert.ToDecimal(Player.y / 32)));

    if (Block[NowX,NowY + 2].Collides == false)
    {
        Falling = true;
    }

    if (Falling == true)
    {
        force += Gravity;
        for (int i = 0; i <= force; i++)
        {
            if (Block[NowX, NowY + 2].Collides == true)
            {
                Falling = false;
                break;
            }
            else
            {
                Player.y += 1;
            }
        }
    }
    else
    {

    }
}

Body:
I'm not sure what platform you're trying to program on, whether it be Console, Winforms, XNA, or whatever else it may be, however, I will try and help you with this.

I noticed you have two values that you kind of set for comparison, these being NowX and NowY. I also notice that you are converting to a decimal, thn back to an Int32.

So my first suggestion that you check is the the objects you are colliding with aren't somehow set to a decimal, float, or double value. Because if they are, then your Collision most likely will never be true, thus getting the infinite loop.

My second thought is that I notice in your if statement that you have the code Player.y += 1 but nowhere do you have something that makes the y value decrease, so maybe the code loop is breaking, just that since the y value is always raised, the loop is always raising it since the first time the Blocks y value might have been 1, and player.y was 2, then the second time around Blocks was still 1 and player.y was 7 or something similar to that.

You might Edit your question and add some more code to the question, like maybe what starts or calls PhysicsLoop, or the Collides method code.

If ever I needed jumping physics in some sort of game, I would follow the same kind of code that was used for good ol' Mario and have an enum with constants to manage the jump physics

enum JumpValues
{
    float StartingVelocity = 1.0F;
    float StartingToSlow = 0.5F;
    float PeakOfJump = 0.0F;
    float StartingToFall = -0.5F;
    float MaxFallSpeed = -1.0F;
}

then use a separate thread to manage the players y value and run through the motions of the enum JumpValues.

I don't know if this helps you or even kind of lets you see where to start looking for errors, but I hope it helps. Good Luck Coding :)


问:
Javascript .match regular expression with reverse quantifier (or parse right to left)
Given a string like such...

```<code>"ABCDEFG"
</code>```

Is it possible to have a quantifier that works in "reverse" so to say?

For instance:

```<code>var foo = "ABCDEFG";
foo.match(/.{1,3}/g);
</code>```

Results in:

```<code>// Array(3) ["ABC", "DEF", "G"]
</code>```

What I'm trying achieve:

```<code>// Array(3) ["A", "BCD", "EFG"]
</code>```

So regardless of the string length, the array is always a representation of the string, with each node 3 characters in length (except possibly the 1st) but always starting at the end of the string.  So the first array item might be 1, 2 or 3 characters long, simply depending on what's "left over".

I have tried using the following to error:

```<code>foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null
</code>```

Thinking perhaps I could use negatives similar to splitting strings, however each of those examples returns null.

I'm assuming this can be done within the pattern somehow and not the quantifier, so I'd like to understand how that would be written with .match().  Or would this require having to write a custom method that would involve other string manipulation in order to accomplish this?

答:
As stated in comments there's no regex or quantifier that matches your string from backwards reading from right to left.

What you can do here is to reverse the string before calling .match() then reverse the matches array:

```<code>var matches = foo.split("").reverse().join("")
    .match(/.{1,3}/g).map(m => m.split("").reverse().join(""))
    .reverse();
</code>```

Explanation:

We use foo.split("").reverse().join("") to reverse the original string.

Then call .match() with this reversed string.

Reverese the matches with .map(m => m.split("").reverse().join("")).

And finally reverse the matches array.

Demo:

var foo = "ABCDEFG";

var matches = foo.split("").reverse().join("").match(/.{1,3}/g).map(m => m.split("").reverse().join("")).reverse();
console.log(matches);```

Body:
Given a string like such...

"ABCDEFG"

Is it possible to have a quantifier that works in "reverse" so to say?

For instance:

var foo = "ABCDEFG";
foo.match(/.{1,3}/g);

Results in:

// Array(3) ["ABC", "DEF", "G"]

What I'm trying achieve:

// Array(3) ["A", "BCD", "EFG"]

So regardless of the string length, the array is always a representation of the string, with each node 3 characters in length (except possibly the 1st) but always starting at the end of the string.  So the first array item might be 1, 2 or 3 characters long, simply depending on what's "left over".

I have tried using the following to error:

foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null

Thinking perhaps I could use negatives similar to splitting strings, however each of those examples returns null.

I'm assuming this can be done within the pattern somehow and not the quantifier, so I'd like to understand how that would be written with .match().  Or would this require having to write a custom method that would involve other string manipulation in order to accomplish this?

Body:
As stated in comments there's no regex or quantifier that matches your string from backwards reading from right to left.

What you can do here is to reverse the string before calling .match() then reverse the matches array:

var matches = foo.split("").reverse().join("")
    .match(/.{1,3}/g).map(m => m.split("").reverse().join(""))
    .reverse();

Explanation:

We use foo.split("").reverse().join("") to reverse the original string.

Then call .match() with this reversed string.

Reverese the matches with .map(m => m.split("").reverse().join("")).

And finally reverse the matches array.

Demo:

var foo = "ABCDEFG";

var matches = foo.split("").reverse().join("").match(/.{1,3}/g).map(m => m.split("").reverse().join("")).reverse();
console.log(matches);


问:
Pandas DataFrame Return Value from Column Index
I have a dataframe that has values of the different column numbers for another dataframe. Is there a way that I can just return the value from the other dataframe instead of just having the column index.

I basically want to match up the index between the Push and df dataframes. The values in the Push dataframe contain what column I want to return from the df dataframe.

Push dataframe:

```<code>    0   1
0   1   2
1   0   3
2   0   3
3   1   3
4   0   2
</code>```

df dataframe:

```<code>    0   1   2   3   4
0   10  11  22  33  44
1   10  11  22  33  44
2   10  11  22  33  44
3   10  11  22  33  44
4   10  11  22  33  44
</code>```

return:

```<code>    0   1
0   11  22
1   10  33
2   10  33
3   11  33
4   10  22
</code>```

答:
You can do it with  np.take ; However this function works on the flattened array. push must be shift like that :

```<code> In [285]: push1 = push.values+np.arange(0,25,5)[:,None]
 In [229]: pd.DataFrame(df.values.take(push1))
</code>```

EDIT

No, I just reinvent np.choose :

```<code>In [24]: df
Out[24]:
    0   1   2   3   4
0   0   1   2   3   4
1  10  11  12  13  14
2  20  21  22  23  24
3  30  31  32  33  34
4  40  41  42  43  44

In [25]: push
Out[25]:
   0  1
0  1  2
1  0  3
2  0  3
3  1  3
4  0  2

In [27]: np.choose(push.T,df).T
Out[27]:
    0   1
0   1   2
1  10  13
2  20  23
3  31  33
4  40  42
</code>```

Body:
I have a dataframe that has values of the different column numbers for another dataframe. Is there a way that I can just return the value from the other dataframe instead of just having the column index.

I basically want to match up the index between the Push and df dataframes. The values in the Push dataframe contain what column I want to return from the df dataframe.

Push dataframe:

    0   1
0   1   2
1   0   3
2   0   3
3   1   3
4   0   2

df dataframe:

    0   1   2   3   4
0   10  11  22  33  44
1   10  11  22  33  44
2   10  11  22  33  44
3   10  11  22  33  44
4   10  11  22  33  44

return:

    0   1
0   11  22
1   10  33
2   10  33
3   11  33
4   10  22

Body:
You can do it with  np.take ; However this function works on the flattened array. push must be shift like that :

 In [285]: push1 = push.values+np.arange(0,25,5)[:,None]
 In [229]: pd.DataFrame(df.values.take(push1))

EDIT

No, I just reinvent np.choose :

In [24]: df
Out[24]:
    0   1   2   3   4
0   0   1   2   3   4
1  10  11  12  13  14
2  20  21  22  23  24
3  30  31  32  33  34
4  40  41  42  43  44

In [25]: push
Out[25]:
   0  1
0  1  2
1  0  3
2  0  3
3  1  3
4  0  2

In [27]: np.choose(push.T,df).T
Out[27]:
    0   1
0   1   2
1  10  13
2  20  23
3  31  33
4  40  42


问:
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?

答:
In Oracle 12.1 and higher, you can solve such problems easily with the match_recognize clause. Link to documentation (with examples) below; my only note about the solution below is that I left the date in DATE data type, especially important if the output is used in further computations. If it isn't, you can wrap within TO_CHAR() with whatever format model is appropriate for your users.

https://docs.oracle.com/database/121/DWHSG/pattern.htm#DWHSG8956

```<code>with
  inputs ( user_id, submitted_dtm ) as (
    select 1, to_date('12/04/2017 1:15', 'mm/dd/yyyy hh24:mi') from dual union all
    select 1, to_date('12/04/2017 5:50', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('11/25/2017 2:00', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('11/25/2017 3:25', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('11/25/2017 6:05', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('10/06/2017 4:00', 'mm/dd/yyyy hh24:mi') from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins below this line. Use your actual table and column names.
select user_id, submitted_dtm, cnt
from   inputs
match_recognize(
  partition by user_id
  order by     submitted_dtm
  measures     trunc(a.submitted_dtm) as submitted_dtm,
               count(*) as cnt
  pattern      ( a b+ )
  define       b as trunc(submitted_dtm) = trunc(a.submitted_dtm)
);

   USER_ID SUBMITTED_DTM              CNT
---------- ------------------- ----------
         1 2017-12-04 00:00:00          2
         2 2017-11-25 00:00:00          3
</code>```

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:
In Oracle 12.1 and higher, you can solve such problems easily with the match_recognize clause. Link to documentation (with examples) below; my only note about the solution below is that I left the date in DATE data type, especially important if the output is used in further computations. If it isn't, you can wrap within TO_CHAR() with whatever format model is appropriate for your users.

https://docs.oracle.com/database/121/DWHSG/pattern.htm#DWHSG8956

with
  inputs ( user_id, submitted_dtm ) as (
    select 1, to_date('12/04/2017 1:15', 'mm/dd/yyyy hh24:mi') from dual union all
    select 1, to_date('12/04/2017 5:50', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('11/25/2017 2:00', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('11/25/2017 3:25', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('11/25/2017 6:05', 'mm/dd/yyyy hh24:mi') from dual union all
    select 2, to_date('10/06/2017 4:00', 'mm/dd/yyyy hh24:mi') from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins below this line. Use your actual table and column names.
select user_id, submitted_dtm, cnt
from   inputs
match_recognize(
  partition by user_id
  order by     submitted_dtm
  measures     trunc(a.submitted_dtm) as submitted_dtm,
               count(*) as cnt
  pattern      ( a b+ )
  define       b as trunc(submitted_dtm) = trunc(a.submitted_dtm)
);

   USER_ID SUBMITTED_DTM              CNT
---------- ------------------- ----------
         1 2017-12-04 00:00:00          2
         2 2017-11-25 00:00:00          3


问:
help with sql server '05 query statement
I'm trying to write a select statement for my autocomplete function(s). I want to take the prefix text from the given text box and pull the first 10 items who's beginning characters matches the prefix. I could probably figure it out on my own, but its getting only the first 10 matches that loses me. Any solutions?</p>

答:
Sql Server is case-insensitive unless you specify that as an installation option. That's a factor of the collation options. Here's an SO question on that topic: SQL Server check case-sensitivity?

To get the top ten results:

SET @searchValue = @searchValue + '%'

SELECT TOP 10 * FROM Items WHERE ItemName LIKE @searchValue ORDER BY ItemName