问:
glibc time function implementation
I am trying to understand the implementation of time() in glibc: https://code.woboq.org/userspace/glibc/sysdeps/unix/sysv/linux/x86/time.c.html#time

If you expand the macros (hovering over them), you get:

```<code>time_t time (time_t *t)
{
  unsigned long int resultvar;
  long int __arg1 = (long int) (t);
  register long int _a1 asm (""rdi"") = __arg1;
  asm volatile ( ""syscall\n\t"" : ""=a"" (resultvar) : ""0"" (201) , ""r"" (_a1) : ""memory"", ""cc"", ""r11"", ""cx"");
  (long int) resultvar;
}
</code>```

The assembly command clearly must return the current time, but I can not understand how. Checking on Intel manual syscall I see it clobbers r11 and cx, the other clobbers are gcc stuff, up to there, I'm fine.

From what I read (https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html) "0" means something is used as both input and output, although I do not get what "(201)" means (I was expecting a variable name, not a number). Any ideas?

I am not sure if _a1 is required to have info, I would assume it can be NULL, so the only real input of the assembly command is that "(201)", but I can't tell how syscall together with 201 gives me access to the internal clock.

Thanks.

P.S.
Bonus question: from what I read on the Intel manual I am under the impression that the only clock available is expected to be on the MoBo rather than be part of the CPU hardware. Have I misunderstood?

答:
This complicated-looking inline assembly just causes the following assembly instructions to be emitted by the compiler:

```<code>mov     eax, 201
syscall
</code>```

So, the entire time function is just:

```<code>time:
    mov     eax, 201
    syscall
    ret
</code>```

The immediate value 201 (0xC9 in hexadecimal notation) is moved into the EAX register, and then the syscall instruction is executed. This instruction does just what the name suggests: it makes a system call. This is basically the way you call platform API functions on Linux. See also section A.2 ("AMD64 Linux Kernel Conventions") of the System V AMD64 ABI.

In brief:

The system call ID number is placed into rax.

(In this case, the number is just 32 bits, so the assembly code places it into eax. The upper 32 bits are implicitly zeroed, saving some bytes in the size of the mov instruction.)

The arguments for the system call, if any, are placed in registers: rdi, rsi, rdx, r10, r8, and r9.

