问:
How do I create an instance of type array in 3rd party XML?
I have written a simple C# Windows application to test a 3rd party web service.  Here are two of the fields from the generated Reference.cs

```<code>/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 4)]
public PriceType Price
{
    get
    {
        return this.priceField;
    }
    set
    {
        this.priceField = value;
        this.RaisePropertyChanged("ExpectedPrice");
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Contact", Order = 5)]
public ContactType[] Contact
{
    get
    {
        return this.contactField;
    }
    set
    {
        this.contactField = value;
        this.RaisePropertyChanged("Contact");
    }
}
</code>```

I created the request object, and assigned a value to Price as follows:-

```<code>RequestServiceType myRequest = new RequestServiceType();

myRequest.Price = new Blah.PriceType();
myRequest.Price.GrossPrice = new Blah.AmountType();
myRequest.Price.GrossPrice.Value = 10M;
</code>```

However

```<code>myRequest.Contact = new Blah.ContactType();
</code>```

Errors with 'Cannot implicitly convert type 'RequestServiceType.ContactType' to 'RequestServiceType.ContactType[]'.

ContactType is an array in the Reference.cs (ContactType[]).  How do I create an instance of Contact in myRequest?

答:
Your syntax is what is the issue here.

the error message clearly explains that you are trying to assign an instance of the object to the property when the property expects an array of that object.

This will crate an array containing one instance

```<code>myRequest.Contact = new []{ new Blah.ContactType() };
</code>```

which is just syntatic sugar for

```<code>var contact = new new Blah.ContactType();
var array = new Blah.ContactType[1];
array[0] = contact;
myRequest.Contact = array;
</code>```

Body:
I have written a simple C# Windows application to test a 3rd party web service.  Here are two of the fields from the generated Reference.cs

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order = 4)]
public PriceType Price
{
    get
    {
        return this.priceField;
    }
    set
    {
        this.priceField = value;
        this.RaisePropertyChanged("ExpectedPrice");
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Contact", Order = 5)]
public ContactType[] Contact
{
    get
    {
        return this.contactField;
    }
    set
    {
        this.contactField = value;
        this.RaisePropertyChanged("Contact");
    }
}

I created the request object, and assigned a value to Price as follows:-

RequestServiceType myRequest = new RequestServiceType();

myRequest.Price = new Blah.PriceType();
myRequest.Price.GrossPrice = new Blah.AmountType();
myRequest.Price.GrossPrice.Value = 10M;

However

myRequest.Contact = new Blah.ContactType();

Errors with 'Cannot implicitly convert type 'RequestServiceType.ContactType' to 'RequestServiceType.ContactType[]'.

ContactType is an array in the Reference.cs (ContactType[]).  How do I create an instance of Contact in myRequest?

Body:
Your syntax is what is the issue here.

the error message clearly explains that you are trying to assign an instance of the object to the property when the property expects an array of that object.

This will crate an array containing one instance

myRequest.Contact = new []{ new Blah.ContactType() };

which is just syntatic sugar for

var contact = new new Blah.ContactType();
var array = new Blah.ContactType[1];
array[0] = contact;
myRequest.Contact = array;


来源: stackexchange

问:
Use of unresolved identifier NSWorkspace
I would like to open a url in browser but I get this error:

Use of unresolved identifier NSWorkspace

my code:

```<code>if let url = URL(string: "https://www.google.com"), NSWorkspace.shared().open(url) {
    print("default browser was successfully opened")
}
</code>```

答:
You are trying to add a code for macOS coding for iOS. When coding for iOS you have to use UIApplication.shared

```<code>if let url = URL(string: "https://google.com"), UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to open a url in browser but I get this error:

Use of unresolved identifier NSWorkspace

my code:

if let url = URL(string: "https://www.google.com"), NSWorkspace.shared().open(url) {
    print("default browser was successfully opened")
}

Body:
You are trying to add a code for macOS coding for iOS. When coding for iOS you have to use UIApplication.shared

if let url = URL(string: "https://google.com"), UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url)
}

ContentLicense: CC BY-SA 3.0


问:
python subprocess popen returns None
I have a python snippet like this:

```<code>self.task = subprocess.Popen("bash ./FOLDER/script.sh", cwd=some_dir, shell=True)
self.task.wait()
</code>```

from which an exception is raised, complaining that a 'NoneType' object has no method wait(). I guess it means the Popen call returns None ? What could be the reason for that. The documentation does not mention this possibility

I'm using python 2.7.13

答:
Well, apparently self.task gives a NoneType respons meaning the subprocess.Popen() command is likely at fault.

First thing I notice is an incorrect syntax, since you did not wrap your command line in square brackets [] and you did not split the arguments.

Furthermore, the Python docs state (regarding the cwd option you used):

If cwd is not None, the child’s current directory will be changed to
  cwd before it is executed. Note that this directory is not considered
  when searching the executable, so you can’t specify the program’s path
  relative to cwd.

So first thing to check would be if your script.sh is situated in some_dir/FOLDER/script.sh.

If that is indeed the case, please check if you inserted the cwd-argument with the right syntax, so as a string.. Meaning cwd="/path/to/some/dir".

Then, since the Python docs clearly state that:

Using shell=True can be a security hazard

I would remove that argument. This might mean you will have to use the full path to your bash. To find out the correct path, open a terminal and execute which bash. Or, to be sure, type bash.

Then, give this a try:

```<code>import subprocess

self.task = subprocess.Popen(["/path/to/your/bash", "./FOLDER/script.sh"], cwd="/path/to/some_dir", stdout=subprocess.PIPE, stderr=subprocess.PIPE) # This makes sure you will also catch any standard errors, so it allows for a bit more control.
output, errors = self.task.communicate() # This already encapsulates .wait()
print(output.decode()) # if you'd like to check the output.
</code>```

Read the comments in code for some further explanation..

Title: python subprocess popen returns None

Body:
I have a python snippet like this:

self.task = subprocess.Popen("bash ./FOLDER/script.sh", cwd=some_dir, shell=True)
self.task.wait()

from which an exception is raised, complaining that a 'NoneType' object has no method wait(). I guess it means the Popen call returns None ? What could be the reason for that. The documentation does not mention this possibility

I'm using python 2.7.13

Body:
Well, apparently self.task gives a NoneType respons meaning the subprocess.Popen() command is likely at fault.

First thing I notice is an incorrect syntax, since you did not wrap your command line in square brackets [] and you did not split the arguments.

Furthermore, the Python docs state (regarding the cwd option you used):

If cwd is not None, the child’s current directory will be changed to
  cwd before it is executed. Note that this directory is not considered
  when searching the executable, so you can’t specify the program’s path
  relative to cwd.

So first thing to check would be if your script.sh is situated in some_dir/FOLDER/script.sh.

If that is indeed the case, please check if you inserted the cwd-argument with the right syntax, so as a string.. Meaning cwd="/path/to/some/dir".

Then, since the Python docs clearly state that:

Using shell=True can be a security hazard

I would remove that argument. This might mean you will have to use the full path to your bash. To find out the correct path, open a terminal and execute which bash. Or, to be sure, type bash.

Then, give this a try:

import subprocess

self.task = subprocess.Popen(["/path/to/your/bash", "./FOLDER/script.sh"], cwd="/path/to/some_dir", stdout=subprocess.PIPE, stderr=subprocess.PIPE) # This makes sure you will also catch any standard errors, so it allows for a bit more control.
output, errors = self.task.communicate() # This already encapsulates .wait()
print(output.decode()) # if you'd like to check the output.

Read the comments in code for some further explanation..


问:
Read the contents of a file again and again in Fortran 95
I want to read entries from a huge file (more than 10^10 rows) inside a loop. Since file is huge, I am reading one element at a time, using it and then reading the next element and so on. Thus, I have something like this:

```<code>DO i = 1, 10
    open(unit = 1, file = 'myfile.dat')
    Do j = 1, 10^10
         read(1, *)x
         !Use x here
    Enddo
    close(1)
ENDDO
</code>```

This works fine when the outer loop runs a small number of times. However, when I want try to run it many more times, (say 100 to 1000), my computer gets hung or throws an error : Not enough space on \tmp. I looked at this but that didn't solve my issue. My primary guess is that this is happening because each time I re-open the file, it gets stored in RAM or tmp but I am not sure about this. In this context, can anybody tell me a better way to load file only once but read the contents over and over ?

答:
You don't have to close the file, just "rewind" it:</p>

```<code>open(newunit = iunit, file = 'myfile.dat') !no need to specify the number, the compiler will do it for you, iunit is an integer
do i = 1, 10
    do j = 1, 10**10                       !fortran compilable
         read(iunit, *)x
         !Use x here
    end do
    rewind(iunit)
end do

close(iunit)
</code>```

Body:
I want to read entries from a huge file (more than 10^10 rows) inside a loop. Since file is huge, I am reading one element at a time, using it and then reading the next element and so on. Thus, I have something like this:

DO i = 1, 10
    open(unit = 1, file = 'myfile.dat')
    Do j = 1, 10^10
         read(1, *)x
         !Use x here
    Enddo
    close(1)
ENDDO

This works fine when the outer loop runs a small number of times. However, when I want try to run it many more times, (say 100 to 1000), my computer gets hung or throws an error : Not enough space on \tmp. I looked at this but that didn't solve my issue. My primary guess is that this is happening because each time I re-open the file, it gets stored in RAM or tmp but I am not sure about this. In this context, can anybody tell me a better way to load file only once but read the contents over and over ?

Body:
You don't have to close the file, just "rewind" it:

open(newunit = iunit, file = 'myfile.dat') !no need to specify the number, the compiler will do it for you, iunit is an integer
do i = 1, 10
    do j = 1, 10**10                       !fortran compilable
         read(iunit, *)x
         !Use x here
    end do
    rewind(iunit)
end do

close(iunit)


问:
Is there an open source C visual debugger for windows?
Is there an open source C visual debugger for windows?
I have heard about the visual C++ express free edition, but does it have a visual debugger?

Thanks.

答:
Visual Studio is the standard for windows development. I have never seen a better IDE for this platform (or any other for that matter).

If has a debugger integrated in the IDE.  Try it - you'll probably like it.

OwnerDisplayName: linkedlist

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: splattne

OwnerDisplayName: Tim


问:
Application Crashes on Thread Exit - C++
My application is crashing when it exits the thread function.  This is how my thread is initialized:

```<code>LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);

// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
    NULL,                           // No security
    TRUE,                           // Create a manual-reset event object
    FALSE,                          // Initial state is non-signaled
    NULL                            // No name specified
    );