(In this case, for system call #201, there are no arguments that need to be specified, so none of these registers are initialized by the time function.)

After syscall is invoked, its result is contained in rax. Conventionally, negative values (−4095 to −1) indicate an error, corresponding to −errno.

For system calls, the rcx and r11 registers are treated as volatile, which means that their contents are subject to being clobbered. If the caller cares about those values, it needs to preserve them. All other registers' values are saved across the system call.

(This is why the clobbers are there in the extended inline asm syntax.)

There is a reference for 64-bit Linux system calls available here (32-bit Linux system calls are here). You can see that 201 (0xC9) corresponds to sys_time.

sys_time interprets the RDI register as a time_t* value. This code:

```<code>long int __arg1 = (long int) (t);
register long int _a1 asm ("rdi") = __arg1;
</code>```

causes the function's parameter, t, to be stored in the RDI register. That doesn't actually cause any machine instructions to be generated, though, because the System V AMD64 calling convention already passes the first parameter of a function in RDI, so t is already in RDI.

The sys_time system call just fills the pointer it finds in RDI, which is the same as the time function's t argument. It also returns its result (an error code) in RAX, which is always used for the return value of a function under the System V AMD64 calling convention, so no machine instructions are required there, either.

Perhaps more clearly:

```<code># inputs:  RDI is a pointer to time_t that will be filled in
# returns: result is left in RAX
time:
    mov     eax, 201
    syscall
    ret
</code>```

Title: glibc time function implementation

Body:
I am trying to understand the implementation of time() in glibc: https://code.woboq.org/userspace/glibc/sysdeps/unix/sysv/linux/x86/time.c.html#time

If you expand the macros (hovering over them), you get:

time_t time (time_t *t)
{
  unsigned long int resultvar;
  long int __arg1 = (long int) (t);
  register long int _a1 asm (""rdi"") = __arg1;
  asm volatile ( ""syscall\n\t"" : ""=a"" (resultvar) : ""0"" (201) , ""r"" (_a1) : ""memory"", ""cc"", ""r11"", ""cx"");
  (long int) resultvar;
}

The assembly command clearly must return the current time, but I can not understand how. Checking on Intel manual syscall I see it clobbers r11 and cx, the other clobbers are gcc stuff, up to there, I'm fine.

From what I read (https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html) "0" means something is used as both input and output, although I do not get what "(201)" means (I was expecting a variable name, not a number). Any ideas?

I am not sure if _a1 is required to have info, I would assume it can be NULL, so the only real input of the assembly command is that "(201)", but I can't tell how syscall together with 201 gives me access to the internal clock.

Thanks.

P.S.
Bonus question: from what I read on the Intel manual I am under the impression that the only clock available is expected to be on the MoBo rather than be part of the CPU hardware. Have I misunderstood?

Body:
This complicated-looking inline assembly just causes the following assembly instructions to be emitted by the compiler:

mov     eax, 201
syscall

So, the entire time function is just:

time:
    mov     eax, 201
    syscall
    ret

The immediate value 201 (0xC9 in hexadecimal notation) is moved into the EAX register, and then the syscall instruction is executed. This instruction does just what the name suggests: it makes a system call. This is basically the way you call platform API functions on Linux. See also section A.2 ("AMD64 Linux Kernel Conventions") of the System V AMD64 ABI.

In brief:

The system call ID number is placed into rax.

(In this case, the number is just 32 bits, so the assembly code places it into eax. The upper 32 bits are implicitly zeroed, saving some bytes in the size of the mov instruction.)

The arguments for the system call, if any, are placed in registers: rdi, rsi, rdx, r10, r8, and r9.

(In this case, for system call #201, there are no arguments that need to be specified, so none of these registers are initialized by the time function.)

After syscall is invoked, its result is contained in rax. Conventionally, negative values (−4095 to −1) indicate an error, corresponding to −errno.

For system calls, the rcx and r11 registers are treated as volatile, which means that their contents are subject to being clobbered. If the caller cares about those values, it needs to preserve them. All other registers' values are saved across the system call.

(This is why the clobbers are there in the extended inline asm syntax.)

There is a reference for 64-bit Linux system calls available here (32-bit Linux system calls are here). You can see that 201 (0xC9) corresponds to sys_time.

sys_time interprets the RDI register as a time_t* value. This code:

long int __arg1 = (long int) (t);
register long int _a1 asm ("rdi") = __arg1;

causes the function's parameter, t, to be stored in the RDI register. That doesn't actually cause any machine instructions to be generated, though, because the System V AMD64 calling convention already passes the first parameter of a function in RDI, so t is already in RDI.

The sys_time system call just fills the pointer it finds in RDI, which is the same as the time function's t argument. It also returns its result (an error code) in RAX, which is always used for the return value of a function under the System V AMD64 calling convention, so no machine instructions are required there, either.

Perhaps more clearly:

# inputs:  RDI is a pointer to time_t that will be filled in
# returns: result is left in RAX
time:
    mov     eax, 201
    syscall
    ret


来源: stackexchange

问:
Spring forms + JSP: Binding the value of a <select> to a map<String, String> - what am I doing wrong
I'm using spring 3.0.5 and tomcat 7

What I'm doing:

I have created a table of select elements in JSP. Each select is associated with an id in my model, like this:

```<code><form:form commandName="someStuff" method="post" id="peopleForm" onSubmit="return validate('${someStuff}');">

<%-- A bunch of other unrelated stuff here --%>
<table>
    <th>some other info</th>
    <th>please select a name</th>
    <c:forEach var="thisThing" items="${allOfTheThings}">
        <tr>
        <td>some other info here</td>
        <td>
            <form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']"  thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">
                <option value="Please Select One">Please Select One</option>
                <option value="John">John</option>
                <option value="Joe">Joe</option>
                <option value="Stephen">Stephen</option>
                <option value="Mary">Mary</option>
            </form:select >
        </td>
        </tr>
    </c:forEach>
</form:form>
</code>```

and then in my domain object 'someStuff'

I define a map like:

```<code>private Map<String, String> tempNames;

public Map<String, String> getTempNames() {
    return tempNames;
}

public void setTempNames(Map<String, String> tempNames) {
    this.tempNames = tempNames;
}
</code>```

The problem:

If I select values from the dropdown and submit this form, I can put a breakpoint in the controller and see that 'tempNames' has all the correct values in it like,  that I can process and save - which is exactly what i'd expect - so the binding works one way...

However, if 'someStuff' already has values in it, those values are not bound to the dropdowns.

I've tried

Adding a 'value' attribute to the  element itself like:

```<code><form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']" value="tempNames['${thisThing.SomeId}']" thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">
</code>```

and also like this:

```<code><form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']" value="${tempNames[thisThing.SomeId]}" thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">
</code>```

but that second one doesn't seem to even be showing up in the resulting HTML....

答:
I've come across the same issue.
Seems that you have to calculate option's selected flag by yourself:

```<code><form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']"  thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">
        <option value="Please Select One">Please Select One</option>
    <c:choose>
        <c:when test="${tempNames['${thisThing.SomeId}'] == "John"}">
            <option value="John" selected="true">John</option>
        </c:when>
        <c:otherwise>
            <option value="John">John</option>
        </c:otherwise>
    </c:choose>

    ...
</form:select >
</code>```

Please note that <option selected="${tempNames['${thisThing.SomeId}'] == "John"}"> won't work. Browser (at least Chrome) ignore the contents of selected attribute, the only thing that matters is presence/absense of the attribute itself: selected="false" still makes the option selected.

ContentLicense: CC BY-SA 3.0

Body:
I'm using spring 3.0.5 and tomcat 7

What I'm doing:

I have created a table of select elements in JSP. Each select is associated with an id in my model, like this:

<form:form commandName="someStuff" method="post" id="peopleForm" onSubmit="return validate('${someStuff}');">

<%-- A bunch of other unrelated stuff here --%>

    some other info
    please select a name
    <c:forEach var="thisThing" items="${allOfTheThings}">

        some other info here

            <form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']"  thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">
                <option value="Please Select One">Please Select One</option>
                <option value="John">John</option>
                <option value="Joe">Joe</option>
                <option value="Stephen">Stephen</option>
                <option value="Mary">Mary</option>
            </form:select >

    </c:forEach>
</form:form>

and then in my domain object 'someStuff'

I define a map like:

private Map<String, String> tempNames;

public Map<String, String> getTempNames() {
    return tempNames;
}

public void setTempNames(Map<String, String> tempNames) {
    this.tempNames = tempNames;
}

The problem:

If I select values from the dropdown and submit this form, I can put a breakpoint in the controller and see that 'tempNames' has all the correct values in it like,  that I can process and save - which is exactly what i'd expect - so the binding works one way...

However, if 'someStuff' already has values in it, those values are not bound to the dropdowns.

I've tried

Adding a 'value' attribute to the  element itself like:

<form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']" value="tempNames['${thisThing.SomeId}']" thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">

and also like this:

<form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']" value="${tempNames[thisThing.SomeId]}" thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">

but that second one doesn't seem to even be showing up in the resulting HTML....

Body:
I've come across the same issue.
Seems that you have to calculate option's selected flag by yourself:

<form:select id="name_for_thing_${thisThing.SomeId}" path = "tempNames['${thisThing.SomeId}']"  thisThingsId="${thisThing.SomeId}" class="thing_name_selector_class">
        <option value="Please Select One">Please Select One</option>
    <c:choose>
        <c:when test="${tempNames['${thisThing.SomeId}'] == "John"}">
            <option value="John" selected="true">John</option>
        </c:when>
        <c:otherwise>
            <option value="John">John</option>
        </c:otherwise>
    </c:choose>

    ...
</form:select >

Please note that <option selected="${tempNames['${thisThing.SomeId}'] == "John"}"> won't work. Browser (at least Chrome) ignore the contents of selected attribute, the only thing that matters is presence/absense of the attribute itself: selected="false" still makes the option selected.


问:
c++ - order of construction and destruction
I have the following C++ code (VS2013):

```<code>#include <iostream>
using namespace std;
class A {
    int i;
public:
    A(int i) : i(i) {
        cout << "DEFAULT CTOR " << i << endl;
    }
    A(const A &o) : i(o.i) {
        cout << "COPY CTOR " << i << endl;
    }
    ~A() {
        cout << "DTOR " << i << endl;
    }
    friend A f(const A &, A, A *);
};
A f(const A &a, A b, A *c) {
    return *c;
}
int main() {
    f(1, A(2), &A(3));
}
</code>```

It produces the following output:

DEFAULT CTOR 1

DEFAULT CTOR 3

DEFAULT CTOR 2

COPY CTOR 3

DTOR 2

DTOR 3

DTOR 3

DTOR 1

The first 3 are parametric constructors (wrongfuly outputing "DEFAULT CTOR" but that doesn't matter), which are called prior to calling f.

Then, when the return *c; line is run, the copy constructor with value 3 is run, followed by the destruction of the object with value 2.

Finally, at the end of main's scope, the remaining objects (3, 3, 1) are destructed.

I don't understand this behavior, and found no explanation to it.

Can anyone elaborate as to the order of things happening?

Specifically:

Why is the third object &A(3) constructed before the second object A(2)? Does this have anything to do with their creation (the third is by reference, the second is by value), or with the way f is defined (the second  is by value, the third is a pointer)?

When return *c; runs, a copy of the third object is created to be returned.
Then, the only object being destructed before returning is the second object. Again, does this have anything to do with their creation, or with the way f is defined?

Thanks in advance.

答:
Why is the third object &A(3) constructed before the second object A(2)? Does this have anything to do with their creation (the third is by reference, the second is by value), or with the way f is defined (the second is by value, the third is a pointer)?

It happens because the evaluation order of function arguments is left unspecified by the C++ standard. A compiler can evaluate them however it likes. This is the cause of many instances of undefined behavior, when programmers that are unaware of this rely on sequencing that isn't there.

When return *c; runs, a copy of the third object is created to be returned. Then, the only object being destructed before returning is the second object. Again, does this have anything to do with their creation, or with the way f is defined?

Kind of, yes. The A(2) object is created by direct initialization of an argument to the function f. The scope of function parameters is the body of the function. So A(2) goes out of scope the moment the function exits. The other objects have a slightly longer lifetime, because they are created outside the function and are passed by reference/pointer. They exist until the end of the full expression f(1, A(2), &A(3));, so they are destructed later.

Body:
I have the following C++ code (VS2013):

#include <iostream>
using namespace std;
class A {
    int i;
public:
    A(int i) : i(i) {
        cout << "DEFAULT CTOR " << i << endl;
    }
    A(const A &o) : i(o.i) {
        cout << "COPY CTOR " << i << endl;
    }
    ~A() {
        cout << "DTOR " << i << endl;
    }
    friend A f(const A &, A, A *);
};
A f(const A &a, A b, A *c) {
    return *c;
}
int main() {
    f(1, A(2), &A(3));
}

It produces the following output:

DEFAULT CTOR 1

DEFAULT CTOR 3

DEFAULT CTOR 2

COPY CTOR 3

DTOR 2

DTOR 3

DTOR 3

DTOR 1

The first 3 are parametric constructors (wrongfuly outputing "DEFAULT CTOR" but that doesn't matter), which are called prior to calling f.

Then, when the return *c; line is run, the copy constructor with value 3 is run, followed by the destruction of the object with value 2.

Finally, at the end of main's scope, the remaining objects (3, 3, 1) are destructed.

I don't understand this behavior, and found no explanation to it.

Can anyone elaborate as to the order of things happening?

Specifically:

Why is the third object &A(3) constructed before the second object A(2)? Does this have anything to do with their creation (the third is by reference, the second is by value), or with the way f is defined (the second  is by value, the third is a pointer)?

When return *c; runs, a copy of the third object is created to be returned.
Then, the only object being destructed before returning is the second object. Again, does this have anything to do with their creation, or with the way f is defined?

Thanks in advance.


问:
Routing optional parameters in ASP.NET MVC 5
I am creating an ASP.NET MVC 5 application and I have some issues with routing. We are using the attribute Route to map our routes in the web application. I have the following action:

```<code>[Route("{type}/{library}/{version}/{file?}/{renew?}")]
public ActionResult Index(EFileType type,
                          string library,
                          string version,
                          string file = null,
                          ECacheType renew = ECacheType.cache)
{
 // code...
}
</code>```

We only can access this URL if we pass the slash char / in the end of url, like this:

```<code>type/lib/version/file/cache/
</code>```

It works fine but does not work without /, I get a 404 not found error, like this

```<code>type/lib/version/file/cache
</code>```

or this (without optional parameters):

```<code>type/lib/version
</code>```

I would like to access with or without / char at the end of url. My two last parameters are optional.

My RouteConfig.cs is like this:

```<code>public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();
    }
}
</code>```

How can I solve it? Make the slash / be optional too?

答:
```<code>//its working with mvc5
[Route("Projects/{Id}/{Title}")]
public ActionResult Index(long Id, string Title)
{
    return view();
}
</code>```

Body:
I am creating an ASP.NET MVC 5 application and I have some issues with routing. We are using the attribute Route to map our routes in the web application. I have the following action:

[Route("{type}/{library}/{version}/{file?}/{renew?}")]
public ActionResult Index(EFileType type,
                          string library,
                          string version,
                          string file = null,
                          ECacheType renew = ECacheType.cache)
{
 // code...
}

We only can access this URL if we pass the slash char / in the end of url, like this:

type/lib/version/file/cache/

It works fine but does not work without /, I get a 404 not found error, like this

type/lib/version/file/cache

or this (without optional parameters):

type/lib/version

I would like to access with or without / char at the end of url. My two last parameters are optional.

My RouteConfig.cs is like this:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();
    }
}

How can I solve it? Make the slash / be optional too?


问:
Uploading multiple image in dropbox ERROR(too_many_write_operations)
Hi Im trying to upload an image to my dropbox and its working fine its uploading but when i choose a multiple image and upload it to the dropbox some of the images didnt upload and the error says

```<code>"{"error_summary": "too_many_write_operations/..", "error": {"reason": {".tag": "too_many_write_operations"}}}"
</code>```

This is the code im using cordovafiletransfer

```<code>  $cordovaImagePicker.getPictures(optionsSelectImage)
            .then(function(results) {
                console.log(results)
                for (var i = 0; i < results.length; i++) {
                    // console.log('Image URI: ' + results[i]);
                    var image = results[i];
                    var counter = 0;
                    // var filename =  JSON.stringify(results[i].substr(results[i].lastIndexOf('/') + 1));
                    // console.log(filename)
                    var options = {
                        headers: {
                            'Content-Type': 'application/octet-stream',
                            'Authorization': 'Bearer ACCESS TOKEN',
                            "Dropbox-API-Arg": '{"path": "/photo.jpg", "mode": "add","autorename": true,"mute": false}'
                        }
                    }

                    $cordovaFileTransfer.upload('https://content.dropboxapi.com/2/files/upload', image, options)
                        .then(function(result) {
                            // Success!
                            counter++;
                            if (counter != results.length) {
                                $ionicLoading.show({
                                    //Loading Content
                                    template: '<ion-spinner icon="android"></ion-spinner><br><center>Uploading ' + counter + ' /' + results.length + ' to Dropbox</center>'
                                });

                            }

                            // if number of files uploaded in the dropbox == total number  of queued files for uploading
                            else if (counter === results.length) {
                                $ionicLoading.hide();

                            }

                            console.log(result)

                        }, function(err) {

                            // Error
                            console.log(err)

                        }, function(progress) {

                        });
</code>```

I think the for loop is too fast for the process thats why dropbox api cant handle it? how can i slow it down or delay the upload for that

答:
Probably you're uploading all at the same time, a better solution could be upload images by pairs or one by one, chaining the promises like this:</p>

```<code>var promiseChain = Q.fcall(function() {});
results.forEach(function(filename) {
  var promiseLink = function() {
    var def = Q.defer();
    $cordovaFileTransfer.upload('...', filename).then(function(result) {
      // do stuff
      setTimeout(function(){
        def.resolve();
      }, delay)
    });
    return def.promise;
  };
  promiseChain = promiseChain.then(promiseLink);
});

promiseChain();
</code>```

Body:
Hi Im trying to upload an image to my dropbox and its working fine its uploading but when i choose a multiple image and upload it to the dropbox some of the images didnt upload and the error says

"{"error_summary": "too_many_write_operations/..", "error": {"reason": {".tag": "too_many_write_operations"}}}"

This is the code im using cordovafiletransfer

  $cordovaImagePicker.getPictures(optionsSelectImage)
            .then(function(results) {
                console.log(results)
                for (var i = 0; i < results.length; i++) {
                    // console.log('Image URI: ' + results[i]);
                    var image = results[i];
                    var counter = 0;
                    // var filename =  JSON.stringify(results[i].substr(results[i].lastIndexOf('/') + 1));
                    // console.log(filename)
                    var options = {
                        headers: {
                            'Content-Type': 'application/octet-stream',
                            'Authorization': 'Bearer ACCESS TOKEN',
                            "Dropbox-API-Arg": '{"path": "/photo.jpg", "mode": "add","autorename": true,"mute": false}'
                        }
                    }

                    $cordovaFileTransfer.upload('https://content.dropboxapi.com/2/files/upload', image, options)
                        .then(function(result) {
                            // Success!
                            counter++;
                            if (counter != results.length) {
                                $ionicLoading.show({
                                    //Loading Content
                                    template: '<ion-spinner icon="android"></ion-spinner>
Uploading ' + counter + ' /' + results.length + ' to Dropbox'
                                });

                            }

                            // if number of files uploaded in the dropbox == total number  of queued files for uploading
                            else if (counter === results.length) {
                                $ionicLoading.hide();

                            }

                            console.log(result)

                        }, function(err) {

                            // Error
                            console.log(err)

                        }, function(progress) {

                        });

I think the for loop is too fast for the process thats why dropbox api cant handle it? how can i slow it down or delay the upload for that

Body:
Probably you're uploading all at the same time, a better solution could be upload images by pairs or one by one, chaining the promises like this:

var promiseChain = Q.fcall(function() {});
results.forEach(function(filename) {
  var promiseLink = function() {
    var def = Q.defer();
    $cordovaFileTransfer.upload('...', filename).then(function(result) {
      // do stuff
      setTimeout(function(){
        def.resolve();
      }, delay)
    });
    return def.promise;
  };
  promiseChain = promiseChain.then(promiseLink);
});

promiseChain();


问:
R write function to bind column to dataframe
I wrote a function which creates a vector of values via a substring operation on a column of an existing data frame:

```<code>fetchParent <- function(column){
  substr(column,1,regexpr(":", column)-1)
}
</code>```

An example run of this function is:

```<code>fetchParent(task2017.06.28$"Work Product")
</code>```

This returns a vector:

```<code> [1] "DE10946" "DE5909"  "US30637" "US31460" "DE16399" "DE18046" "DE18841" "DE18904" "DE19138"
 [10] "US48201" "US48314" "US48315" "US48316" "US48317 ...
</code>```

I wrote a second function to bind this vector to the original data frame:

```<code>addParent <- function(df){
  df <- cbind(df,fetchParent(df$"Work Product"))
}
</code>```

However, when I run this function:

```<code>addParent(task2017.06.28)
</code>```

the result returns the original without the new column.

What am I missing here?

答:
You have to return the new data.frame:

```<code>addParent <- function(df){
     return(cbind(df,fetchParent(df$"Work Product")))
}
</code>```

In your fetchParent() function this is not neccessary, because you don't assign the output of substr to anything.

So this would work as well:

```<code>addParent <- function(df){
    cbind(df,fetchParent(df$"Work Product"))
}
</code>```

and also

```<code>addParent <- function(df){
    df <- cbind(df,fetchParent(df$"Work Product"))
    return(df)
}
</code>```

Body:
I wrote a function which creates a vector of values via a substring operation on a column of an existing data frame:

fetchParent <- function(column){
  substr(column,1,regexpr(":", column)-1)
}

An example run of this function is:

fetchParent(task2017.06.28$"Work Product")

This returns a vector:

 [1] "DE10946" "DE5909"  "US30637" "US31460" "DE16399" "DE18046" "DE18841" "DE18904" "DE19138"
 [10] "US48201" "US48314" "US48315" "US48316" "US48317 ...

I wrote a second function to bind this vector to the original data frame:

addParent <- function(df){
  df <- cbind(df,fetchParent(df$"Work Product"))
}

However, when I run this function:

addParent(task2017.06.28)

the result returns the original without the new column.

What am I missing here?

Body:
You have to return the new data.frame:

addParent <- function(df){
     return(cbind(df,fetchParent(df$"Work Product")))
}

In your fetchParent() function this is not neccessary, because you don't assign the output of substr to anything.

So this would work as well:

addParent <- function(df){
    cbind(df,fetchParent(df$"Work Product"))
}

and also

addParent <- function(df){
    df <- cbind(df,fetchParent(df$"Work Product"))
    return(df)
}


问:
RabbitMQ flooded by new connections
i'm using java api client with Automatic Recovery but every time it loses the connection, when it reconnects it creates a new connection on a different port, flooding my RabbitMQ with multiple connections.The environment I am working on loses the connection frequently.

Is it possibile use the same connection when it tries to reconnect?

Thanks in advance

答: I guess what you want is a connection pool to setup connection with RabbitMQ. Since you are using java-client, you may what to try CachingConnectionFactory that support channel caching(by default) as well as connection caching(extra setup required). You can check it here: CachingConnectionFactory

Title: RabbitMQ flooded by new connections


问:
Illegal String offset & Trying to get property of non-object (laravel 5.3)
So i've problem to print the result in blade that the data are from controller, so  :

UseController.php :

```<code>     $expertCategory = Category::getCategoryByID($user_id);
     $data = [ 'expertCategory' => $expertCategory ];
     return view('cms.user.edit', $data);
</code>```

Category.php (models) getCategoryByID($user_id) return result array if i dd(expertCategory); in controller, which the result is :

```<code>array:9 [▼
   "id" => 1
   "name" => "Beauty"
   "sequence" => 1
   "background_color" => "ffffff"
   "status" => "Active"
   "created_at" => "2017-06-19 09:41:38"
   "updated_at" => "2017-06-19 09:41:38"
   "icon_filename" => "beauty-icon"
   "iconURL" => array:3 [▼
            "small" => "http://localhost:8000/images/category_icons/small/beauty-icon"
           "medium" => "http://localhost:8000/images/category_icons/medium/beauty-icon"
     ]
]
</code>```

But when i want to print using foreach the result in blade.php with code :

```<code> @foreach($expertCategory as $expertCat)
   {{ $expertCat->id }}
 @endforeach
</code>```

will return error "Trying to get property of non-object "

if i use code like this :

@foreach($expertCategory as $expertCat)
  {{ $expertCat['id'] }}
 @endforeach

it will return : "Illegal string offset 'id'"

anybody can help solve this problem :s ? many thanks !

答:
As $expertCategory is a one dimensional array you are facing this issue

Just Replace this

```<code>$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => $expertCategory ];
return view('cms.user.edit', $data);
</code>```

With

```<code>$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => [$expertCategory] ];
return view('cms.user.edit', $data);
</code>```

Then use

```<code>@foreach($expertCategory as $expertCat)
  {{ $expertCat['id'] }}
@endforeach
</code>```

In your blade it will work for you.

Body:
So i've problem to print the result in blade that the data are from controller, so  :

UseController.php :

     $expertCategory = Category::getCategoryByID($user_id);
     $data = [ 'expertCategory' => $expertCategory ];
     return view('cms.user.edit', $data);

Category.php (models) getCategoryByID($user_id) return result array if i dd(expertCategory); in controller, which the result is :

array:9 [▼
   "id" => 1
   "name" => "Beauty"
   "sequence" => 1
   "background_color" => "ffffff"
   "status" => "Active"
   "created_at" => "2017-06-19 09:41:38"
   "updated_at" => "2017-06-19 09:41:38"
   "icon_filename" => "beauty-icon"
   "iconURL" => array:3 [▼
            "small" => "http://localhost:8000/images/category_icons/small/beauty-icon"
           "medium" => "http://localhost:8000/images/category_icons/medium/beauty-icon"
     ]
]

But when i want to print using foreach the result in blade.php with code :

 @foreach($expertCategory as $expertCat)
   {{ $expertCat->id }}
 @endforeach

will return error "Trying to get property of non-object "

if i use code like this :

@foreach($expertCategory as $expertCat)
  {{ $expertCat['id'] }}
 @endforeach

it will return : "Illegal string offset 'id'"

anybody can help solve this problem :s ? many thanks !

Body:
As $expertCategory is a one dimensional array you are facing this issue

Just Replace this

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => $expertCategory ];
return view('cms.user.edit', $data);

With

$expertCategory = Category::getCategoryByID($user_id);
$data = [ 'expertCategory' => [$expertCategory] ];
return view('cms.user.edit', $data);

Then use

@foreach($expertCategory as $expertCat)
  {{ $expertCat['id'] }}
@endforeach

In your blade it will work for you.


问:
Non-relational database modeling tool?
Hey guys, please recommend some tools you have used succesfully on DW, DataMart, BI an non-relational modeling.
Example for automatic creation of snow-flake Schemas, dimensions and facts tables.
Wich tools makes you sense familiarity with the diagrams and surrogates keys and it will have the option for export or connect to SQL Server 2008.

Thanks

答: Take a look at Powerdesigner from Sybase. Have used it to do a DW for a Central Bank.  Very powerful can layer, i.e. Link dims and facts back to a relational model. Downside is $$$.</p>

ContentLicense: CC BY-SA 2.5

Title: Non-relational database modeling tool?


问:
Unreachable IP Socket Close Time in Windows OS
These codes provide send data via User Datagram Protocol. There are two codes at below. When I use the first code for unreachable Ip address I got the three-second delay.

Please Look New Results Title

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (FIRST CODE)

```<code>using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    using (var client = new UdpClient())
                    {
                        // Please check IP Address, It must be unreachable...
                       // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.141"), 55600);
                      //  client.Connect(ep);
                        client.Send(data, data.Length, "192.168.1.141" , 55600);
                    }
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                    Console.WriteLine("    ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}
</code>```

Test 1(with using): Reachable IP

  Test 2(with using): Unreachable IP

  Output:

  Test1    label1 ---> h:mm:ss         label2 ---> h:mm:ss (Same Time)

  Test2      label1 ---> h:mm:ss        label2 ---> h:mm:ss +3 second

  (No exception)

WireShark Results:

  Test 1(with using) : Reachable Ip --> Data is caught, seen.

  Test 2(with using) : Unreachable IP-> No data.

When I use without "using" blocks, I didn't get the three-second
  delay.

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (SECOND CODE)

```<code>using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    var client = new UdpClient();
                    //Please check IP address, It must be unreachable...
                   // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.41"), 5600);
                   // client.Connect(ep);
                    client.Send(data, data.Length, "192.168.1.141", 55600);

                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                }
                catch (Exception xe)
                {
                    Console.WriteLine(xe.ToString());
                }
                Console.WriteLine("   ");
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}
</code>```

Test 1(without using) : Reachable Ip

  Test 2(without using) : Unreachable Ip

Output:

  Test1     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  Test2     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  (No exception)

WireShark Results:

  Test 1(without using) : Reachable Ip --> Data is caught, seen.

  Test 2(without using) : Unreachable IP-> No data.

What is the mean of that three-second delay?

I am not sure but I think I have to use "using" blocks because if I didn't use the blocks memory usage will increase very high stage.
What is the difference between both codes? Which one is more reliable? Is there any better way? I don't want the three-second delay.

How to decrease three-second delay to zero?

Thanks in advance...

NEW RESULTS

I have tried socket Close/Dispose for unreachable IP with Python Programming
  Language in Windows OS.  I got same result namely three-second delay for unreachable
  IP. But when I try same Python code within Ubuntu 15.10, I didn't get
  the three-second delay.

```<code>import socket
import datetime

IPADDR = '192.168.1.141'
PORTNUM = 5600
PACKETDATA = "f1a525da11f6".encode()

while(True):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.connect((IPADDR, PORTNUM))
    s.send(PACKETDATA)
    print(datetime.datetime.now())
    s.close()
</code>```

答:
Your UdpClient is a disposable object. You should dispose it, before you reconnect.

```<code>            using (var client = new UdpClient()){
                //Please check IP address, It must be unreachable...
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.41"), 5600);
                client.Connect(ep);
                client.Send(data, data.Length);
            }
</code>```

or move the connect outside your loop to reuse the same connection.

Body:
These codes provide send data via User Datagram Protocol. There are two codes at below. When I use the first code for unreachable Ip address I got the three-second delay.

Please Look New Results Title

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (FIRST CODE)

using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    using (var client = new UdpClient())
                    {
                        // Please check IP Address, It must be unreachable...
                       // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.141"), 55600);
                      //  client.Connect(ep);
                        client.Send(data, data.Length, "192.168.1.141" , 55600);
                    }
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                    Console.WriteLine("    ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}

Test 1(with using): Reachable IP

  Test 2(with using): Unreachable IP

  Output:

  Test1    label1 ---> h:mm:ss         label2 ---> h:mm:ss (Same Time)

  Test2      label1 ---> h:mm:ss        label2 ---> h:mm:ss +3 second

  (No exception)

WireShark Results:

  Test 1(with using) : Reachable Ip --> Data is caught, seen.

  Test 2(with using) : Unreachable IP-> No data.

When I use without "using" blocks, I didn't get the three-second
  delay.

JUST OPEN NEW C# CONSOLE APP AND PASTE THESE CODES IN IT. (SECOND CODE)

using System;
using System.Net;
using System.Net.Sockets;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = { 1, 20, 60, 44, 244 };
            while (true)
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                try
                {
                    var client = new UdpClient();
                    //Please check IP address, It must be unreachable...
                   // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.41"), 5600);
                   // client.Connect(ep);
                    client.Send(data, data.Length, "192.168.1.141", 55600);

                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                }
                catch (Exception xe)
                {
                    Console.WriteLine(xe.ToString());
                }
                Console.WriteLine("   ");
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

Test 1(without using) : Reachable Ip

  Test 2(without using) : Unreachable Ip

Output:

  Test1     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  Test2     label1 ---> h:mm:ss (Same Time)      label2 ---> h:mm:ss (Same Time)

  (No exception)

WireShark Results:

  Test 1(without using) : Reachable Ip --> Data is caught, seen.

  Test 2(without using) : Unreachable IP-> No data.

What is the mean of that three-second delay?

I am not sure but I think I have to use "using" blocks because if I didn't use the blocks memory usage will increase very high stage.
What is the difference between both codes? Which one is more reliable? Is there any better way? I don't want the three-second delay.

How to decrease three-second delay to zero?

Thanks in advance...

NEW RESULTS

I have tried socket Close/Dispose for unreachable IP with Python Programming
  Language in Windows OS.  I got same result namely three-second delay for unreachable
  IP. But when I try same Python code within Ubuntu 15.10, I didn't get
  the three-second delay.

import socket
import datetime

IPADDR = '192.168.1.141'
PORTNUM = 5600
PACKETDATA = "f1a525da11f6".encode()

while(True):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.connect((IPADDR, PORTNUM))
    s.send(PACKETDATA)
    print(datetime.datetime.now())
    s.close()

Body:
Your UdpClient is a disposable object. You should dispose it, before you reconnect.

            using (var client = new UdpClient()){
                //Please check IP address, It must be unreachable...
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.41"), 5600);
                client.Connect(ep);
                client.Send(data, data.Length);
            }

or move the connect outside your loop to reuse the same connection.


问:
Change selector in match when selector is a mutable reference
I want to change enum variant based on some properties of the current enum variant in Iterator::next. I have two attempts, neither of which compile:

```<code>enum Test {
    A(Vec<usize>),
    B,
}

impl<'a> Iterator for Test {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        // attempt 1
        if let Test::A(ref a) = *self {
            if a.len() == 0 {
                *self = Test::B; // doesn't work because a is borrowed
            };
        }

        // attempt 2
        *self = match *self {
            Test::A(ref a) if a.len() == 0 => Test::B,
            _ => *self, // cannot move out of borrowed context
        };
        None
    }
}

fn main() {}
</code>```

My second attempt does work if I am not working with references in the selector:

```<code>let mut a = Test::A(vec![]);
a = match a {
    Test::A(ref a) if a.len() == 0 => Test::B,
    _ => a,
};
</code>```

This question is related to Is there a way to use match() in rust when modifying the selector?, but the solution proposed there is not generic: it only works if the same function is executed in both branches.

What is the Rustacean way to achieve my goal?

答:
Since the condition is not very readable when put inside an if let / match block, I would just use a helper function to test for it:

```<code>impl Test {
    fn is_empty_a(&self) -> bool {
        if let Test::A(ref a) = *self {
            a.len() == 0
        } else {
            false
        }
    }
}
</code>```

And then there shouldn't be any borrowing issues:

```<code>impl<'a> Iterator for Test {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.is_empty_a() {
            *self = Test::B;
        }
        None
    }
}
</code>```

Body:
I want to change enum variant based on some properties of the current enum variant in Iterator::next. I have two attempts, neither of which compile:

enum Test {
    A(Vec<usize>),
    B,
}

impl<'a> Iterator for Test {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        // attempt 1
        if let Test::A(ref a) = *self {
            if a.len() == 0 {
                *self = Test::B; // doesn't work because a is borrowed
            };
        }

        // attempt 2
        *self = match *self {
            Test::A(ref a) if a.len() == 0 => Test::B,
            _ => *self, // cannot move out of borrowed context
        };
        None
    }
}

fn main() {}

My second attempt does work if I am not working with references in the selector:

let mut a = Test::A(vec![]);
a = match a {
    Test::A(ref a) if a.len() == 0 => Test::B,
    _ => a,
};

This question is related to Is there a way to use match() in rust when modifying the selector?, but the solution proposed there is not generic: it only works if the same function is executed in both branches.

What is the Rustacean way to achieve my goal?

Body:
Since the condition is not very readable when put inside an if let / match block, I would just use a helper function to test for it:

impl Test {
    fn is_empty_a(&self) -> bool {
        if let Test::A(ref a) = *self {
            a.len() == 0
        } else {
            false
        }
    }
}

And then there shouldn't be any borrowing issues:

impl<'a> Iterator for Test {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.is_empty_a() {
            *self = Test::B;
        }
        None
    }
}


问:
How to make revolution slider text selectable?
I have a a problem with the revolution slider, I want to make the text(layer) I add on the revolution slider to be hoverable/selectable if this are the correct terms. I have a mobile number and I want people to be able to copy it if they want, but unfortunately if they can't select it, it's not possible.

Is it possible? If yes, hope someone can tell me how to do it, I wasn't able to find anywhere on the internet this question.

答:
I asked the support. Just add this to your Custom CSS of the Slider</p>

```<code>.tp-caption.tp-layer-selectable{
-webkit-user-select: text !important; /* Chrome, Opera, Safari */
-moz-user-select: text !important; /* Firefox 2+ */
-ms-user-select: text !important; /* IE 10+ */
user-select: text !important; /* Standard syntax */
}
</code>```

Body:
I asked the support. Just add this to your Custom CSS of the Slider

.tp-caption.tp-layer-selectable{
-webkit-user-select: text !important; /* Chrome, Opera, Safari */
-moz-user-select: text !important; /* Firefox 2+ */
-ms-user-select: text !important; /* IE 10+ */
user-select: text !important; /* Standard syntax */
}


问:
Is it possible to generate PDF using jQuery?
I am using Ajax functionality to retrieve my content and I need to export PDF on success of jQuery.ajax(). How can I do that?