if ( _hNotifyWindowThreadExitEvent == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
    NULL,                           // No security attributes.
    0,                              // Use default initial stack size.
    pThreadStart,                   // Function to execute in new thread.
    pvThreadData,                   // Thread parameters.
    0,                              // Use default creation settings.
    NULL                            // Thread ID is not needed.
    );

if ( _hNotifyWindowThread == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}
</code>```

This is the portion of my thread function that gets executed:

```<code>DWORD NotifyWindowThreadFn( void * pParam )
{
    static CNotifyWindow * pobjNotifyWindow = NULL;
    CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);

    // Create notify window to handle surprize removal/insertion events...
    try
    {
        pobjNotifyWindow = new CNotifyWindow();
    }
    catch ( DWORD error )
    {
        return error;                // 1. PC gets here
    }
    catch ( long error )
    {
        return error;
    }
    catch ( ... )
    {
        return ERROR_CANNOT_MAKE;
    }

    /* Other stuff that is not executed due to return. */

}                                     // 2. PC then gets here
</code>```

When the application crashes, Visual Studio gives me this error message:

Windows has triggered a breakpoint in CppTestConsole.exe.

This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while CppTestConsole.exe has focus.

The output window may have more diagnostic information.

The output window doesn't have anything especially useful.  Only...

The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).

Then it shows that a bunch of DLLs are unloaded.  When I click the Break button, the PC is at the end of _CrtIsValidHeapPointer in dbgheap.c.  Does anyone have any ideas as to why my application is crashing when the thread exits?  Should I not be returning directly from within a threaded function?  Thanks.

答:
Try using _beginthreadex instead of CreateThread:

A thread in an executable that calls
  the C run-time library (CRT) should
  use the _beginthreadex and
  _endthreadex functions for thread management rather than CreateThread
  and ExitThread; this requires the use
  of the multi-threaded version of the
  CRT. If a thread created using
  CreateThread calls the CRT, the CRT
  may terminate the process in
  low-memory conditions.

Body:
My application is crashing when it exits the thread function.  This is how my thread is initialized:

LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);

// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
    NULL,                           // No security
    TRUE,                           // Create a manual-reset event object
    FALSE,                          // Initial state is non-signaled
    NULL                            // No name specified
    );

if ( _hNotifyWindowThreadExitEvent == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
    NULL,                           // No security attributes.
    0,                              // Use default initial stack size.
    pThreadStart,                   // Function to execute in new thread.
    pvThreadData,                   // Thread parameters.
    0,                              // Use default creation settings.
    NULL                            // Thread ID is not needed.
    );

if ( _hNotifyWindowThread == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

This is the portion of my thread function that gets executed:

DWORD NotifyWindowThreadFn( void * pParam )
{
    static CNotifyWindow * pobjNotifyWindow = NULL;
    CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);

    // Create notify window to handle surprize removal/insertion events...
    try
    {
        pobjNotifyWindow = new CNotifyWindow();
    }
    catch ( DWORD error )
    {
        return error;                // 1. PC gets here
    }
    catch ( long error )
    {
        return error;
    }
    catch ( ... )
    {
        return ERROR_CANNOT_MAKE;
    }

    /* Other stuff that is not executed due to return. */

}                                     // 2. PC then gets here

When the application crashes, Visual Studio gives me this error message:

Windows has triggered a breakpoint in CppTestConsole.exe.

This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while CppTestConsole.exe has focus.

The output window may have more diagnostic information.

The output window doesn't have anything especially useful.  Only...

The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).

Then it shows that a bunch of DLLs are unloaded.  When I click the Break button, the PC is at the end of _CrtIsValidHeapPointer in dbgheap.c.  Does anyone have any ideas as to why my application is crashing when the thread exits?  Should I not be returning directly from within a threaded function?  Thanks.


问:
Replace empty element in a list using sapply
I have two lists. The first one has an empty element. I'd like to replace that empty element with the first vector of the third list element of another list.

```<code>l1 <- list(a=1:3,b=4:9,c="")
l2 <- list(aa=11:13,bb=14:19,cc=data.frame(matrix(100:103,ncol=2)))