答: jQuery cannot (because JavaScript cannot) create a PDF from data, no...it can get one from your server (like any other request), but it cannot generate one.  JavaScript simply doesn't have a mechanism (though there are some HTML5 options being implemented now) to create/save a file that works cross-browser, especially a binary file.


问:
Pandas related error when generating heatmap with Bokeh
I'm trying to reproduce this heatmap but I keep getting the following error:

AttributeError: 'pandas._libs.interval.Interval' object has no attribute 'split'

I'm running pandas version 0.20.2 and bokeh version 0.12.5.

I've found someone who has the same issue in this post but wasn't able to find a fix.

答: Apparently this is a known issue due to recent changes made to pandas. Running pandas version before 0.20 gets rid of the error.</p>


问:
When trying to open up/run eclipse, I get the "Java was started but returned exit code"
I've just started to learn Java and I'm encountering a problem in starting Eclipse. It says:

Java was started but returned exit code = 13

and a bit more. Please help me find a solution, thanks!

答:
Your issue might possibly get solved by one of the following:

Create an environment variable to Windows properties variable name = PATH variable value = C:\Program Files\Java\jdk1.7.0_02\bin, not to C:\Program Files (x86)\Java\jre7\bin.

Program Files (x86) is the folder where 64-bit Windows places 32-bit programs. Program Files is the folder where 64-bit Windows places 64-bit programs. Your version of Eclipse might be 64-bit while the version of Java might be 32-bit, or vice-versa

Specify the JVM path in eclipse.ini


问:
Linq - Is there are way to build up a linq statement from several snippets of linq
I have several methods that use similar linq statements but different enough for them to be in their own methods. So say, for the sake of arguemnt, I had the following linq snippet which is repeated across all methods (the real snippets would be much longer than this):

```<code>        where su.ObjId == serviceUserId
        where cl.StaffMemberId == staffMemberId
</code>```

If I was working in SQL I could just contatenate the repeated SQL as follows:

```<code>private string GetRepeatedSql()
{
 return "where su.ObjId = serviceUserId and cl.StaffMemberId = staffMemberId";
}

private void DoSomething()
{
 string mySql = "Select * from ...... lots of sql .." + GetRepeatedSql() + ".. some more sql";
}
</code>```

(Usual health warnings around contatenating SQL string together noted).

Is there something equivalent in Linq? I'm sick of having to make changes in several places - this seems to contravene the DRY principle.

Thanks!

答:
You can use PredicateBuilder to do this:

The Albahari one here is one I've used recently although there are others around:
http://www.albahari.com/nutshell/predicatebuilder.aspx

Body:
I have several methods that use similar linq statements but different enough for them to be in their own methods. So say, for the sake of arguemnt, I had the following linq snippet which is repeated across all methods (the real snippets would be much longer than this):

        where su.ObjId == serviceUserId
        where cl.StaffMemberId == staffMemberId

If I was working in SQL I could just contatenate the repeated SQL as follows:

private string GetRepeatedSql()
{
 return "where su.ObjId = serviceUserId and cl.StaffMemberId = staffMemberId";
}

private void DoSomething()
{
 string mySql = "Select * from ...... lots of sql .." + GetRepeatedSql() + ".. some more sql";
}

(Usual health warnings around contatenating SQL string together noted).

Is there something equivalent in Linq? I'm sick of having to make changes in several places - this seems to contravene the DRY principle.

Thanks!


问:
How to set proxy host on HttpClient request in Java
I want to set proxy before sending HttpClient request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to do that.

Curl command:

```<code>**curl -I -x IP:80  URL**
</code>```

Code change done in java file:

```<code>HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
</code>```

With above code changes in my java file I am getting below error :

```<code>java.net.ConnectException: Connection refused (Connection refused)
</code>```

Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.

答:
A full example is given in this tutorial: How do I setting a proxy for HttpClient?

```<code>package org.kodejava.example.commons.httpclient;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.IOException;

public class HttpGetProxy {
    private static final String PROXY_HOST = "proxy.host.com";
    private static final int PROXY_PORT = 8080;

    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("https://kodejava.org");

        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(PROXY_HOST, PROXY_PORT);

        String username = "guest";
        String password = "s3cr3t";
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

        client.getState().setProxyCredentials(authScope, credentials);

        try {
            client.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                String response = method.getResponseBodyAsString();
                System.out.println("Response = " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}
</code>```

For this, you need to add a jar file: http://repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar

Complete Example of a Apache HttpClient 4.1, setting proxy can be found below

```<code>HttpHost proxy = new HttpHost("ip address",port number);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param name", param));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
HttpResponse response = httpclient.execute(httpost);

HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
InputStream in = entity.getContent();
httpclient.getConnectionManager().shutdown();
</code>```

Resource Link: https://stackoverflow.com/a/4957144

For other version like 4.3 or 4.3+, you can go through this SO answer: Apache HttpClient 4.1 - Proxy Authentication

Body:
I want to set proxy before sending HttpClient request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to do that.

Curl command:

**curl -I -x IP:80  URL**

Code change done in java file:

HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));

With above code changes in my java file I am getting below error :

java.net.ConnectException: Connection refused (Connection refused)

Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.

Body:
A full example is given in this tutorial: How do I setting a proxy for HttpClient?

package org.kodejava.example.commons.httpclient;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.IOException;

public class HttpGetProxy {
    private static final String PROXY_HOST = "proxy.host.com";
    private static final int PROXY_PORT = 8080;

    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("https://kodejava.org");

        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(PROXY_HOST, PROXY_PORT);

        String username = "guest";
        String password = "s3cr3t";
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

        client.getState().setProxyCredentials(authScope, credentials);