l1[sapply(l1, `[[`, 1)==""] <- l2[[3]][[1]]
</code>```

Using sapply, I can identify which elements are empty. However, when I try to assign a vector to this empty element: I get this error message:

Warning message: In l1[sapply(l1, [[, 1) == ""] <- l2[[3]][[1]] :

  number of items to replace is not a multiple of replacement length

This is only a warning, but the result I get is not the one I want. This is the l1 I get:

```<code>> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100
</code>```

This is what I need (two elements in $c):

```<code>> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101
</code>```

答: Just use l2[[3]][1] on the right hand side (single [ not [[)

Body:
I have two lists. The first one has an empty element. I'd like to replace that empty element with the first vector of the third list element of another list.

l1 <- list(a=1:3,b=4:9,c="")
l2 <- list(aa=11:13,bb=14:19,cc=data.frame(matrix(100:103,ncol=2)))

l1[sapply(l1, `[[`, 1)==""] <- l2[[3]][[1]]

Using sapply, I can identify which elements are empty. However, when I try to assign a vector to this empty element: I get this error message:

Warning message: In l1[sapply(l1, [[, 1) == ""] <- l2[[3]][[1]] :

  number of items to replace is not a multiple of replacement length

This is only a warning, but the result I get is not the one I want. This is the l1 I get:

> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100

This is what I need (two elements in $c):

> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101


问:
Opencv convert to grayscale not working properly
I've been trying to convert an image to grayscale using opencv in Python but it converts the image to some kind of thermal camera image. What am I doing wrong?
Here is the code for image below:

```<code>img =X_tr[9999]
plt.imshow(img)
plt.show()
img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_RGB2GRAY)
plt.imshow(img)
plt.show()
img.shape
</code>```

This image is taken from CIFAR10 dataset.
Thanks.

答:
Gray scale images, i.e. images with only one colorchannel, are interpreted by imshow as to be plotted using a colormap. You therefore need to specify the colormap you want to use (and the normalization, if it matters).

```<code>plt.imshow(img, cmap="gray", vmin=0, vmax=255)
</code>```

Body:
I've been trying to convert an image to grayscale using opencv in Python but it converts the image to some kind of thermal camera image. What am I doing wrong?
Here is the code for image below:

img =X_tr[9999]
plt.imshow(img)
plt.show()
img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_RGB2GRAY)
plt.imshow(img)
plt.show()
img.shape

This image is taken from CIFAR10 dataset.
Thanks.

Body:
Gray scale images, i.e. images with only one colorchannel, are interpreted by imshow as to be plotted using a colormap. You therefore need to specify the colormap you want to use (and the normalization, if it matters).

plt.imshow(img, cmap="gray", vmin=0, vmax=255)


问:
What is the $_REQUEST precedence?

PHP Superglobal variables

PHP has global variables which can be accessed within any scope of your script. Three of these variables ($_GET, $_POST, $_COOKIE) are stored within a fourth variable ($_REQUEST).

$_GET

An associative array of variables passed to the current script via the URL parameters.

Consider the following example in which a URL is sent and accessed.

http://www.example.com/myPage.php?myVar=myVal
```

<pre class="lang-php prettyprint-override"><code>echo $_GET["myVar"]; // returns "myVal"
</code>```

$_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

An example of this being used is as follows.

<form action="somePage.php" method="POST">
    <input type="text" name="myVar" value="myVal" />
    <input type="submit" name="submit" value="Submit" />
</form>
```

<pre class="lang-php prettyprint-override"><code>echo $_POST["myVar"]; // returns "myVal"
</code>```

$_COOKIE

An associative array of variables passed to the current script via HTTP Cookies

setcookie("myVar", "myVal", time() + 3600);
echo $_COOKIE["myVar"]; // returns "myVal"
```

<h2><code>$_REQUEST</code></h2>

<blockquote>
  <p>An associative array that by default contains the contents of <code>$_GET</code>, <code>$_POST</code> and <code>$_COOKIE</code>.</p>
</blockquote>

<hr>

<h1>Here's the thing</h1>

<p><code>$_REQUEST</code> contains all three in one array and is accessed via <code>$_REQUEST["myVar"]</code>.</p>

<h2>A random scenario</h2>

<p>Let's assume, for whatever reason, that I use the same name for my <code>$_GET</code>, <code>$_POST</code>, and <code>$_COOKIE</code>.</p>

<p>What would the precedence be for what is stored in <code>$_REQUEST</code>.</p>

<p>Assuming I set a sent data through the URL, posted through the form and, set a cookie with the same name as each other (a bizarre scenario, I know).<br>
Lets say I used the name "example".</p>

<p>What would be the output of the following output?</p>

<pre class="lang-php prettyprint-override"><code>     if ($_REQUEST["example"] == $_GET["example"])    echo "GET";
else if ($_REQUEST["example"] == $_POST["example"])   echo "POST";
else if ($_REQUEST["example"] == $_COOKIE["example"]) echo "COOKIE";
</code>```

tl;dr

If $_GET, $_POST, and $_COOKIE all have a value stored with the same name; which one will $_REQUEST store under said name?

答:
In php.ini file there are 2 directives: request_order and variables_order

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables
into the _REQUEST array. Registration is done from left to right, newer values override
older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the 'C' for cookies,
due to security concerns.
```
</blockquote>

<p>and</p>

<blockquote>
  <p><code>variables_order string</code></p>

<pre class="lang-none prettyprint-override"><code>Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable
parsing. For example, if variables_order is set to "SP" then PHP will create the
superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting
to "" means no superglobals will be set.

If the deprecated register_globals directive is on, then variables_order also configures
the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope.
So for example if variables_order is set to "EGPCS", register_globals is enabled, and both
$_GET['action'] and $_POST['action'] are set, then $action will contain the value of
$_POST['action'] as P comes after G in our example directive value.
</code>```

Taken from official documentation

Title: What is the $_REQUEST precedence?

Body:
PHP Superglobal variables

PHP has global variables which can be accessed within any scope of your script. Three of these variables ($_GET, $_POST, $_COOKIE) are stored within a fourth variable ($_REQUEST).

$_GET

An associative array of variables passed to the current script via the URL parameters.

Consider the following example in which a URL is sent and accessed.

http://www.example.com/myPage.php?myVar=myVal

echo $_GET["myVar"]; // returns "myVal"

$_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

An example of this being used is as follows.

<form action="somePage.php" method="POST">
    <input type="text" name="myVar" value="myVal" />
    <input type="submit" name="submit" value="Submit" />
</form>

echo $_POST["myVar"]; // returns "myVal"

$_COOKIE

An associative array of variables passed to the current script via HTTP Cookies

setcookie("myVar", "myVal", time() + 3600);
echo $_COOKIE["myVar"]; // returns "myVal"

$_REQUEST

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

Here's the thing

$_REQUEST contains all three in one array and is accessed via $_REQUEST["myVar"].

A random scenario

Let's assume, for whatever reason, that I use the same name for my $_GET, $_POST, and $_COOKIE.

What would the precedence be for what is stored in $_REQUEST.

Assuming I set a sent data through the URL, posted through the form and, set a cookie with the same name as each other (a bizarre scenario, I know).

Lets say I used the name "example".

What would be the output of the following output?

     if ($_REQUEST["example"] == $_GET["example"])    echo "GET";
else if ($_REQUEST["example"] == $_POST["example"])   echo "POST";
else if ($_REQUEST["example"] == $_COOKIE["example"]) echo "COOKIE";

tl;dr

If $_GET, $_POST, and $_COOKIE all have a value stored with the same name; which one will $_REQUEST store under said name?

Body:
In php.ini file there are 2 directives: request_order and variables_order

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables
into the _REQUEST array. Registration is done from left to right, newer values override
older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the 'C' for cookies,
due to security concerns.

and

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable
parsing. For example, if variables_order is set to "SP" then PHP will create the
superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting
to "" means no superglobals will be set.

If the deprecated register_globals directive is on, then variables_order also configures
the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope.
So for example if variables_order is set to "EGPCS", register_globals is enabled, and both
$_GET['action'] and $_POST['action'] are set, then $action will contain the value of
$_POST['action'] as P comes after G in our example directive value.

Taken from official documentation


问:
set the CLASSPATH
I am using Mac os Sierra 10.12.3 ,I want to  execute  the byte code  on  the Java(TM) Virtual Machine
(JVM) I need to set the CLASSPATH,
 Using my terminal

```<code>CLASSPATH=</Users/.../Documents/jj2000/jj2000-4.1\ 3>/jj2000-4.1.jar:$CLASSPATH export CLASSPATH
</code>```

show me

```<code>-bash: /jj2000-4.1.jar:: Permission denied
</code>```

I am confusing with command line  how can I set the CLASSPATH.
My java  is

```<code>java version "1.8.0_20-ea"
Java(TM) SE Runtime Environment (build 1.8.0_20-ea-b20)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b20, mixed mode)
</code>```

Please help.

答:
Don't, ever, set a global CLASSPATH environment variable. Pass the classpath to each java program you launch: each one has its own, specific classpath. </p>

```<code>java -cp /path/to/jj2000-4.1.jar:your-application.jar com.yourcompany.youapp.Main
</code>```

Title: set the CLASSPATH

Body:
I am using Mac os Sierra 10.12.3 ,I want to  execute  the byte code  on  the Java(TM) Virtual Machine
(JVM) I need to set the CLASSPATH,
 Using my terminal

CLASSPATH=</Users/.../Documents/jj2000/jj2000-4.1\ 3>/jj2000-4.1.jar:$CLASSPATH export CLASSPATH

show me

-bash: /jj2000-4.1.jar:: Permission denied

I am confusing with command line  how can I set the CLASSPATH.
My java  is

java version "1.8.0_20-ea"
Java(TM) SE Runtime Environment (build 1.8.0_20-ea-b20)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b20, mixed mode)

Please help.

Body:
Don't, ever, set a global CLASSPATH environment variable. Pass the classpath to each java program you launch: each one has its own, specific classpath.

java -cp /path/to/jj2000-4.1.jar:your-application.jar com.yourcompany.youapp.Main


问:
In Elm, how would I express verbally function type defn: `route : Url.Parser (Route -> a) a`?
I'm trying to understand this code from url-parser:

```<code>route : Url.Parser (Route -> a) a
route =
    Url.oneOf
        [ Url.map Home top
        , Url.map BlogList (s "blog" <?> stringParam "search")
        , Url.map BlogPost (s "blog" </> int)
        ]
</code>```

Is it: "route is a function that takes 1) a Parser, 2) a function that takes a Route and returns an a, and 3) an a"?

This doesn't seem correct because if it's just listing the arguments, where is it expressing the return value of route itself?

I'm very new to elm, but what throws me off here is that the -> is contained within the parens, and then there's no -> at the end indicating what route returns.

答:
Since you see just the function name before the = in route =, it means that it takes no arguments.
You can also see that in the annotation since there's no ->.
There is one inside parenthesis.

route therefore, returns a Url.Parser (Route -> a) a.

From what I understand, it returns a type Parser a b
where a is a function (Route -> a) and b can be anything ( it's named a here, but it's irrelevant ).

The -> is referring to that function that the type Parser "encapsulates".
I don't know how to explain it better, but take a look at the library functions. They work in a similar way
http://package.elm-lang.org/packages/evancz/url-parser/2.0.1/UrlParser

Body:
I'm trying to understand this code from url-parser:

route : Url.Parser (Route -> a) a
route =
    Url.oneOf
        [ Url.map Home top
        , Url.map BlogList (s "blog" <?> stringParam "search")
        , Url.map BlogPost (s "blog" </> int)
        ]

Is it: "route is a function that takes 1) a Parser, 2) a function that takes a Route and returns an a, and 3) an a"?

This doesn't seem correct because if it's just listing the arguments, where is it expressing the return value of route itself?

I'm very new to elm, but what throws me off here is that the -> is contained within the parens, and then there's no -> at the end indicating what route returns.


问:
Javascript import function syntax
I am trying to import a function from another module but on running am getting an error:

```<code>TypeError: _this.getData is not a function.
</code>```

data.js

```<code>function getData() {
  return [
    { id: 1,
      name: 'Pluto',
      type: 'Dwarf Planet'
    },
    { id: 2,
      name: 'Neptune',
      type: 'Planet'
    }
  ]
}
export { getData }
</code>```

worker.js

```<code>import getData from data.js

this.data = this.getData()
</code>```

Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?

答:
You should omit the "this" keyword when using "getData()" it doesn't belong on the current object.</p>

```<code>function getData() { .... }

export default getData;

import getData from "data.js"

this.data = getData();
</code>```

Title: Javascript import function syntax

Body:
I am trying to import a function from another module but on running am getting an error:

TypeError: _this.getData is not a function.

data.js

function getData() {
  return [
    { id: 1,
      name: 'Pluto',
      type: 'Dwarf Planet'
    },
    { id: 2,
      name: 'Neptune',
      type: 'Planet'
    }
  ]
}
export { getData }

worker.js

import getData from data.js

this.data = this.getData()

Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?

Body:
You should omit the "this" keyword when using "getData()" it doesn't belong on the current object.

function getData() { .... }

export default getData;

import getData from "data.js"

this.data = getData();


问:
Ajax and SQL population of a dropdown
This seems to be the pain of my life I have now spent hours on this and none of the researched solutions seem to fix it. My code is supposed to populate a dropdown from a database called "notes" the field that is populated from is supposed is "name" and then the program is supposed to select all of the records with the name as the same selected. Except it does not seem to populate the list. I don't think that it's a database connection error as when all patients is selected all the records show up.

Here's my code:

<?php

// php select option value from database

$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";

// connect to mysql database

 //load_data_select.php

 mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
 $connect = mysqli_connect($hostname, $username, $password, $databaseName);
 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM name";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }
 function fill_patients($connect)
 {
      $output = '';
      $sql = "SELECT * FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
';
           $output .= '
'.$row["details"].'';
           $output .=     '
';
           $output .=     '
';
      }
      return $output;
 }
 ?>
 <!DOCTYPE html>

           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                          <?php echo fill_patients($connect); ?>
                     </select>

                          <?php echo fill_patients($connect);?>

   ```

答:
You are not calling fill_name function in your select, but calling fill_patients instead, And I don't see any element with the id of #show_name in your html.

<?php

// php select option value from database

$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";

// connect to mysql database

 //load_data_select.php

 mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
 $connect = mysqli_connect($hostname, $username, $password, $databaseName);
 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM name";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }
 function fill_patients($connect)
 {
      $output = '';
      $sql = "SELECT * FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
';
           $output .= '
'.$row["details"].'';
           $output .=     '
';
           $output .=     '
';
      }
      return $output;
 }
 ?>
 <!DOCTYPE html>

           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           </script>

                     <select name="name" id="name">
                          <option value="">Show All Patients</option>

                           <?php echo fill_name($connect); ?>
                     </select>

                          <?php echo fill_patients($connect);?>

  ```

Results

Title: Ajax and SQL population of a dropdown

Body:
You are not calling fill_name function in your select, but calling fill_patients instead, And I don't see any element with the id of #show_name in your html.

<?php

// php select option value from database

$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";

// connect to mysql database

 //load_data_select.php

 mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
 $connect = mysqli_connect($hostname, $username, $password, $databaseName);
 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM name";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }
 function fill_patients($connect)
 {
      $output = '';
      $sql = "SELECT * FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<div class="col-md-3">';
           $output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["details"].'';
           $output .=     '</div>';
           $output .=     '</div>';
      }
      return $output;
 }
 ?>
 <!DOCTYPE html>
 <html>
      <head>
           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           </script>
      </head>
      <body>
           <br /><br />
           <div class="container">
                <h3>
                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                          <!-- <?php echo fill_patients($connect); ?> -->
                          <!-- call fill_name function instead of the above function -->
                           <?php echo fill_name($connect); ?>
                     </select>
                     <br /><br />
                     <div class="row" id="show_patients">
                          <?php echo fill_patients($connect);?>
                     </div>
                </h3>
           </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 <script>
 $(document).ready(function(){
      $('#name').change(function(){
           var name_id = $(this).val();
           $.ajax({
                url:"load_data.php",
                method:"POST",
                data:{id: name_id},
                success:function(data){
                     $('#show_name').html(data);
                }
           });
      });
 });
 </script>
      </body>
 </html>

Results


问:
How can I countdown a timer
How do I set my time difference on countdown?

I have the time difference from my java code, and all I want for it to do is to countdown.

Here's my java code.

```<code>public class time {

    public void printDifference( Date endDate){

        Date now = new Date();
        Date startDate = now;
        //milliseconds
        long different = endDate.getTime() - startDate.getTime();

        System.out.println("startDate : " + startDate);
        System.out.println("endDate : "+ endDate);
        System.out.println("different : " + different);

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        System.out.printf(
            "%d days, %d hours, %d minutes, %d seconds%n",
            elapsedDays,
            elapsedHours, elapsedMinutes, elapsedSeconds);

    }

    public static void main(String[] args) {

    }
}
</code>```

答:
Assuming that you require a countdown timer in background, say for a quiz application, running a separate thread in the background is a viable solution.
Let me know if you expect something else.

```<code>public class time implements Runnable{
   private Thread counter;
   //making your local varibles members so that they could be used by      "counter" thread
   private long different, secondsInMilli,  minutesInMilli,
        hoursInMilli, daysInMilli;

   public void printDifference( Date endDate){
        Date now = new Date();
        Date startDate = now;
        //milliseconds
        this.different = endDate.getTime() - startDate.getTime();

        System.out.println("startDate : " + startDate);
        System.out.println("endDate : "+ endDate);
        System.out.println("different : " + different);

        //Initializing your variables
        this.secondsInMilli = 1000;
        this.minutesInMilli = secondsInMilli * 60;
        this.hoursInMilli = minutesInMilli * 60;
        this.daysInMilli = hoursInMilli * 24;
        this.counter = new Thread(this, "counter");
        counter.start();
  }

  @Override
  public void run() {
      if(Thread.currentThread().getName().equals("counter")){
          try{
              long differentCopy = different;
                  while(differentCopy > 0 ){
                      //dropping your calculations here
                      long elapsedDays = different / daysInMilli;
                      different = different % daysInMilli;

                      long elapsedHours = different / hoursInMilli;
                      different = different % hoursInMilli;

                      long elapsedMinutes = different / minutesInMilli;
                      different = different % minutesInMilli;

                      long elapsedSeconds = different / secondsInMilli;
                      System.out.printf("%d days, %d hours, %d minutes, %d seconds\n",
                            elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
                      different = differentCopy-=1000;
                      Thread.sleep(1000);
                  }
          }catch(InterruptedException | HeadlessException e){
            e.printStackTrace();
          }
      }
  }
  public static void main(String[] args) {
    // TODO code application logic here
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MILLISECOND, 10000);//current time + 10s
    Date endDate = calendar.getTime();
    time t = new time();
    t.printDifference(endDate);
}}
</code>```

Output:

```<code>startDate : Sat Apr 01 19:30:12 IST 2017
endDate : Sat Apr 01 19:30:22 IST 2017
different : 9999
0 days, 0 hours, 0 minutes, 9 seconds
0 days, 0 hours, 0 minutes, 8 seconds
0 days, 0 hours, 0 minutes, 7 seconds
0 days, 0 hours, 0 minutes, 6 seconds
0 days, 0 hours, 0 minutes, 5 seconds
0 days, 0 hours, 0 minutes, 4 seconds
0 days, 0 hours, 0 minutes, 3 seconds
0 days, 0 hours, 0 minutes, 2 seconds
0 days, 0 hours, 0 minutes, 1 seconds
0 days, 0 hours, 0 minutes, 0 seconds
</code>```

Title: How can I countdown a timer

Body:
How do I set my time difference on countdown?

I have the time difference from my java code, and all I want for it to do is to countdown.

Here's my java code.

public class time {

    public void printDifference( Date endDate){

        Date now = new Date();
        Date startDate = now;
        //milliseconds
        long different = endDate.getTime() - startDate.getTime();

        System.out.println("startDate : " + startDate);
        System.out.println("endDate : "+ endDate);
        System.out.println("different : " + different);

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        System.out.printf(
            "%d days, %d hours, %d minutes, %d seconds%n",
            elapsedDays,
            elapsedHours, elapsedMinutes, elapsedSeconds);

    }

    public static void main(String[] args) {

    }
}

Body:
Assuming that you require a countdown timer in background, say for a quiz application, running a separate thread in the background is a viable solution.
Let me know if you expect something else.

public class time implements Runnable{
   private Thread counter;
   //making your local varibles members so that they could be used by      "counter" thread
   private long different, secondsInMilli,  minutesInMilli,
        hoursInMilli, daysInMilli;

   public void printDifference( Date endDate){
        Date now = new Date();
        Date startDate = now;
        //milliseconds
        this.different = endDate.getTime() - startDate.getTime();

        System.out.println("startDate : " + startDate);
        System.out.println("endDate : "+ endDate);
        System.out.println("different : " + different);

        //Initializing your variables
        this.secondsInMilli = 1000;
        this.minutesInMilli = secondsInMilli * 60;
        this.hoursInMilli = minutesInMilli * 60;
        this.daysInMilli = hoursInMilli * 24;
        this.counter = new Thread(this, "counter");
        counter.start();
  }

  @Override
  public void run() {
      if(Thread.currentThread().getName().equals("counter")){
          try{
              long differentCopy = different;
                  while(differentCopy > 0 ){
                      //dropping your calculations here
                      long elapsedDays = different / daysInMilli;
                      different = different % daysInMilli;

                      long elapsedHours = different / hoursInMilli;
                      different = different % hoursInMilli;

                      long elapsedMinutes = different / minutesInMilli;
                      different = different % minutesInMilli;

                      long elapsedSeconds = different / secondsInMilli;
                      System.out.printf("%d days, %d hours, %d minutes, %d seconds\n",
                            elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
                      different = differentCopy-=1000;
                      Thread.sleep(1000);
                  }
          }catch(InterruptedException | HeadlessException e){
            e.printStackTrace();
          }
      }
  }
  public static void main(String[] args) {
    // TODO code application logic here
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MILLISECOND, 10000);//current time + 10s
    Date endDate = calendar.getTime();
    time t = new time();
    t.printDifference(endDate);
}}

Output:

startDate : Sat Apr 01 19:30:12 IST 2017
endDate : Sat Apr 01 19:30:22 IST 2017
different : 9999
0 days, 0 hours, 0 minutes, 9 seconds
0 days, 0 hours, 0 minutes, 8 seconds
0 days, 0 hours, 0 minutes, 7 seconds
0 days, 0 hours, 0 minutes, 6 seconds
0 days, 0 hours, 0 minutes, 5 seconds
0 days, 0 hours, 0 minutes, 4 seconds
0 days, 0 hours, 0 minutes, 3 seconds
0 days, 0 hours, 0 minutes, 2 seconds
0 days, 0 hours, 0 minutes, 1 seconds
0 days, 0 hours, 0 minutes, 0 seconds


Title: load csv into 2D matrix with numpy for plotting

Body:
Given this CSV file:

"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12

I simply want to load it as a matrix/ndarray with 3 rows and 7 columns.  However, for some reason, all I can get out of numpy is an ndarray with 3 rows (one per line) and no columns.

r = np.genfromtxt(fname,delimiter=',',dtype=None, names=True)
print r
print r.shape

[ (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291111964948.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291113113366.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291120650486.0)]
(3,)

I can manually iterate and hack it into the shape I want, but this seems silly.  I just want to load it as a proper matrix so I can slice it across different dimensions and plot it, just like in matlab.

Body:
I think using dtype where there is a name row is confusing the routine.  Try

>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111196e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111311e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29112065e+12]])
>>> r[:,0]    # Slice 0'th column
array([ 611.88243,  611.88243,  611.88243])


问:
not sure why all text is being printed when specific template exists
I have a template element that is specific to listitems nodes.

xsl

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="listitems">
    <xsl:value-of select="@status" />
  </xsl:template>

</xsl:stylesheet>
</code>```