        try {
            client.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                String response = method.getResponseBodyAsString();
                System.out.println("Response = " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}

For this, you need to add a jar file: http://repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar

Complete Example of a Apache HttpClient 4.1, setting proxy can be found below

HttpHost proxy = new HttpHost("ip address",port number);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param name", param));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
HttpResponse response = httpclient.execute(httpost);

HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
InputStream in = entity.getContent();
httpclient.getConnectionManager().shutdown();

Resource Link: https://stackoverflow.com/a/4957144

For other version like 4.3 or 4.3+, you can go through this SO answer: Apache HttpClient 4.1 - Proxy Authentication


问:
Which application mode should I use in Azure Notification Hubs for Testflight betas?
I am using Azure Notification Hubs for sending notifications.
It worked fine when I tried it a few times on my development iOS device.

But now I want to distribute the app to testers via iTunes Connect / Test Flight and the notifications have stopped working.

I am unsure as to which application mode in Azure Notification Hubs that is the correct to use with Test Flight betas? Sandbox or Production?
I have tried both without any luck.

This is for a Xamarin Forms app and I am using V4 of the Azure Mobile Client. Is there anywhere I need to disable sandbox mode in the app itself?

I am currently registering using this bit of code:

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    if (deviceToken != null)
        App.Client.GetPush().RegisterAsync(deviceToken);
}
```

答:
So it started working "by itself" after a little while.
I chose Production for the Test Flight betas and there was no notifications coming through.
After waiting an hour or so it seemed to fix itself - now notifications are coming through just fine.

So maybe the lesson is when you change from Sandbox to Production you need to wait a bit before things work again.


问:
How to run cucumber/selenium tests in Docker?
I am struggling to run my cucumber tests from a Docker image.

Here is my setup:

I use OSX with XQuartz to run an X11 session

I use an Ubuntu 14 Vagrant image for development where I forward my X11 session

I am trying to run a docker image with Firefox that will use my XQuartz session for display

So far, I managed to start Firefox with the following setup:

```<code># Dockerfile
FROM ubuntu:14.04

RUN apt-get update && apt-get install -y firefox

# Replace 1000 with something appropriate ;)
RUN export uid=1000 gid=1000 && \
     mkdir -p /home/developer && \
     echo "developer:x:${uid}:${gid}:Developer,,,:/home/dev:/bin/bash" >> /etc/passwd && \
     echo "developer:x:${uid}:" >> /etc/group && \
     echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \
     chmod 0440 /etc/sudoers.d/developer && \
     chown ${uid}:${gid} -R /home/developer

USER developer
ENV HOME /home/developer
CMD /usr/bin/firefox
</code>```

I can start Firefox with --net=host from my Vagrant machine:

```<code>docker build -t firefox .
docker run --net=host -ti --rm -e DISPLAY=$DISPLAY -v $HOME/.Xauthority:/home/developer/.Xauthority -v /tmp/.X11-unix:/tmp/.X11-unix:rw firefox:latest
</code>```

But this is not ideal because I can't link other containers to my machine in the docker-compose.yml file. Ideally, I would like to run my docker machine without --net=host like this:

```<code>docker build -t firefox .
docker run -ti --rm -e DISPLAY=$DISPLAY -v $HOME/.Xauthority:/home/developer/.Xauthority -v /tmp/.X11-unix:/tmp/.X11-unix:rw firefox:latest
</code>```

But I get the following error:

```<code>error: XDG_RUNTIME_DIR not set in the environment.
Error: cannot open display: localhost:10.0
</code>```

Please help :)

答:
You could simply use elgalu/docker-selenium to avoid dealing with what's already solved for you, and maintained:

```<code>docker run --rm -ti --net=host --pid=host --name=grid \
   -e SELENIUM_HUB_PORT=4444 -e TZ="US/Pacific" \
   -v /dev/shm:/dev/shm --privileged elgalu/selenium
</code>```

If you need advanced features like a dashboard with video recording for example, or live preview, you can use Zalenium and start it with:

```<code>curl -sSL https://raw.githubusercontent.com/dosel/t/i/p | bash -s start -i
</code>```

Body:
I am struggling to run my cucumber tests from a Docker image.

Here is my setup:

I use OSX with XQuartz to run an X11 session

I use an Ubuntu 14 Vagrant image for development where I forward my X11 session

I am trying to run a docker image with Firefox that will use my XQuartz session for display

So far, I managed to start Firefox with the following setup:

# Dockerfile
FROM ubuntu:14.04

RUN apt-get update && apt-get install -y firefox

# Replace 1000 with something appropriate ;)
RUN export uid=1000 gid=1000 && \
     mkdir -p /home/developer && \
     echo "developer:x:${uid}:${gid}:Developer,,,:/home/dev:/bin/bash" >> /etc/passwd && \
     echo "developer:x:${uid}:" >> /etc/group && \
     echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \
     chmod 0440 /etc/sudoers.d/developer && \
     chown ${uid}:${gid} -R /home/developer

USER developer
ENV HOME /home/developer
CMD /usr/bin/firefox

I can start Firefox with --net=host from my Vagrant machine:

docker build -t firefox .
docker run --net=host -ti --rm -e DISPLAY=$DISPLAY -v $HOME/.Xauthority:/home/developer/.Xauthority -v /tmp/.X11-unix:/tmp/.X11-unix:rw firefox:latest

But this is not ideal because I can't link other containers to my machine in the docker-compose.yml file. Ideally, I would like to run my docker machine without --net=host like this:

docker build -t firefox .
docker run -ti --rm -e DISPLAY=$DISPLAY -v $HOME/.Xauthority:/home/developer/.Xauthority -v /tmp/.X11-unix:/tmp/.X11-unix:rw firefox:latest

But I get the following error:

error: XDG_RUNTIME_DIR not set in the environment.
Error: cannot open display: localhost:10.0

Please help :)

Body:
You could simply use elgalu/docker-selenium to avoid dealing with what's already solved for you, and maintained:

docker run --rm -ti --net=host --pid=host --name=grid \
   -e SELENIUM_HUB_PORT=4444 -e TZ="US/Pacific" \
   -v /dev/shm:/dev/shm --privileged elgalu/selenium

If you need advanced features like a dashboard with video recording for example, or live preview, you can use Zalenium and start it with:

curl -sSL https://raw.githubusercontent.com/dosel/t/i/p | bash -s start -i


问:
Doubles decimal separator WPF
Using a TextBox in WPF I have the problem that if I use ',' instead of '.' every time I try to get the value, the text inside the TextBox is transformed with the same number without comma..

How can I disable this automatic transformation?

```<code><TextBox
    x:Name="XValue"
    Text="{Binding XInitValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    Width="80" VerticalAlignment="Center"
    TextChanged="XValue_TextChanged"
</TextBox>

private void XValue_TextChanged(object sender, TextChangedEventArgs e)
{
    double a = XInitValue;
}
</code>```

答:
I solved it using an converter</p>

```<code>public class DecimalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ".")
                return value.ToString().Replace(",", ".");
            else
                return value.ToString().Replace(".", ",");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ".")
                return value.ToString().Replace(".", ",");
            else
                return value.ToString().Replace(",", ".");
        }

    }
</code>```

Title: Doubles decimal separator WPF

Body:
Using a TextBox in WPF I have the problem that if I use ',' instead of '.' every time I try to get the value, the text inside the TextBox is transformed with the same number without comma..

How can I disable this automatic transformation?

<TextBox
    x:Name="XValue"
    Text="{Binding XInitValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    Width="80" VerticalAlignment="Center"
    TextChanged="XValue_TextChanged"
</TextBox>

private void XValue_TextChanged(object sender, TextChangedEventArgs e)
{
    double a = XInitValue;
}

Body:
I solved it using an converter

public class DecimalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ".")
                return value.ToString().Replace(",", ".");
            else
                return value.ToString().Replace(".", ",");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ".")
                return value.ToString().Replace(".", ",");
            else
                return value.ToString().Replace(",", ".");
        }

    }


问:
How can I decompile Perl 6?
We're supposed to be able to do this somehow. I think I've seen it somewhere, but I can't find what I think I remember. Mostly I want to see how the compiler interprets code.

Along with decompiling, is there a way to watch what it's doing as it compiles? I think seeing what's it's trying to do and where might be easier than trying to understand some of its error messages. And, decompiling a program can undo all the shorthand and cleverness to elucidate what's actually happening.

答:
I'm not sure why you would want to do it. Also, the compilation result is backend dependent, and you did not specify a backend. Anyway, with the --target= parameter, you can get intermediate results. The most useful are:

```<code>$ perl6 --target=parse -e 'say "foo"'
- statementlist: say "foo"
  - statement: 1 matches
    - EXPR: say "foo"
      - args:  "foo"
        - arglist: "foo"
          - EXPR: "foo"
            - value: "foo"
              - quote: "foo"
                - nibble: foo
      - longname: say
        - name: say
          - identifier: say
          - morename:  isa NQPArray
        - colonpair:  isa NQPArray
</code>```

--target=parse shows the immediate result of the parse.

```<code>$ perl6 --target=ast -e 'say "foo"'
- QAST::CompUnit  :W<?> :UNIT<?>
  [pre_deserialize]
    - QAST::Stmt
      - QAST::Stmt
        - QAST::Op(loadbytecode)
          - QAST::VM
            [jvm]
              - QAST::SVal(ModuleLoader.class)
            [moar]
              - QAST::SVal(ModuleLoader.moarvm)
        - QAST::Op(callmethod load_module)
*snip*
</code>```

--target=ast shows the Abstract Syntax Trees.

```<code>$ perl6 --target=mast -e 'say "foo"'
MAST::Frame name<<unit-outer>>, cuuid<2>
  Local types: 0<obj>, 1<obj>, 2<obj>, 3<obj>,
  Outer: <none>
  Instructions:
  [0] MAST::Op getcode
    MAST::Local index<3>
    MAST::Frame name<<unit>>, cuuid<1>
  [1] MAST::Op capturelex
    MAST::Local index<3>
  [2] MAST::Op getcode
    MAST::Local index<1>
    MAST::Frame name<<unit>>, cuuid<1>
  [3] MAST::Op takeclosure
*snip*
</code>```

And --target=mast shows the actual byte code that is being generated, in this case for the MoarVM backend.

Title: How can I decompile Perl 6?

Body:
I'm not sure why you would want to do it. Also, the compilation result is backend dependent, and you did not specify a backend. Anyway, with the --target= parameter, you can get intermediate results. The most useful are:

$ perl6 --target=parse -e 'say "foo"'
- statementlist: say "foo"
  - statement: 1 matches
    - EXPR: say "foo"
      - args:  "foo"
        - arglist: "foo"
          - EXPR: "foo"
            - value: "foo"
              - quote: "foo"
                - nibble: foo
      - longname: say
        - name: say
          - identifier: say
          - morename:  isa NQPArray
        - colonpair:  isa NQPArray

--target=parse shows the immediate result of the parse.

$ perl6 --target=ast -e 'say "foo"'
- QAST::CompUnit  :W<?> :UNIT<?>
  [pre_deserialize]
    - QAST::Stmt
      - QAST::Stmt
        - QAST::Op(loadbytecode)
          - QAST::VM
            [jvm]
              - QAST::SVal(ModuleLoader.class)
            [moar]
              - QAST::SVal(ModuleLoader.moarvm)
        - QAST::Op(callmethod load_module)
*snip*

--target=ast shows the Abstract Syntax Trees.

$ perl6 --target=mast -e 'say "foo"'
MAST::Frame name<<unit-outer>>, cuuid<2>
  Local types: 0<obj>, 1<obj>, 2<obj>, 3<obj>,
  Outer: <none>
  Instructions:
  [0] MAST::Op getcode
    MAST::Local index<3>
    MAST::Frame name<<unit>>, cuuid<1>
  [1] MAST::Op capturelex
    MAST::Local index<3>
  [2] MAST::Op getcode
    MAST::Local index<1>
    MAST::Frame name<<unit>>, cuuid<1>
  [3] MAST::Op takeclosure
*snip*

And --target=mast shows the actual byte code that is being generated, in this case for the MoarVM backend.


问:
How do i execute a logic after Hangfire job has succeded, i mean the Succeded state?
I tried these action job filter methods, but what I actually need is, I want to call a method after the Job id has been executed successfully or it has internally failed after it gave the Job id.</p>

```<code>public void OnStateElection(ElectStateContext context)
        {
            //Log event
        }

        public void OnCreating(CreatingContext filterContext)
        {
            //Log event
        }

        public void OnCreated(CreatedContext filterContext)
        {
            //Log event
        }

        public void OnPerforming(PerformingContext context)
        {
            //Log event
        }

        public void OnPerformed(PerformedContext context)
        {
            //Log event
        }

        public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            //Log event
        }

        public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            //Log event
        }