xml

```<code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="callvsapply.xslt"?>
<!-- sample XML snippet -->
<xml>
  <foo status="No">You are here.</foo>
  <bar status="Yes">Hello Bar!</bar>
  <baz status="No">Hello Baz!</baz>
  <listitems status="Yes" id="13" />
  <listitems status="No" id="12" />
</xml>
</code>```

results

```<code>  You are here.
  Hello Bar!
  Hello Baz!
  Yes
  No
</code>```

Why does all text print? I expected just Yes and No.

答:
XSLT has a concept of "built-in template rules", which are templates that are used if no relevant template is defined for the current node to which templates are being applied.

They look like this:

```<code><xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="text()|@*">
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="processing-instruction()|comment()"/>
</code>```

What these boil down to is:

If the current node is an element or the root node, apply templates to all child nodes.

If the current node is a text node or attribute node, place its value in the output.

If the current node is a processing instruction or comment, do nothing.

So basically, XSLT's default behavior, if no templates are specified at all, is to walk the document from top to bottom, outputting the value of all text nodes along the way. That is what you are seeing - your XSLT is outputting all text it encounters on the way down.

To remedy this in your case, there are two basic approaches:

First approach: intercept the processing at the root node (or at the document element), and directly target the nodes you want to process from there:

```<code><xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="/*">
    <xsl:apply-templates select="listitems" />
  </xsl:template>

  <xsl:template match="listitems">
    <xsl:value-of select="@status" />
  </xsl:template>

</xsl:stylesheet>
</code>```

Second approach: override the built-in processing for text nodes, so that their values are not sent to the output by default:

```<code><xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="listitems">
    <xsl:value-of select="@status" />
  </xsl:template>

  <xsl:template match="text()" />

</xsl:stylesheet>
</code>```

Body:
I have a template element that is specific to listitems nodes.

xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="listitems">
    <xsl:value-of select="@status" />
  </xsl:template>

</xsl:stylesheet>

xml

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="callvsapply.xslt"?>

<xml>
  <foo status="No">You are here.</foo>
  <bar status="Yes">Hello Bar!</bar>
  <baz status="No">Hello Baz!</baz>
  <listitems status="Yes" id="13" />
  <listitems status="No" id="12" />
</xml>

results

  You are here.
  Hello Bar!
  Hello Baz!
  Yes
  No

Why does all text print? I expected just Yes and No.

Body:
XSLT has a concept of "built-in template rules", which are templates that are used if no relevant template is defined for the current node to which templates are being applied.

They look like this:

<xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="text()|@*">
  <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="processing-instruction()|comment()"/>

What these boil down to is:

If the current node is an element or the root node, apply templates to all child nodes.

If the current node is a text node or attribute node, place its value in the output.

If the current node is a processing instruction or comment, do nothing.

So basically, XSLT's default behavior, if no templates are specified at all, is to walk the document from top to bottom, outputting the value of all text nodes along the way. That is what you are seeing - your XSLT is outputting all text it encounters on the way down.

To remedy this in your case, there are two basic approaches:

First approach: intercept the processing at the root node (or at the document element), and directly target the nodes you want to process from there:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="/*">
    <xsl:apply-templates select="listitems" />
  </xsl:template>

  <xsl:template match="listitems">
    <xsl:value-of select="@status" />
  </xsl:template>

</xsl:stylesheet>

Second approach: override the built-in processing for text nodes, so that their values are not sent to the output by default:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="listitems">
    <xsl:value-of select="@status" />
  </xsl:template>

  <xsl:template match="text()" />

</xsl:stylesheet>


问:
Deletion a Node from binary search tree with 2 nodes, with a different method possible?
I have searched everywhere for this but there is only one method :

find predecessor (or successor) of node to delete

replace node with predecessor (or successor)

delete predecessor (or successor)

But i feel we can also do in this way :

pulloff the right(or left) element to the node to delete i.e just replace the
  element to delete with right (or left) element and keep doing it till we encounter
  the leaf and then delete the leaf.
  In brief, keep replacing element to delete with its right(or left) element and keep doing it till we reach the leaf , and then delete the leaf.