</code>```

答:
Hangfire can build an execution chains. If you want to schedule next job after first one succeed, you need to use ContinueWith(string parentId, Expression<Action> methodCall, JobContinuationOptions options); with the JobContinuationOptions.OnlyOnSucceededState.

More detailed information you can find here: https://indexoutofrange.com/Don%27t-do-it-now!-Part-5.-Hangfire-job-continuation,-ContinueWith/

Body:
I tried these action job filter methods, but what I actually need is, I want to call a method after the Job id has been executed successfully or it has internally failed after it gave the Job id.

public void OnStateElection(ElectStateContext context)
        {
            //Log event
        }

        public void OnCreating(CreatingContext filterContext)
        {
            //Log event
        }

        public void OnCreated(CreatedContext filterContext)
        {
            //Log event
        }

        public void OnPerforming(PerformingContext context)
        {
            //Log event
        }

        public void OnPerformed(PerformedContext context)
        {
            //Log event
        }

        public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            //Log event
        }

        public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            //Log event
        }


问:
How to align an object to match path
I am animating an object along a spline path in OpenGL. I am using some code I found to generate the spline. Sadly, I don't yet understand the mechanics of it.  I want my object to align to match the tangent of path so that it looks like its following the path.

Two questions.

How do I find a vector that is tangent to the path at a given point?
Secondly, given that vector and a vector pointing up, how do rotate the object to align?

Here is my spline code.

```<code>public Spline(Vector Path[])
{
    ControlPoints = Path;

    // Flatten out the control points array.
    int len = ControlPoints.length;
    float[] controlsX = new float[len];
    float[] controlsY = new float[len];
    float[] controlsZ = new float[len];
    for (int i = 0; i < len; ++i)
    {
        controlsX[i] = ControlPoints[i].x;
        controlsY[i] = ControlPoints[i].y;
        controlsZ[i] = ControlPoints[i].z;
   }

    // Calculate the gamma values just once.
    final int n = ControlPoints.length - 1;
    float[] gamma = new float[n + 1];
    gamma[0] = 1.0f / 2.0f;
    for (int i = 1; i < n; ++i) gamma[i] = 1 / (4 - gamma[i - 1]);
    gamma[n] = 1 / (2 - gamma[n - 1]);

    // Calculate the cubic segments.
    cubicX = calcNaturalCubic(n, controlsX, gamma);
    cubicY = calcNaturalCubic(n, controlsY, gamma);
    cubicZ = calcNaturalCubic(n, controlsZ, gamma);
}

private Cubic[] calcNaturalCubic(int n, float[] x, float[] gamma)
{
    float[] delta = new float[n + 1];
    delta[0] = 3 * (x[1] - x[0]) * gamma[0];
    for (int i = 1; i < n; ++i)
    {
        delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i];
    }
    delta[n] = (3 * (x[n] - x[n - 1])-delta[n - 1]) * gamma[n];

    float[] D = new float[n + 1];
    D[n] = delta[n];
    for (int i = n - 1; i >= 0; --i)
    {
        D[i] = delta[i] - gamma[i] * D[i + 1];
    }

    // Calculate the cubic segments.
    Cubic[] C = new Cubic[n];
    for (int i = 0; i < n; i++) {
        final float a = x[i];
        final float b = D[i];
        final float c = 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1];
        final float d = 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1];
        C[i] = new Cubic(a, b, c, d);
    }
    return C;
}

final public Vector GetPoint(float Position)
{
    if(Position >= 1) { return ControlPoints[ControlPoints.length - 1]; }
    float position = Position * cubicX.length;
    int splineIndex = (int)Math.floor(position);
    float splinePosition = position - splineIndex;
    return new Vector(cubicX[splineIndex].eval(splinePosition), cubicY[splineIndex].eval(splinePosition), cubicZ[splineIndex].eval(splinePosition));
}
</code>```

答:
First question:

If you keep track of the previous position of your object as well as the new position, you can find out the facing direction without finding the tangent of the spline, like so:

```<code>facing = newPosition - previousPosition
</code>```

Second question:

You can use the answers described here for rotating an object to face a particular direction: What is the easiest way to align the Z axis with a vector?

Title: How to align an object to match path

Body:
I am animating an object along a spline path in OpenGL. I am using some code I found to generate the spline. Sadly, I don't yet understand the mechanics of it.  I want my object to align to match the tangent of path so that it looks like its following the path.

Two questions.

How do I find a vector that is tangent to the path at a given point?
Secondly, given that vector and a vector pointing up, how do rotate the object to align?

Here is my spline code.

public Spline(Vector Path[])
{
    ControlPoints = Path;

    // Flatten out the control points array.
    int len = ControlPoints.length;
    float[] controlsX = new float[len];
    float[] controlsY = new float[len];
    float[] controlsZ = new float[len];
    for (int i = 0; i < len; ++i)
    {
        controlsX[i] = ControlPoints[i].x;
        controlsY[i] = ControlPoints[i].y;
        controlsZ[i] = ControlPoints[i].z;
   }

    // Calculate the gamma values just once.
    final int n = ControlPoints.length - 1;
    float[] gamma = new float[n + 1];
    gamma[0] = 1.0f / 2.0f;
    for (int i = 1; i < n; ++i) gamma[i] = 1 / (4 - gamma[i - 1]);
    gamma[n] = 1 / (2 - gamma[n - 1]);

    // Calculate the cubic segments.
    cubicX = calcNaturalCubic(n, controlsX, gamma);
    cubicY = calcNaturalCubic(n, controlsY, gamma);
    cubicZ = calcNaturalCubic(n, controlsZ, gamma);
}

private Cubic[] calcNaturalCubic(int n, float[] x, float[] gamma)
{
    float[] delta = new float[n + 1];
    delta[0] = 3 * (x[1] - x[0]) * gamma[0];
    for (int i = 1; i < n; ++i)
    {
        delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i];
    }
    delta[n] = (3 * (x[n] - x[n - 1])-delta[n - 1]) * gamma[n];

    float[] D = new float[n + 1];
    D[n] = delta[n];
    for (int i = n - 1; i >= 0; --i)
    {
        D[i] = delta[i] - gamma[i] * D[i + 1];
    }

    // Calculate the cubic segments.
    Cubic[] C = new Cubic[n];
    for (int i = 0; i < n; i++) {
        final float a = x[i];
        final float b = D[i];
        final float c = 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1];
        final float d = 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1];
        C[i] = new Cubic(a, b, c, d);
    }
    return C;
}

final public Vector GetPoint(float Position)
{
    if(Position >= 1) { return ControlPoints[ControlPoints.length - 1]; }
    float position = Position * cubicX.length;
    int splineIndex = (int)Math.floor(position);
    float splinePosition = position - splineIndex;
    return new Vector(cubicX[splineIndex].eval(splinePosition), cubicY[splineIndex].eval(splinePosition), cubicZ[splineIndex].eval(splinePosition));
}

Body:
First question:

If you keep track of the previous position of your object as well as the new position, you can find out the facing direction without finding the tangent of the spline, like so:

facing = newPosition - previousPosition

Second question:

You can use the answers described here for rotating an object to face a particular direction: What is the easiest way to align the Z axis with a vector?


问:
Create path without looping through rows of data frame
Imagine I have a dataframe that contain information for different persons and there location.

```<code>Person <- c('A','A','A','B','B','C')
Place  <- c('Ber','Mun','Stu','LA','NY','Ber')

df <- as.data.frame(cbind(Person,Place))
</code>```

Now I would like to have a new data frame that tells me how the person traveled. It should look somehow like this:

```<code>Person From  To
A       Ber   Mun
A       Mun   Stu
B        LA   NY
</code>```

I could do it with by looping over the data frame. But I want to do this for several million rows. Does somebody no a better way?

Best,
Felix

答:
We can use data.table.  Convert the 'data.frame' to 'data.table' , grouped by 'Person', change the 'Place' to 'From' and create the 'To' by taking the 'lead' of 'Place', then remove the rows where there is NA in 'To'

```<code>library(data.table)
setDT(df)[ ,.(From = Place, To =shift(Place, type = 'lead')), Person][!is.na(To)]
#   Person From  To
#1:      A  Ber Mun
#2:      A  Mun Stu
#3:      B   LA  NY
</code>```

It can also be done with tidyverse

```<code>library(dplyr)
df %>%
   group_by(Person) %>%
   transmute(From = Place, To = lead(Place)) %>%
   filter(!is.na(To))