So Is this method right ?

答:
For your subject question, the answer is yes; another method is possible.

There is a way that I discovered in a book of Sedgewick, which in my opinion is easier and general.

First, consider the exclusive join of two BST ts and tg'. Exclusive means that all the keys intsare smaller than any key intg`. So consider the following situation:

Now, if you select any root between ts or tg as the root of the exclusive join, you could recursively define the definitive result as follows:

In this case the root of the join is the root of ts.

Note that when you delete a complete node in a BST, its children are two exclusive trees in the sense previously defined. So you could define the deletion as follows:

```<code>Node * remove_from_bst(Node *& root, int key) noexcept
{
  if (root == nullptr)
    return nullptr; // In this case key was not found

  // recursive searching of the key to be removed
  if (key < root->key)
    return remove_from_bst(root->left, key);
  else if (root->key <  key)
    return remove_from_bst(root->right, key);

  // here root contains a node with key
  Node * ret_val = root; // backup of root that we will remove from tree
  root = join_exclusive(root->left, root->right); // new subtree

  return ret_val; // we return the removed node
}
</code>```

Now, for finishing, we define the join_exclusive() operation:

```<code>Node * join_exclusive(Node *& ts, Node *& tg) noexcept
{
  if (ts == nullptr)
    return tg;

  if (tg == nullptr)
    return ts;

  tg->left = join_exclusive(ts->right, tg->left);

  ts->right = tg;
  Node * ret_val = ts;
  ts = tg = nullptr; // empty the trees

  return ret_val;
}
</code>```

This approach is for me easier because it manages the three cases: a leaf, an incomplete node and a complete node. In addition, the keys never are moved between nodes.

Since the root of the exclusive join is arbitrarily selected, this approach, as well as the yours, introduces a bias that tends to unbalance a random tree (the root selection was not randomly done). However, as Martinez & Roura propose for their random trees, you could store the cardinality of each subtree in the node. Then, you could perform a raffle that ponderates the cardinalities of each subtree. With this approach you could guarantee that the tree always is equivalent to a BST randomly built

Body:
For your subject question, the answer is yes; another method is possible.

There is a way that I discovered in a book of Sedgewick, which in my opinion is easier and general.

First, consider the exclusive join of two BST ts and tg'. Exclusive means that all the keys intsare smaller than any key intg`. So consider the following situation:

Now, if you select any root between ts or tg as the root of the exclusive join, you could recursively define the definitive result as follows:

In this case the root of the join is the root of ts.

Note that when you delete a complete node in a BST, its children are two exclusive trees in the sense previously defined. So you could define the deletion as follows:

Node * remove_from_bst(Node *& root, int key) noexcept
{
  if (root == nullptr)
    return nullptr; // In this case key was not found

  // recursive searching of the key to be removed
  if (key < root->key)
    return remove_from_bst(root->left, key);
  else if (root->key <  key)
    return remove_from_bst(root->right, key);

  // here root contains a node with key
  Node * ret_val = root; // backup of root that we will remove from tree
  root = join_exclusive(root->left, root->right); // new subtree

  return ret_val; // we return the removed node
}

Now, for finishing, we define the join_exclusive() operation:

Node * join_exclusive(Node *& ts, Node *& tg) noexcept
{
  if (ts == nullptr)
    return tg;

  if (tg == nullptr)
    return ts;

  tg->left = join_exclusive(ts->right, tg->left);

  ts->right = tg;
  Node * ret_val = ts;
  ts = tg = nullptr; // empty the trees

  return ret_val;
}

This approach is for me easier because it manages the three cases: a leaf, an incomplete node and a complete node. In addition, the keys never are moved between nodes.

Since the root of the exclusive join is arbitrarily selected, this approach, as well as the yours, introduces a bias that tends to unbalance a random tree (the root selection was not randomly done). However, as Martinez & Roura propose for their random trees, you could store the cardinality of each subtree in the node. Then, you could perform a raffle that ponderates the cardinalities of each subtree. With this approach you could guarantee that the tree always is equivalent to a BST randomly built


问:
Can split recursion be done by hand?
I have this worksheet problem to work on, and I just don't see how it can be done by hand. Each method calls 2 more methods to run, so each one would call 2 more. I don't know how to keep track of any of it. I don't know how one would even find the answer besides putting it into Eclipse.</p>

```<code>static int fun(int x) {
    if(x < 1) {
        return 1;
    } else {
        return x + fun(x-1) + fun(x-2);
    }
}

public static void main(String[] args) {
    System.out.println(fun(4));
}
</code>```

答:
If you mean functions that call itself more than once at times then Yes!

Base case: x < 1 ==> 1, thus fun(-1) as well as fun(0) substitutes to 1

```<code>fun(1)              ; == [substitute default case with result]
1 + fun(0) + fun(-1); == [substitute base cases]
1 + 1 + 1           ; ==> 3

fun(2)              ; == [substitute default case with result]
2 + fun(1) + fun(0) ; == [substitute fun(1) with previously calculated result]
2 + 3 + fun(0)      ; == [substitute base cases]
2 + 3 + 1           ; ==> 6

fun(3)              ; == [substitute default case with result]
3 + fun(2) + fun(1) ; == [substitute with previously calculated result]
3 + 6 + 3           ; ==> 12

fun(4)              ; == [substitute default case with result]
4 + fun(3) + fun(2) ; == [substitute with previously calculated results]
4 + 12 + 6          ; ==> 22
</code>```

You could have started with fun(4) like this:

```<code>fun(4) ; == [expand default cases]
4 +
fun(3) +
fun(2) ; == [expand default cases]
4 +
3 + fun(2) + fun(1) +
2 + fun(1) + fun(0) ; == [expand fun(2) default case]

4 +
3 + (2 + fun(1) + fun(0)) + fun(1) +
2 + fun(1) + fun(0) ; == [group]

4 + 3 + 2*2 + 3*fun(1) + 2*fun(0) ; == [expand default cases]

4 + 3 + 2*2 + 2*fun(0) +
3*(1 + fun(0) + fun(-1)) ; == [group, group x<1 as b]

4 + 3+ 2*2 + 3*1 + 8*fun(b) ; == [expand base cases]
4 + 3+ 2*2 + 3*1 + 8*1      ; == [calculate]
; ==> 22
</code>```

I find it slightly messier. Especially if you don't group the several calls together it can be a pain.

Notice that this cannot be done if the function result is not directly mapped to its argument. As a treat here is a better version of your function:

```<code>static int fun(int n) {
    return fun(n, 0, 1, 3);
}

static int fun(int n, int v, int a, int b) {
    return n >= v ? a : fun(n, v+1, b, a+b+n+2);
}
</code>```

It seems to be consistent with the sequence A066982 except it omits the first element.

Title: Can split recursion be done by hand?

Body:
I have this worksheet problem to work on, and I just don't see how it can be done by hand. Each method calls 2 more methods to run, so each one would call 2 more. I don't know how to keep track of any of it. I don't know how one would even find the answer besides putting it into Eclipse.

static int fun(int x) {
    if(x < 1) {
        return 1;
    } else {
        return x + fun(x-1) + fun(x-2);
    }
}

public static void main(String[] args) {
    System.out.println(fun(4));
}

Body:
If you mean functions that call itself more than once at times then Yes!

Base case: x < 1 ==> 1, thus fun(-1) as well as fun(0) substitutes to 1

fun(1)              ; == [substitute default case with result]
1 + fun(0) + fun(-1); == [substitute base cases]
1 + 1 + 1           ; ==> 3

fun(2)              ; == [substitute default case with result]
2 + fun(1) + fun(0) ; == [substitute fun(1) with previously calculated result]
2 + 3 + fun(0)      ; == [substitute base cases]
2 + 3 + 1           ; ==> 6

fun(3)              ; == [substitute default case with result]
3 + fun(2) + fun(1) ; == [substitute with previously calculated result]
3 + 6 + 3           ; ==> 12

fun(4)              ; == [substitute default case with result]
4 + fun(3) + fun(2) ; == [substitute with previously calculated results]
4 + 12 + 6          ; ==> 22

You could have started with fun(4) like this:

fun(4) ; == [expand default cases]
4 +
fun(3) +
fun(2) ; == [expand default cases]
4 +
3 + fun(2) + fun(1) +
2 + fun(1) + fun(0) ; == [expand fun(2) default case]

4 +
3 + (2 + fun(1) + fun(0)) + fun(1) +
2 + fun(1) + fun(0) ; == [group]

4 + 3 + 2*2 + 3*fun(1) + 2*fun(0) ; == [expand default cases]

4 + 3 + 2*2 + 2*fun(0) +
3*(1 + fun(0) + fun(-1)) ; == [group, group x<1 as b]

4 + 3+ 2*2 + 3*1 + 8*fun(b) ; == [expand base cases]
4 + 3+ 2*2 + 3*1 + 8*1      ; == [calculate]
; ==> 22

I find it slightly messier. Especially if you don't group the several calls together it can be a pain.

Notice that this cannot be done if the function result is not directly mapped to its argument. As a treat here is a better version of your function:

static int fun(int n) {
    return fun(n, 0, 1, 3);
}

static int fun(int n, int v, int a, int b) {
    return n >= v ? a : fun(n, v+1, b, a+b+n+2);
}

It seems to be consistent with the sequence A066982 except it omits the first element.


问:
apache pig, permutations of values grouped by id
Using Apache Pig, I need all permutations of a field, grouped by an id field ('title' in this case).  The input data looks like this:

schema is {chararray, chararray}

```<code>(title1, name1)
(title1, name2)
(title1, name3)
(title2, name4)
(title2, name5)
(title2, name6)
</code>```

I need all permutations of title1 name relations and title2 name relations in one list.  Desired output is:

```<code>(name1, name2)
(name1, name3)
(name2, name3)
(name4, name5)
(name4, name6)
(name5, name6)
</code>```

I found this related answer How To Find All Possible Permutations From A Bag under apache pig, but I'm having difficulties with extending the solution so that it limits the permutations for each title field.

答:
After doing some more searching, using these two posts:
How To Find All Possible Permutations From A Bag under apache pig , PIG: Get all tuples out of a grouped bag led me to this solution:

input schema is {chararray, chararray}

```<code>inpt = foreach input generate $0 as (id:chararray), $1 as (val);
grp = group inpt by (id);
id_grp = foreach grp generate group as id, inpt.val as value_bag;
result = foreach id_grp generate FLATTEN(value_bag) as v1,FLATTEN(value_bag) as v2;
result = filter result by v1 <= v2;
result = filter result by v1 != v2;
</code>```

Body:
Using Apache Pig, I need all permutations of a field, grouped by an id field ('title' in this case).  The input data looks like this:

schema is {chararray, chararray}

(title1, name1)
(title1, name2)
(title1, name3)
(title2, name4)
(title2, name5)
(title2, name6)

I need all permutations of title1 name relations and title2 name relations in one list.  Desired output is:

(name1, name2)
(name1, name3)
(name2, name3)
(name4, name5)
(name4, name6)
(name5, name6)

I found this related answer How To Find All Possible Permutations From A Bag under apache pig, but I'm having difficulties with extending the solution so that it limits the permutations for each title field.

Body:
After doing some more searching, using these two posts:
How To Find All Possible Permutations From A Bag under apache pig , PIG: Get all tuples out of a grouped bag led me to this solution:

input schema is {chararray, chararray}

inpt = foreach input generate $0 as (id:chararray), $1 as (val);
grp = group inpt by (id);
id_grp = foreach grp generate group as id, inpt.val as value_bag;
result = foreach id_grp generate FLATTEN(value_bag) as v1,FLATTEN(value_bag) as v2;
result = filter result by v1 <= v2;
result = filter result by v1 != v2;


问:
How to get the href value in c++ using regex?
I want to fetch the value of href in c++, but my code is not giving the desired result

```<code>#include <fstream>
#include <iostream>
#include <string>
#include <regex>

int main()
{

   std::regex url("/.*(href=')(.*)('>)/");
  std::string url_test = "hjsh.ppt";
    std::ifstream file("in.txt");
    if (!file.is_open())
    {
        std::cerr << "Failed to open file!\n";
        return -1;
    }

    const std::string needle = "href";

    while (std::getline(file, url_test))
    {
        if (url_test.find(needle) != std::string::npos)
        {
          if(regex_match(url_test, url)){}
            std::cout << url_test << "\n";

        }
    }
}
</code>```

The above code prints whole line as

```<code><a href="11_custom_io.ppt">Ch11: Customizing I/O</a>
</code>```

I want only 11_custom_io.ppt , name of the file.
Please Help.

答:
As already mentioned in comments it is not a good idea to parse XML or HTML using regexes. But if you want to get sub-match then you can use std::match_results. For example:

```<code>std::string line("<a href='11_custom_io.ppt'>Ch11: Customizing I/O</a>");
std::regex re("href='(.*)'>");
std::smatch match;

if ( std::regex_search(line, match, re) ) {
    std::cout << "sub-match " << match[1].str() << '\n';
}
</code>```

And output will be: sub-match 11_custom_io.ppt

Body:
I want to fetch the value of href in c++, but my code is not giving the desired result

#include <fstream>
#include <iostream>
#include <string>
#include <regex>

int main()
{

   std::regex url("/.*(href=')(.*)('>)/");
  std::string url_test = "hjsh.ppt";
    std::ifstream file("in.txt");
    if (!file.is_open())
    {
        std::cerr << "Failed to open file!\n";
        return -1;
    }

    const std::string needle = "href";

    while (std::getline(file, url_test))
    {
        if (url_test.find(needle) != std::string::npos)
        {
          if(regex_match(url_test, url)){}
            std::cout << url_test << "\n";

        }
    }
}

The above code prints whole line as

Ch11: Customizing I/O

I want only 11_custom_io.ppt , name of the file.
Please Help.

Body:
As already mentioned in comments it is not a good idea to parse XML or HTML using regexes. But if you want to get sub-match then you can use std::match_results. For example:

std::string line("<a href='11_custom_io.ppt'>Ch11: Customizing I/O</a>");
std::regex re("href='(.*)'>");
std::smatch match;

if ( std::regex_search(line, match, re) ) {
    std::cout << "sub-match " << match[1].str() << '\n';
}

And output will be: sub-match 11_custom_io.ppt


问:
WPF - ObservableCollection casting
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

```<code>public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}
</code>```

答:
Considering that the class should be ObservableCollection, try this:</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        var employees = new ObservableCollection<Employee>();
        var persons = employees.OfType<Person>();

        Test(new ObservableCollection<Person>(persons));
    }

    static void Test(ObservableCollection<Person> persons)
    {
        // Do something
    }
}

public class Person { }
public class Employee : Person { }
</code>```

Title: WPF - ObservableCollection casting

Body:
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}

Body:
Considering that the class should be ObservableCollection, try this:

class Program
{
    static void Main(string[] args)
    {
        var employees = new ObservableCollection<Employee>();
        var persons = employees.OfType<Person>();

        Test(new ObservableCollection<Person>(persons));
    }

    static void Test(ObservableCollection<Person> persons)
    {
        // Do something
    }
}

public class Person { }
public class Employee : Person { }


问:
How to ask permissions from a Service
I am implementing a service that uses LocationManager to get and utilize the tablet location. This service is start and stop from an activity.

The latest Android requires that permissions are requested on runtime. Now I have managed to do this on an activity by using requestPermission in onCreate , checkSelfPermission everytime I use some Location manager function, and adding the requestPermission function and overriding the onRequestPermissionResult.

It works great.

Now for my service I need to do the same, but these functions seems to work only for activities. How can I activate permissions in a Service?

just in case, I have already asked for permissions in the activity that starts and stops the services

答:
How can I activate permissions in a Service?

You can't request for permissions from services. Permissions should be asked explicitly which should be visible to the user in UI. However you can ask permission from activity and, if succeed, you can access those resources until user again turned off permission for your app.

how can you "transfer" these permissions to the service?

Permission is assigned for the entire app, so you don't need to transfer it from one activity to another or from one activity to service. Once you get a permission in an Activity, that permission is assigned to the entire app and your services can access the resources then after. cheers :)

Title: How to ask permissions from a Service


问:
Testing PayPal with Rails
I need to test a new PayPal integration with my application. I use PayPal sandbox in development env.

In order to test the entire interface, I figured out that ngrok might solve the problem of messages from PayPal.

I installed ngrok using apt-get install ngrok-client on my new Ubuntu 16.04 instalation.

When I try to run it (ngrok 3000, ngrok 80) I get the following error:

```<code>Invalid address server_addr 'ngrokd.ngrok.com:443': lookup ngrokd.ngrok.com: no such host
</code>```

Any idea?

Any other solution to test PayPal integration?

==================== EDIT ==================

Very important - if youi use Rails 4.2.0, have a look at this tutorial, it might save you some hours of frustration:

https://www.youtube.com/watch?v=YXKNxEv35HU

答:
I supposed you installed ngrok from package manager with this command

```<code>$ sudo apt-get install ngrok-client
</code>```

But it no longer work because it's the 1.6 version.

You have to download a new version on official page. Then you can run it like this:

```<code>$ ./ngrok http 3000
</code>```

Title: Testing PayPal with Rails

Body:
I need to test a new PayPal integration with my application. I use PayPal sandbox in development env.

In order to test the entire interface, I figured out that ngrok might solve the problem of messages from PayPal.

I installed ngrok using apt-get install ngrok-client on my new Ubuntu 16.04 instalation.

When I try to run it (ngrok 3000, ngrok 80) I get the following error:

Invalid address server_addr 'ngrokd.ngrok.com:443': lookup ngrokd.ngrok.com: no such host

Any idea?

Any other solution to test PayPal integration?

==================== EDIT ==================

Very important - if youi use Rails 4.2.0, have a look at this tutorial, it might save you some hours of frustration:

https://www.youtube.com/watch?v=YXKNxEv35HU

Body:
I supposed you installed ngrok from package manager with this command

$ sudo apt-get install ngrok-client

But it no longer work because it's the 1.6 version.

You have to download a new version on official page. Then you can run it like this:

$ ./ngrok http 3000


答:
You should join the user table twice using alias </p>

```<code>  select  msg.sender, u1.name  as sender_name, msg.receiver, u2.name as receiver_name
  from msg
  inner join users u1 on u1.id =  msg.sender
  inner join users u2 on u2.id =  msg.receiver