# A tibble: 3 x 3
# Groups:   Person [2]
#  Person  From    To
#   <chr> <chr> <chr>
#1      A   Ber   Mun
#2      A   Mun   Stu
#3      B    LA    NY
</code>```

Body:
Imagine I have a dataframe that contain information for different persons and there location.

Person <- c('A','A','A','B','B','C')
Place  <- c('Ber','Mun','Stu','LA','NY','Ber')

df <- as.data.frame(cbind(Person,Place))

Now I would like to have a new data frame that tells me how the person traveled. It should look somehow like this:

Person From  To
A       Ber   Mun
A       Mun   Stu
B        LA   NY

I could do it with by looping over the data frame. But I want to do this for several million rows. Does somebody no a better way?

Best,
Felix

Body:
We can use data.table.  Convert the 'data.frame' to 'data.table' , grouped by 'Person', change the 'Place' to 'From' and create the 'To' by taking the 'lead' of 'Place', then remove the rows where there is NA in 'To'

library(data.table)
setDT(df)[ ,.(From = Place, To =shift(Place, type = 'lead')), Person][!is.na(To)]
#   Person From  To
#1:      A  Ber Mun
#2:      A  Mun Stu
#3:      B   LA  NY

It can also be done with tidyverse

library(dplyr)
df %>%
   group_by(Person) %>%
   transmute(From = Place, To = lead(Place)) %>%
   filter(!is.na(To))
# A tibble: 3 x 3
# Groups:   Person [2]
#  Person  From    To
#   <chr> <chr> <chr>
#1      A   Ber   Mun
#2      A   Mun   Stu
#3      B    LA    NY


问:
Why If isset match with syntax is not working
I want if isset $_POST["items"] text match with reject1 text and then echo. My code is not working why?

```<code>if(isset($_POST["items"])==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}
</code>```

答:
Try this

```<code>if(isset($_POST["items"]) && $_POST["items"]==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}
</code>```

It will work for you.

ContentLicense: CC BY-SA 4.0

Body:
I want if isset $_POST["items"] text match with reject1 text and then echo. My code is not working why?

if(isset($_POST["items"])==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}

Body:
Try this

if(isset($_POST["items"]) && $_POST["items"]==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}

It will work for you.


答:
You must write it like that:

```<code>if(isset($_POST["items"]) && $_POST["items"]==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}
</code>```

Because isset is return only true or false, not an value.

Title: Why If isset match with syntax is not working

Body:
You must write it like that:

if(isset($_POST["items"]) && $_POST["items"]==='reject1'){
   echo 'text match :)';
}
else {
   echo 'not match :(';
}

Because isset is return only true or false, not an value.


问:
How to get data from mongoose model and store with variable like mvc using node.js
Here below code is sample MVC framework code in PHP. I need same process as like in node.js with mongoose also.

I'm using Node.js, MongoDB, REST API development.

controller file:

```<code><?php
class Myclass {
 public function store_users() {
   //get the data from model file
   $country = $this->country->get_country_details($country_id);
  //After getting data do business logic
 }
}
</code>```

model file

```<code><?php
class Mymodel {
 public function get_country_details($cid) {
  $details = $this->db->table('country')->where('country_id',$id);
  return $details;
 }
}
</code>```

In node.js need to use as like MVC PHP process. Kindly suggest on this.

答:
Lets say you have user schema in mongoose which should act as model

```<code>// userModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var user = new Schema({
  name: { type: String, required: true },
  dob: { type: Date },
  email: { type: String, required: true, unique: true, lowercase: true},
  active: { type: Boolean, required: true, default: true}
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

var userSchema = mongoose.model('users', user);
module.exports = userSchema;
</code>```

```<code>// userController.js
var User = require('./userModel');

exports.getUserByEmail = function(req, res, next) {
    var email = req.param.email;
    User.findOne({ email: email }, function(err, data) {
       if (err) {
           next.ifError(err);
       }
       res.send({
           status: true,
           data: data
       });
       return next();
    });
};
</code>```

Ref: http://mongoosejs.com/docs/index.html

Body:
Here below code is sample MVC framework code in PHP. I need same process as like in node.js with mongoose also.

I'm using Node.js, MongoDB, REST API development.

controller file:

<?php
class Myclass {
 public function store_users() {
   //get the data from model file
   $country = $this->country->get_country_details($country_id);
  //After getting data do business logic
 }
}

model file

<?php
class Mymodel {
 public function get_country_details($cid) {
  $details = $this->db->table('country')->where('country_id',$id);
  return $details;
 }
}

In node.js need to use as like MVC PHP process. Kindly suggest on this.

Body:
Lets say you have user schema in mongoose which should act as model

// userModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var user = new Schema({
  name: { type: String, required: true },
  dob: { type: Date },
  email: { type: String, required: true, unique: true, lowercase: true},
  active: { type: Boolean, required: true, default: true}
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

var userSchema = mongoose.model('users', user);
module.exports = userSchema;

// userController.js
var User = require('./userModel');

exports.getUserByEmail = function(req, res, next) {
    var email = req.param.email;
    User.findOne({ email: email }, function(err, data) {
       if (err) {
           next.ifError(err);
       }
       res.send({
           status: true,
           data: data
       });
       return next();
    });
};

Ref: http://mongoosejs.com/docs/index.html


问:
if content size > actual height then fixed height and if content size < actual height then dynamic of tableview swift 3?
In storyBoard i have given top, bottom, leading and trailing constraints to tableview in a view.
i have given tableview height as contentSize.height. As per tableview height, no of cells that can visible in tableview 3 or 4 or etc(depending upon content size it may vary). But the problem is table view height is increasing as per content size.
if no of cells are more, then it should compare actual height of the table view with content size and if contentSize is lesser than tableview Actual height then only it should change the height of tableview.

```<code>if tableViewActualHeight > contentSize {
// then only change tableview height
    tableViewActualHeight = contentSize
}
</code>```

How can we get & where to place that code?

答:
OK here is an idea for that

First get height of tableview by yourTableView.frame.size.height.
Now calculate height of your tableView cells.
Lets assume the cases.

Assuming cell is of height 50 and tableview if height 200

First case

If you have 2 cell, then total cell height is 100. Now check if 100<200
bottomConstraint of tableView will be 200 - 100, that is 100.So here tableView height becomes 100

Second Case

If you have 5 cells ,then total cell height is 250 .Now check if 250<200
bottomConstraint will be ZERO

Please let me know if its helps you or having trouble to understand

Body:
In storyBoard i have given top, bottom, leading and trailing constraints to tableview in a view.
i have given tableview height as contentSize.height. As per tableview height, no of cells that can visible in tableview 3 or 4 or etc(depending upon content size it may vary). But the problem is table view height is increasing as per content size.
if no of cells are more, then it should compare actual height of the table view with content size and if contentSize is lesser than tableview Actual height then only it should change the height of tableview.

if tableViewActualHeight > contentSize {
// then only change tableview height
    tableViewActualHeight = contentSize
}

How can we get & where to place that code?


问:
"Lock obtain timed out exception" with no "write.lock" file
I am getting Lock obtain timed out exception with entirely empty index folder.

This exception throws at the moment I try to create an index with following code:

```<code>IndexWriter writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)
</code>```

How could I possibly solve this error?

答:
There are several possible causes:

Your directory does not have sufficient access. To fix this, right click on the directory>properties>security>make sure your process IIS_IUSRS has privileges

Another process is using the directory at the same time. Use Lock Hunter to detect which process is using this file

The write.lock in the directory is an orphan file, initially it was created but due to the process being killed, it has stayed there.

You are not Optimizing/Commiting/Disposing the writer which you have opened

To commit/dispose writer:

```<code>writer.Optimize();
writer.Commit();
writer.Dispose();
</code>```

I had this issue then had an instance of IProviderContext which was not being optimized/commited/disposed.

I hope this will solve your problem

Body:
I am getting Lock obtain timed out exception with entirely empty index folder.

This exception throws at the moment I try to create an index with following code:

IndexWriter writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)

How could I possibly solve this error?

Body:
There are several possible causes:

Your directory does not have sufficient access. To fix this, right click on the directory>properties>security>make sure your process IIS_IUSRS has privileges

Another process is using the directory at the same time. Use Lock Hunter to detect which process is using this file

The write.lock in the directory is an orphan file, initially it was created but due to the process being killed, it has stayed there.

You are not Optimizing/Commiting/Disposing the writer which you have opened

To commit/dispose writer:

writer.Optimize();
writer.Commit();
writer.Dispose();

I had this issue then had an instance of IProviderContext which was not being optimized/commited/disposed.

I hope this will solve your problem


问:
Nodejs: Changing single key value in an object
This has been asked before but I was not able to understand the answer. So I am asking again. This is the object I need to manipulate.

```<code>[
  "description": {
      "zh": "CDes",
      "en": "EDes"
  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]
</code>```

When I send a put request to the url with the following raw code

```<code>{
   description: {
     "zh" : "chinese"
   }
}
</code>```

it changes to

```<code>[
  "description": {
      "zh": "Chinese",

  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]
</code>```

but i want to keep the "en": "EDes" as well. I have used $set as

```<code>if (req.body.description.zh !== "undefined"){
    const id = "{" + req.params + " }";
    var obj = {
        'zh' : req.body.description.zh
    };

    Product.update(id, {'$set': {
        "description.$.zh" : req.body.description.zh
        }
    });
}
</code>```

but it is not working. I need to do this for description, nutrition and brand_names.Someone please help. Thank you
 This is the screenshot of the json I am getting after GET request

答:
If this is your object

```<code>var yourObject = [
  "description": {
      "zh": "CDes",
      "en": "EDes"
  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]
</code>```

You can get the zh object by

```<code>  var obj = {
    'zh' : yourObject[0].description.zh
};
</code>```

Your Initial object is an array

Body:
This has been asked before but I was not able to understand the answer. So I am asking again. This is the object I need to manipulate.

[
  "description": {
      "zh": "CDes",
      "en": "EDes"
  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]

When I send a put request to the url with the following raw code

{
   description: {
     "zh" : "chinese"
   }
}

it changes to

[
  "description": {
      "zh": "Chinese",

  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]

but i want to keep the "en": "EDes" as well. I have used $set as

if (req.body.description.zh !== "undefined"){
    const id = "{" + req.params + " }";
    var obj = {
        'zh' : req.body.description.zh
    };

    Product.update(id, {'$set': {
        "description.$.zh" : req.body.description.zh
        }
    });
}

but it is not working. I need to do this for description, nutrition and brand_names.Someone please help. Thank you
 This is the screenshot of the json I am getting after GET request

Body:
If this is your object

var yourObject = [
  "description": {
      "zh": "CDes",
      "en": "EDes"
  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]

You can get the zh object by

  var obj = {
    'zh' : yourObject[0].description.zh
};

Your Initial object is an array