</code>```

Title: MySQL query to display name from sender and receiver

Body:
I have a table called  users  which looks like this:

 +----+----------------+
 | id | name           |
 +----+----------------+
 |  1 | Blake          |
 |  2 | Jenn           |
 +----+----------------+

And i have a table called  msg  which looks like this:

 +----+----------------+----------------+
 | id | sender         | receiver       |
 +----+----------------+----------------+
 |  1 | 1              | 2              |
 |  2 | 2              | 1              |
 +----+----------------+----------------+

So now i have a problem because i can't figure out how to join msg.sender(id) to users.name(name).

So basicly what i want to end up with, looks kind of like this:

 +----+----------------+----------------+----------------+----------------+
 | id | sender         | sender_name    | receiver       | receiver_name  |
 +----+----------------+----------------+----------------+----------------+
 |  1 | 1              | Blake          | 2              | Jenn           |
 |  2 | 2              | Jenn           | 1              | Blake          |
 +----+----------------+----------------+----------------+----------------+

I hope these illustrations kind of help with what I'm trying to explain.

Body:
You should join the user table twice using alias

  select  msg.sender, u1.name  as sender_name, msg.receiver, u2.name as receiver_name
  from msg
  inner join users u1 on u1.id =  msg.sender
  inner join users u2 on u2.id =  msg.receiver


答:
Just join the users table twice with msg table - Once on sender and  then on receiver.

```<code>select m.*,
    s.name as sender_name,
    r.name as receiver_name
from msg m
join users s on m.sender = s.id
join users r on m.receiver = r.id;
</code>```

Body:
Just join the users table twice with msg table - Once on sender and  then on receiver.

select m.*,
    s.name as sender_name,
    r.name as receiver_name
from msg m
join users s on m.sender = s.id
join users r on m.receiver = r.id;


问:
How to get json-server, when used as module, to delay responses?
json-server allows one to configure responses to be delayed via the command line:

```<code>json-server --port 4000 --delay 1000 db.json
</code>```

How does one try to do this when using json-server as a module? The following doesn't work:

```<code>const jsonServer = require('json-server')
var server = jsonServer.create();

server.use(jsonServer.defaults());
server.use(jsonServer.router("db.json"));
server.use(function(req, res, next) {
    setTimeout(next, 1000);
});

server.listen(4000);
</code>```

It just ignores the setTimeout function completely and doesn't execute it.

答:
The order is important. Middlewares should be before the router. If you move your timeout before server.use(jsonServer.router("db.json")); it should work.

Here is my working example:

```<code>var app = jsonServer.create();
var router = jsonServer.router(path.join(__dirname, '../../test/api/dev.json'));
var middlewares = jsonServer.defaults();

app.use(function(req, res, next){
  setTimeout(next, 10000);
});
app.use(middlewares);
app.use(router);

server = app.listen(3000, function () {
  console.log('JSON Server is running on localhost:3000');
  done();
});
</code>```

Body:
json-server allows one to configure responses to be delayed via the command line:

json-server --port 4000 --delay 1000 db.json

How does one try to do this when using json-server as a module? The following doesn't work:

const jsonServer = require('json-server')
var server = jsonServer.create();

server.use(jsonServer.defaults());
server.use(jsonServer.router("db.json"));
server.use(function(req, res, next) {
    setTimeout(next, 1000);
});

server.listen(4000);

It just ignores the setTimeout function completely and doesn't execute it.

Body:
The order is important. Middlewares should be before the router. If you move your timeout before server.use(jsonServer.router("db.json")); it should work.

Here is my working example:

var app = jsonServer.create();
var router = jsonServer.router(path.join(__dirname, '../../test/api/dev.json'));
var middlewares = jsonServer.defaults();

app.use(function(req, res, next){
  setTimeout(next, 10000);
});
app.use(middlewares);
app.use(router);

server = app.listen(3000, function () {
  console.log('JSON Server is running on localhost:3000');
  done();
});


答:
How can I activate permissions in a Service?

You don't. You activate (i.e., request) permissions from an activity. That is not negotiable.

Ideally, you request permissions before the activity starts the service or does something that will eventually cause the service to start (e.g., schedules the job with JobScheduler).

If you determine that your service no longer has the necessary permissions — perhaps the user revoked them from Settings — you could raise a Notification that leads the user to an activity where you re-request the permissions.

It is technically possible for a service to start an activity which requests the permissions. Usually, this is not a good idea, as you may not know what the user is doing at that moment, and the user may be unhappy to have you interrupt them with this permission request.

Title: How to ask permissions from a Service

Body:
I am implementing a service that uses LocationManager to get and utilize the tablet location. This service is start and stop from an activity.

The latest Android requires that permissions are requested on runtime. Now I have managed to do this on an activity by using requestPermission in onCreate , checkSelfPermission everytime I use some Location manager function, and adding the requestPermission function and overriding the onRequestPermissionResult.

It works great.

Now for my service I need to do the same, but these functions seems to work only for activities. How can I activate permissions in a Service?

just in case, I have already asked for permissions in the activity that starts and stops the services


问:
changing default to function django
so im trying to change the default language according to a setting a user made before. My problem is that the value of the function im calling is 'English' or 'Spanish' but I need a short term like 'en' or 'esp' to make it actually work. I also have this error message when I try to try to run it: userlang() takes exactly 1 argument (0 given)

so here is what I tried:

```<code>def userlang(self):
    return (self.user.userprofile.language)

class 123(models.Model
    language = models.CharField(verbose_name=_(u"Language"),
               max_length=4, choices=settings.LANGUAGES,default=userlang)
</code>```

I hope somebody can help me out.

答:
You can use such a thing:

```<code>class CustomModel(models.Model):
    language = gender = models.CharField(
        max_length=2,
        choices=(('en', 'English'),('es', 'Spanish')),
        default=None,
        blank=True,
        null=True
    )
</code>```

Then it's pretty straight forward to use.

Of course if you have hundred of possibilities for the language, you should do a OneToMany association and not using such a pattern.

Btw. Your example is very badly formatted and written. For the error you have, just remove "self" in the arguments of your function... It's only required when it's class method.

Title: changing default to function django

Body:
so im trying to change the default language according to a setting a user made before. My problem is that the value of the function im calling is 'English' or 'Spanish' but I need a short term like 'en' or 'esp' to make it actually work. I also have this error message when I try to try to run it: userlang() takes exactly 1 argument (0 given)

so here is what I tried:

def userlang(self):
    return (self.user.userprofile.language)

class 123(models.Model
    language = models.CharField(verbose_name=_(u"Language"),
               max_length=4, choices=settings.LANGUAGES,default=userlang)

I hope somebody can help me out.

Body:
You can use such a thing:

class CustomModel(models.Model):
    language = gender = models.CharField(
        max_length=2,
        choices=(('en', 'English'),('es', 'Spanish')),
        default=None,
        blank=True,
        null=True
    )

Then it's pretty straight forward to use.

Of course if you have hundred of possibilities for the language, you should do a OneToMany association and not using such a pattern.

Btw. Your example is very badly formatted and written. For the error you have, just remove "self" in the arguments of your function... It's only required when it's class method.