问:
How to query amount of allocated memory on Linux (and OSX)?
While this might look like a duplicate from other questions, let me explain why it's not.

I am looking to get a specific part of my application to degrade gracefully when a certain memory limit has been reached.  I could have used criteria based on remaining available physical memory, but this wouldn't be safe, because the OS could start paging out memory used by my application before reaching the criteria, which would think there is still some physical memory left, and keep allocating, etc.  For the same reason, I can't used the amount of physical memory currently used by the process, because as soon as the OS would start swapping me out, I would keep allocating as the OS pages memory so the number would not grow anymore.

For this reason, I chose a criteria based on the amount of memory allocated by my application, i.e. very close to virtual memory size.

This question (How to determine CPU and memory consumption from inside a process?) provides great ways of querying the amount of virtual memory used by the current process, which I THOUGHT was what I needed.

On Windows, I'm using GetProcessMemoryInfo() and the PrivateUsage field, which works great.

On Linux, I tried several things (listed below) that did not work.  The reason why virtual memory usage does not work for me is because of something that happens with OpenCL context creation on NVidia hardware on Linux.  The driver reserves a region of the virtual memory space big enough to hold all RAM, all swap and all video memory.  My guess is it does so for unified address space and everything.  But it also means that the process reports using enormous amounts of memory.  On my system for instance, top will report 23.3 Gb in the VIRT column (12 Gb of RAM, 6 Gb of swap, 2 Gb of video memory, which gives 20 Gb reserved by the NVidia driver).

On OSX, by using task_info() and the virtual_size field, I also get a bigger than expected number (a few Gb for an app that takes not even close to 1 Gb on Windows), but not as big as Linux.

So here is the big question: how can I get the amount of memory allocated by my application?  I know that this is a somewhat vague question (what does "allocated memory" means?), but I'm flexible:

I would prefer to include the application static data, code section and everything, but I can live without.

I would prefer to include the memory allocated for stacks, but I can live without.

I would prefer to include the memory used by shared libraries, but I can live without.

I don't really care for mmap stuff, I can do with or without at that point.

Etc.

What is really important is that the number grows with dynamic allocation (new, malloc, anything) and shrinks when the memory is released (which I know can be implementation-dependent).

Things I have tried

Here are a couple of solutions I have tried and/or thought of but that would not work for me.

Read from /proc/self/status

This is the approach suggested by how-to-determine-cpu-and-memory-consumption-from-inside-a-process.  However, as stated above, this returns the amount of virtual memory, which does not work for me.

Read from /proc/self/statm

Very slightly worst: according to http://kernelnewbies.kernelnewbies.narkive.com/iG9xCmwB/proc-pid-statm-doesnt-match-with-status, which refers to Linux kernel code, the only difference between those two values is that the second one does not substract reserved_vm to the amount of virtual memory.  I would have HOPED that reserved_vm would include the memory reserved by the OpenCL driver, but it does not.

Use mallinfo() and the uordblks field

This does not seem to include all the allocations (I'm guessing the news are missing), since for an +2Gb growth in virtual memory space (after doing some memory-heavy work and still holding the memory), I'm only seeing about 0.1Gb growth in the number returned by mallinfo().

Read the [heap] section size from /proc/self/smaps

This value started at around 336,760 Kb and peaked at 1,019,496 Kb for work that grew virtual memory space by +2Gb, and then it never gets down, so I'm not sure I can't really rely on this number...

Monitor all memory allocations in my application

Yes, in an ideal world, I would have control over everybody who allocates memory.  However, this is a legacy application, using tons of different allocators, some mallocs, some news, some OS-specific routines, etc.  There are some plug-ins that could do whatever they want, they could be compiled with a different compiler, etc.  So while this would be great to really control memory, this does not work in my context.

Read the virtual memory size before and after the OpenCL context initialization

While this could be a "hacky" way to solve the problem (and I might have to fallback to it), I would really wish for a more reliable way to query memory, because OpenCL context could be initialized somewhere out of my control, and other similar but non-OpenCL specific issues could creep in and I wouldn't know about it.

So that's pretty much all I've got.  There is one more thing I have not tried yet, because it only works on OSX, but it is to use the approach described in Why does mstats and malloc_zone_statistics not show recovered memory after free?, i.e. use malloc_get_all_zones() and malloc_zone_statistics(), but I think this might be the same problem as mallinfo(), i.e. not take all allocations into account.

So, can anyone suggest a way to query memory usage (as vague of a term as this is, see above for precision) of a given process in Linux (and also OSX even if it's a different method)?

答:
Here is what I ended up using.  I scan /proc/self/maps and sum the size of all the address ranges meeting my criteria, which is:

Only include ranges from inode 0 (i.e. no devices, no mapped file, etc.)

Only include ranges that are at least one of readable, writable or executable

Only include private memory

In my experiments I did not see instances of shared memory from inode 0.  Maybe with inter-process shared memory...?

Here is the code for my solution:

```<code>size_t getValue()
{
    FILE* file = fopen("/proc/self/maps", "r");
    if (!file)
    {
        assert(0);
        return 0;
    }

    size_t value = 0;

    char line[1024];
    while (fgets(line, 1024, file) != NULL)
    {
        ptrdiff_t start_address, end_address;
        char perms[4];
        ptrdiff_t offset;
        int dev_major, dev_minor;
        unsigned long int inode;
        const int nb_scanned = sscanf(
            line, "%16tx-%16tx %c%c%c%c %16tx %02x:%02x %lu",
            &start_address, &end_address,
            &perms[0], &perms[1], &perms[2], &perms[3],
            &offset, &dev_major, &dev_minor, &inode
            );
        if (10 != nb_scanned)
        {
            assert(0);
            continue;
        }

        if ((inode == 0) &&
            (perms[0] != '-' || perms[1] != '-' || perms[2] != '-') &&
            (perms[3] == 'p'))
        {
            assert(dev_major == 0);
            assert(dev_minor == 0);
            value += (end_address - start_address);
        }
    }

    fclose(file);

    return value;
}
</code>```

Since this is looping through all the lines in /proc/self/maps, querying memory that way is significantly slower than using "Virtual Memory currently used by current process" from How to determine CPU and memory consumption from inside a process?.

However, it provides an answer much closer to what I need.

Body:
Here is what I ended up using.  I scan /proc/self/maps and sum the size of all the address ranges meeting my criteria, which is:

Only include ranges from inode 0 (i.e. no devices, no mapped file, etc.)

Only include ranges that are at least one of readable, writable or executable

Only include private memory

In my experiments I did not see instances of shared memory from inode 0.  Maybe with inter-process shared memory...?

Here is the code for my solution:

size_t getValue()
{
    FILE* file = fopen("/proc/self/maps", "r");
    if (!file)
    {
        assert(0);
        return 0;
    }

    size_t value = 0;

    char line[1024];
    while (fgets(line, 1024, file) != NULL)
    {
        ptrdiff_t start_address, end_address;
        char perms[4];
        ptrdiff_t offset;
        int dev_major, dev_minor;
        unsigned long int inode;
        const int nb_scanned = sscanf(
            line, "%16tx-%16tx %c%c%c%c %16tx %02x:%02x %lu",
            &start_address, &end_address,
            &perms[0], &perms[1], &perms[2], &perms[3],
            &offset, &dev_major, &dev_minor, &inode
            );
        if (10 != nb_scanned)
        {
            assert(0);
            continue;
        }

        if ((inode == 0) &&
            (perms[0] != '-' || perms[1] != '-' || perms[2] != '-') &&
            (perms[3] == 'p'))
        {
            assert(dev_major == 0);
            assert(dev_minor == 0);
            value += (end_address - start_address);
        }
    }

    fclose(file);

    return value;
}

Since this is looping through all the lines in /proc/self/maps, querying memory that way is significantly slower than using "Virtual Memory currently used by current process" from How to determine CPU and memory consumption from inside a process?.

However, it provides an answer much closer to what I need.


来源: stackexchange

问:
(Should be easy) Selenium chromedriver (java) no element found error
I tried this exact code on other websites and it seems to work fine. It's just on pizza hut that it can't even locate an element let alone click on it. Thread.sleep() doesn't make a difference. The problem is between the commented *, according to the compiler. Here's the code.</p>

```<code>package training;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PizzaHut {

WebDriver driver;
@Test
public void open() throws Exception {
        //SET UP WEBDRIVER AND OPEN WEBSITE
        System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.pizzahut.com/#/home");
        Thread.sleep(1000);

        //CLICK PIZZA
        Thread.sleep(5000);
        test("before");
        //**************PROBLEM*CODE**********************
        driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();
        //************************************************
        test("clicked pizza");

        //CLOSE BROWSER
        Thread.sleep(15000);
        driver.close();
    }

    public static void test(String x) {
        System.out.println(x);
    }
}
</code>```

答:
You are not able to click it because it is an AngularJS tag, hence it takes some time to load: add some wait like below and it works (Here i'm just adding thread.sleep for the sake of simplicity,I've increased it to 15000ms):</p>

```<code>    //CLICK PIZZA
    Thread.sleep(15000);
    test("before");
    //**************PROBLEM*CODE**********************
    driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried this exact code on other websites and it seems to work fine. It's just on pizza hut that it can't even locate an element let alone click on it. Thread.sleep() doesn't make a difference. The problem is between the commented *, according to the compiler. Here's the code.

package training;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PizzaHut {

WebDriver driver;
@Test
public void open() throws Exception {
        //SET UP WEBDRIVER AND OPEN WEBSITE
        System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.pizzahut.com/#/home");
        Thread.sleep(1000);

        //CLICK PIZZA
        Thread.sleep(5000);
        test("before");
        //**************PROBLEM*CODE**********************
        driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();
        //************************************************
        test("clicked pizza");

        //CLOSE BROWSER
        Thread.sleep(15000);
        driver.close();
    }

    public static void test(String x) {
        System.out.println(x);
    }
}

Body:
You are not able to click it because it is an AngularJS tag, hence it takes some time to load: add some wait like below and it works (Here i'm just adding thread.sleep for the sake of simplicity,I've increased it to 15000ms):

    //CLICK PIZZA
    Thread.sleep(15000);
    test("before");
    //**************PROBLEM*CODE**********************
    driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();


问:
How can I configure IntelliJ IDEA to format block comments like Eclipse does?
How can I configure IntelliJ (for Groovy and Java) to format regular non-Javadoc block comments like Eclipse (with a * preceding each line)?

I'm pretty new to IntelliJ, and I haven't noticed a code formatter setting that seems applicable.

EXAMPLES

This is how IntelliJ formats these comments by default (which I think is particularly ugly):

```<code>/*
This
is
a block comment.
 */
</code>```

This is how Eclipse formats these comments by default, and what I'd like IntelliJ to do:

```<code>/*
 * This
 * is
 * a block comment.
 */
</code>```

答:
You cannot directly enable this in IntelliJ IDEA.

Idea does this just for JavaDoc comments. When you start your comment with /**, Idea will automatically add * to each new line when hitting Enter.

Body:
How can I configure IntelliJ (for Groovy and Java) to format regular non-Javadoc block comments like Eclipse (with a * preceding each line)?

I'm pretty new to IntelliJ, and I haven't noticed a code formatter setting that seems applicable.

EXAMPLES

This is how IntelliJ formats these comments by default (which I think is particularly ugly):

/*
This
is
a block comment.
 */

This is how Eclipse formats these comments by default, and what I'd like IntelliJ to do:

/*
 * This
 * is
 * a block comment.
 */


问:
Difference between ISR of a RTOS vs General Purpose OS
I am learning about ISR but I can not find what is the difference bewteen an interrupt service routine of a RTOS vs a General Purpose OS. Can anyone please explain the differecne between them, if there is any?</p>

答:
In an RTOS, exiting the interrupt context normally causes the scheduler to run (the ISR will have an interrupt epilogue that does this) in order to determine the highest priority ready task (which may have changed if the ISR has signalled a task in any way).  In a GPOS (General-purpose OS) on the other hand task switching is normally performed on a time-slice basis so the scheduler runs only on the OS clock interrupt.

To put it another way in a GPOS, on completion of an ISR it normally returns to whichever task was interrupted, while in an RTOS it evaluates the task schedule and switches context to the highest priority task in the ready state.


问:
How to retrieve children that has particular value to it?
I'm thinking of building a mobile App that can fetch data based on the tags provided by the user.

The app is about suggesting some Gifts based on user Input. For Example, A user selects Tags : "Male", "Birthday", "under30". The API should able to provide list of items matching this criteria.

```<code>{
  "gifts" : {
    "\"93c08520-14ea-11e7-855f-e957e315db04\"" : {
      "Description" : "SomeDescription",
      "Name" : "Some GIFT",
      "Tags" : [ "wedding", "graduation", "Easter" ],
      "id" : "93c08520-14ea-11e7-855f-e957e315db04"
    },
    "\"93d48250-14ea-11e7-855f-e957e315db04\"" : {
      "Description" : "SomeDescription",
      "Name" : "Some GIFT",
      "Tags" : [ "birthday", "graduation", "anniversary" ],
      "id" : "93d48250-14ea-11e7-855f-e957e315db04"
    },
    "\"93e487e0-14ea-11e7-855f-e957e315db04\"" : {
      "Description" : "SomeDescription",
      "Name" : "Some GIFT",
      "Tags" : [ "graduation", "wedding", "birthday" ],
      "id" : "93e487e0-14ea-11e7-855f-e957e315db04"
    }
}
</code>```

I came up with this kinda of structure with firebase, and Playing about with orderByValue and OrderByKey.

Please suggest some ways to order my data and ways to retrieve them using Firebase Query Param(RESTful).

答:
Please avoid using arrays. They are very limited; individual elements cannot be accessed and if you need to add, edit or delete anything in the array the entire array must be updated and re-written. See Arrays Are Evil.

To answer the question; when you want to query for more than one parameter you need to either

```<code>1) Nest your queries - can get quite complex
2) Filter in code - with a large dataset can be to much
3) Combine your parameters into a single child.
</code>```

Here's the 3) way. Assume you have a set number of tags:

```<code>male
female
birthday
age
</code>```

and a structure

```<code>Gifts
  gift_0
    desc: "asdas"
    name: "assad"
    male: true
    birthday: true
    age: 30
    query: male_birthday_30
  gift_1
    desc: "asdas"
    name: "assad"
    female: true
    anniversary: true
    age: 28
    query: female_anniversary_28
  gift_2
    desc: "asdas"
    name: "assad"
    male: true
    birthday: true
    age: 35
    query: male_birthday_35
</code>```

With this structure you can easily query all gifts for males or females, gifts for people of a certain age or between ages or for birthday or anniversary.

The query child node enables you to extend that with the ability to query for male_birthday gifts or female_annivesary gifts but also enables you to capture a range of ages: (here's some pseudo code)

```<code>query.startingAt("male_birthday_30").endingAt("male_birthday_35")
</code>```

You can extend that farther with a little cross referencing. Let's define a few variables to stand for different combinations of events...

```<code>  combo0 = birthday
  combo1 = birthday and anniversary
  combo2 = birthday and anniversary and graduation
</code>```

then a gift node would look like this

```<code>  gift_0
    desc: "asdas"
    name: "assad"
    male: true
    birthday: true
    anniversary: true
    age: 30
    query: male_combo1_30
</code>```

and the query

```<code>query.startingAt("male_combo1_30").endingAt("male_combo1_35")
</code>```

which would return all gifts for males that are appropriate for birthday and anniversary who are between 30 and 35.

Using that technique you can make some wickedly complex queries.

Body:
I'm thinking of building a mobile App that can fetch data based on the tags provided by the user.

The app is about suggesting some Gifts based on user Input. For Example, A user selects Tags : "Male", "Birthday", "under30". The API should able to provide list of items matching this criteria.

{
  "gifts" : {
    "\"93c08520-14ea-11e7-855f-e957e315db04\"" : {
      "Description" : "SomeDescription",
      "Name" : "Some GIFT",
      "Tags" : [ "wedding", "graduation", "Easter" ],
      "id" : "93c08520-14ea-11e7-855f-e957e315db04"
    },
    "\"93d48250-14ea-11e7-855f-e957e315db04\"" : {
      "Description" : "SomeDescription",
      "Name" : "Some GIFT",
      "Tags" : [ "birthday", "graduation", "anniversary" ],
      "id" : "93d48250-14ea-11e7-855f-e957e315db04"
    },
    "\"93e487e0-14ea-11e7-855f-e957e315db04\"" : {
      "Description" : "SomeDescription",
      "Name" : "Some GIFT",
      "Tags" : [ "graduation", "wedding", "birthday" ],
      "id" : "93e487e0-14ea-11e7-855f-e957e315db04"
    }
}

I came up with this kinda of structure with firebase, and Playing about with orderByValue and OrderByKey.

Please suggest some ways to order my data and ways to retrieve them using Firebase Query Param(RESTful).

Body:
Please avoid using arrays. They are very limited; individual elements cannot be accessed and if you need to add, edit or delete anything in the array the entire array must be updated and re-written. See Arrays Are Evil.

To answer the question; when you want to query for more than one parameter you need to either

1) Nest your queries - can get quite complex
2) Filter in code - with a large dataset can be to much
3) Combine your parameters into a single child.

Here's the 3) way. Assume you have a set number of tags:

male
female
birthday
age

and a structure

Gifts
  gift_0
    desc: "asdas"
    name: "assad"
    male: true
    birthday: true
    age: 30
    query: male_birthday_30
  gift_1
    desc: "asdas"
    name: "assad"
    female: true
    anniversary: true
    age: 28
    query: female_anniversary_28
  gift_2
    desc: "asdas"
    name: "assad"
    male: true
    birthday: true
    age: 35
    query: male_birthday_35

With this structure you can easily query all gifts for males or females, gifts for people of a certain age or between ages or for birthday or anniversary.

The query child node enables you to extend that with the ability to query for male_birthday gifts or female_annivesary gifts but also enables you to capture a range of ages: (here's some pseudo code)

query.startingAt("male_birthday_30").endingAt("male_birthday_35")

You can extend that farther with a little cross referencing. Let's define a few variables to stand for different combinations of events...

  combo0 = birthday
  combo1 = birthday and anniversary
  combo2 = birthday and anniversary and graduation

then a gift node would look like this

  gift_0
    desc: "asdas"
    name: "assad"
    male: true
    birthday: true
    anniversary: true
    age: 30
    query: male_combo1_30

and the query

query.startingAt("male_combo1_30").endingAt("male_combo1_35")

which would return all gifts for males that are appropriate for birthday and anniversary who are between 30 and 35.

Using that technique you can make some wickedly complex queries.


问:
Broken images displaying image from database
Hello i am trying to retrieve image stored in database as BLOB however it is coming back as broken so the image doesnt display what am i doing wrong code below.</p>

```<code><?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);

while($row = mysqli_fetch_array($result)){

    echo '<tr>';
    echo '<td>';
    echo '<img src="data:image/jpeg;base64,'.base64_encode($row['photo'] ).'" height="100" width="100" class="img-thumnail" />';
    echo '</td>';
    echo '</tr>';
}
?>
</code>```

答:
Use addslashes function while save BLOB image into database. Because apostrophe ' may broken your image, addslashes function replace ' with \' which solve the problem.

For Inserting BLOB image into DataBase

```<code>$connect = mysqli_connect("localhost", "root", "", "testing");
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO item (item_id,photo) VALUES('','$image')";
$result = mysqli_query($connect, $query);
</code>```

For Accessing BLOB image From DB

```<code>$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result)){

    echo '<tr>';
    echo '<td>';
    echo '<img src="data:image/jpeg;base64,'.base64_encode($row['photo'] ).'" height="100" width="100" class="img-thumnail" />';
    echo '</td>';
    echo '</tr>';
}
</code>```

Body:
Hello i am trying to retrieve image stored in database as BLOB however it is coming back as broken so the image doesnt display what am i doing wrong code below.

<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);

while($row = mysqli_fetch_array($result)){

    echo '
';
    echo '';
    echo '';
    echo '	';
    echo '
';
}
?>

Body:
Use addslashes function while save BLOB image into database. Because apostrophe ' may broken your image, addslashes function replace ' with \' which solve the problem.

For Inserting BLOB image into DataBase

$connect = mysqli_connect("localhost", "root", "", "testing");
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO item (item_id,photo) VALUES('','$image')";
$result = mysqli_query($connect, $query);

For Accessing BLOB image From DB

$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result)){

    echo '<tr>';
    echo '<td>';
    echo '<img src="data:image/jpeg;base64,'.base64_encode($row['photo'] ).'" height="100" width="100" class="img-thumnail" />';
    echo '</td>';
    echo '</tr>';
}


问:
Can't access JSON attribute.
```<code>alert(fetch('https://facebook.github.io/react-native/movies.json')
    .then(function(response) {
        return response.json()['description']
    }))
</code>```

I was expecting Your app fetched this from a remote endpoint! but apparently, this is just an Object?

According to the other answers I've checked, like this one, this should work perfectly.

答:
response.json returns a Promise

```<code>.then(function(response) {
    return response.json()
})
.then(function(data) {
   return data.description
})
.then(function(description) {
    alert(description)
 })
</code>```

Title: Can't access JSON attribute.

Body:
alert(fetch('https://facebook.github.io/react-native/movies.json')
    .then(function(response) {
        return response.json()['description']
    }))

I was expecting Your app fetched this from a remote endpoint! but apparently, this is just an Object?

According to the other answers I've checked, like this one, this should work perfectly.

Body:
response.json returns a Promise

.then(function(response) {
    return response.json()
})
.then(function(data) {
   return data.description
})
.then(function(description) {
    alert(description)
 })


问:
Jaxb generated xml - problem with root element prefix
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

```<code> <report>
   <id>rep 1</id>
</report>
</code>```

, But getting as

```<code><ns2:report>
....
</ns2:report>
</code>```

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

答: The blog entry Customizing JAXB shows the alternatives provided by implementing a PreferredMapper . Unfortunately it explains, that is not possible to fully suppress namespaces.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

 <report>
   <id>rep 1</id>
</report>

, But getting as

<ns2:report>
....
</ns2:report>

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help


问:
Connection pool with single connection vs connection for infrequent queries
I am building a Java application which queries my SQL server once a minute. Right now, the application is using a connection pool with a single connection (min pool size 1, max pool size 1).

I figured that a pool size of 1 would be enough because of the infrequent queries (once a minute, as mentioned before).

Do I need a connection pool at all, and if the answer is yes, is 1 connection enough? Or should I just not use a pool and open a new connection every minute?

答:
I would like to give some reason to use the connection pool, potentially with multiple connections. Not sure if you are considering this negative case.

In real world, a query might run more than 1 minute with various reason.
Do you want the application to wait for the hung connection? Or what is your expected behavior for this?

Also if you use connection pool, DB connection initialize process(time and resource consuming) is done while the pool is generated. When you actually use the DB connection pool, some of initialization step should be already done so it reduce repetitive overhead when the application is running query.


问:
Can i add, modify and remove folders using minor upgrade in installshield
I need to add, modify, remove and change folder structure and send it as a upgrade file. Can i achieve this with minor upgrade feature in the Install-shield software. Explain the difference between small, minor and major upgrades.</p>

答:
Installation projects usually do not operate with bare "files" and "folders", instead they operate with "features" and "components". This is exactly you should be looking for in your existing project. As the simple answer you can remove or add folders with minor upgrade, but this is not a good idea. You should be operating with features and components to re-structure your project and add/remove folders and files.

This is the first line of Google search for your question "Explain the difference between small, minor and major upgrades." : Major Upgrade vs. Minor Upgrade vs. Small Update. Please consider do more reading before posting the question.


问:
Swift: UIButton vs UIView
In Swift, it appears as though similar behavior can be achieved from a UIButton and a UIView. To give functionality to a button, addTarget can be called, whereas addGestureRecognizer can be called for a UIView. When should one be used over another? In particular, when images are involved, is it better to use a UIButton paired with setImage or UIImageView paired with my_image_view.image = UIImage(...)?

Additionally, what does a UIButton offer that a UIView doesn't (and vice versa)? Thanks!

答:
The choice is up to you but UIButton is made for if you want a view to be touchable. Moreover, the UIButton class includes every visual effects needed on a button (on press for example). It also has some attribute as selected which can be useful for some uses.

To sum up, if the primary goal of your view is to be clickable, then you should use UIButton.

Title: Swift: UIButton vs UIView


问:
Is It Possible to Make Every Instance of a Word on a Website Non-Breaking?
We have a hyphenated word that we use frequently on our website and we never want it to wrap or break - we always want the two parts of the word on the same line.

Is there a way to make every instance of this word on the site non-breaking or do I have to do it with something like "white-space: nowrap" in a span around every instance of the word?

Ideally, would love to be able to do an update where every instance of the word that exists on the site becomes non-breaking, without having to manually go and update each word.

Thanks!

答:
Here's a function that recursively changes hyphens to non-breaking hyphens for all text nodes:

function changeHyphens(element) {
  var nodes = element.childNodes;
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].nodeType === 1) { //this is an element node
      changeHyphens(nodes[i]);
    } else if (nodes[i].nodeType === 3) { //this is a text node
      nodes[i].nodeValue = nodes[i].nodeValue.replace(/-/g, '\u2011');
    }
  }
} //changeNodes

changeHyphens(document.body);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  this-is-a-test this-is-a-longer-test this-is-a-longest-test-that-should-not-break this-is-a-test this-is-a-longer-test this-is-a-test-that-should-not-break this-is-a-test this-is-a-longer-test this-is-a-longest-test-that-should-not-break this-is-a-test
  this-is-a-longer-test this-is-a-test-that-should-not-break
</p></code>```

Body:
Here's a function that recursively changes hyphens to non-breaking hyphens for all text nodes:

function changeHyphens(element) {
  var nodes = element.childNodes;
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].nodeType === 1) { //this is an element node
      changeHyphens(nodes[i]);
    } else if (nodes[i].nodeType === 3) { //this is a text node
      nodes[i].nodeValue = nodes[i].nodeValue.replace(/-/g, '\u2011');
    }
  }
} //changeNodes

changeHyphens(document.body);

<p>
  this-is-a-test this-is-a-longer-test this-is-a-longest-test-that-should-not-break this-is-a-test this-is-a-longer-test this-is-a-test-that-should-not-break this-is-a-test this-is-a-longer-test this-is-a-longest-test-that-should-not-break this-is-a-test
  this-is-a-longer-test this-is-a-test-that-should-not-break
</p>


问:
How to make attributed string within a UITextView accessible?
By default the screen reader will select the entire view, and the link isn't able to be followed on a double tap. In fact, pressing activate on the accessibility inspector crashes the app delegate without any stack trace in the console. I've tried messing with the accessibility traits within the UITextView itself but I didn't have any luck.

```<code>let quoteAttributedStr = NSMutableAttributedString(string: "This is a test String" + " ")
                let enableLinkText = NSAttributedString(string: "this is the clickable text", attributes: dummyLinkAttribute)
                quoteAttributedStr.append(enableLinkText)

                return quoteAttributedStr
</code>```

答:
To make a portion of the NSMutableAttributedString selectable, you'll need to set it as a link like so:

```<code>quoteAttributedStr.setAsLink("string that you wish to be selectable goes here", linkURL: "url")
</code>```

You'll also need to add the UITextViewDelegate, and add:

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
}
</code>```

to handle it.

Here's an extension for the setAsLink that I forgot to include:

```<code>extension NSMutableAttributedString {

public func setAsLink(_ textToFind:String, linkURL:String) -> Bool {

    let foundRange = self.mutableString.range(of: textToFind)
    if foundRange.location != NSNotFound {
        self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
        return true
    }
    return false
}
}
</code>```

Body:
By default the screen reader will select the entire view, and the link isn't able to be followed on a double tap. In fact, pressing activate on the accessibility inspector crashes the app delegate without any stack trace in the console. I've tried messing with the accessibility traits within the UITextView itself but I didn't have any luck.

let quoteAttributedStr = NSMutableAttributedString(string: "This is a test String" + " ")
                let enableLinkText = NSAttributedString(string: "this is the clickable text", attributes: dummyLinkAttribute)
                quoteAttributedStr.append(enableLinkText)

                return quoteAttributedStr

Body:
To make a portion of the NSMutableAttributedString selectable, you'll need to set it as a link like so:

quoteAttributedStr.setAsLink("string that you wish to be selectable goes here", linkURL: "url")

You'll also need to add the UITextViewDelegate, and add:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
}

to handle it.

Here's an extension for the setAsLink that I forgot to include:

extension NSMutableAttributedString {

public func setAsLink(_ textToFind:String, linkURL:String) -> Bool {

    let foundRange = self.mutableString.range(of: textToFind)
    if foundRange.location != NSNotFound {
        self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
        return true
    }
    return false
}
}


问:
compile scala-spark file to jar file
Im working on a project of frequent item sets, and I use the Algorithm FP-Growth, I depend on the version developed in Scala-Spark

https://github.com/apache/spark/blob/v2.1.0/mllib/src/main/scala/org/apache/spark/mllib/fpm/FPGrowth.scala

I need to modify this code and recompile it to have a jar file that I can include it to Spark-shell , and call its functions in spark

the problem s that spark-shell is un interpreter , and it finds errors in this file, Ive tried Sbt with eclipse but it did not succeded .
what i need is compiler that can use the last version of scala and spark-shel libraries to compile this file to jar file.

答:
Got your question now!

All you need to do is add dependency jars(scala, java, etc.,) with respect to the machine you are going to use you own jar. Later on add the jars to spark-shell and you can use it like below,

spark-shell --jars your_jar.jar

Title: compile scala-spark file to jar file


问:
Deny nodejs connections from IPs that arent the server IP
Okay so, I have a chat app made with socket.io and NodeJS.

The username is set via the value of an HTML object so that the user cant change the username.

But problem is, the user can create a connection with the socket io server and still send messages with another username if they paste this in the dev tools:

var socket = io.connect('http://*.*.*.*:3000');
socket.emit('send', { message: 'message', username: 'user' });

How can I get the node server to only accept connections from the server so that users cant execute the code above.

I hope I was clear enough. Thanks.

答:
Deny nodejs connections from IPs that arent the server IP

If you deny connections from IPs that aren't the server's IP then you will deny connections to all of your users, because every one of them - no matter if they use their own username or a username of someone else - is connecting to your server from their browser and thus their own IP address.

The username is set via the value of an HTML object so that the user cant change the username.

Anyone can change it very easily. Just right-click on the page and click Inspect and you can change any HTML you want.

You need to authenticate users and not rely on them being who they say they are. For example you can use something like passport.socketio to access Passport.js authenticated user information from Socket.io connection - see:

https://github.com/jfromaniello/passport.socketio

I don't know if you're using Passport.js for authenticating users or not. Hopefully you use something for authentication but it's not clear from your question. You can find more info at:

http://passportjs.org/

It has great documentation.

Now, that having been said, if you still want to deny connections from IPs that aren't the server's IP then you can do something like this - in your connection handler:

```<code>io.on('connection', socket => {
  if (socket.handshake.address !== YOUR_SERVER_IP) {
    socket.disconnect();
  }
  // your normal code here
});
</code>```

How can I get the node server to only accept connections from the server so that users cant execute the code above.

The above will do the trick but I doubt anyone will be able to use your service then.

Body:
Deny nodejs connections from IPs that arent the server IP

If you deny connections from IPs that aren't the server's IP then you will deny connections to all of your users, because every one of them - no matter if they use their own username or a username of someone else - is connecting to your server from their browser and thus their own IP address.

The username is set via the value of an HTML object so that the user cant change the username.

Anyone can change it very easily. Just right-click on the page and click Inspect and you can change any HTML you want.

You need to authenticate users and not rely on them being who they say they are. For example you can use something like passport.socketio to access Passport.js authenticated user information from Socket.io connection - see:

https://github.com/jfromaniello/passport.socketio

I don't know if you're using Passport.js for authenticating users or not. Hopefully you use something for authentication but it's not clear from your question. You can find more info at:

http://passportjs.org/

It has great documentation.

Now, that having been said, if you still want to deny connections from IPs that aren't the server's IP then you can do something like this - in your connection handler:

io.on('connection', socket => {
  if (socket.handshake.address !== YOUR_SERVER_IP) {
    socket.disconnect();
  }
  // your normal code here
});

How can I get the node server to only accept connections from the server so that users cant execute the code above.

The above will do the trick but I doubt anyone will be able to use your service then.


问:
how can I write text into a image in swift in the right coordinates
I am trying to write text into an image but when I do it the text show in the wrong coordinates, I think that the problem is that the image is set as Aspect Fit in the storyboard because is bigger than the screen size, this is my code:</p>

```<code>class ExteriorSketchViewController: UIViewController {

    // MARK: - Properties

    var lastPoint = CGPoint.zero

    // MARK: - Outlets

    @IBOutlet weak var template: UIImageView!

    // MARK: - Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            lastPoint = touch.location(in: self.view)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self.view)
            lastPoint = currentPoint
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        template.image = textToImage(drawText: "x", inImage: template.image!, atPoint: lastPoint)
    }

    func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
        let textColor = UIColor.red
        let textFont = UIFont(name: "Helvetica Bold", size: 32)!

        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            ] as [String : Any]
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

        let rect = CGRect(origin: point, size: image.size)
        text.draw(in: rect, withAttributes: textFontAttributes)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }

}
</code>```

答:
I would like to share the code that solved my problem:</p>

```<code>    import UIKit
    import AVFoundation

    class ExteriorSketchViewController: UIViewController {

        // MARK: - Properties

    var lastPoint = CGPoint.zero

    // MARK: - Outlets

    @IBOutlet weak var template: UIImageView!

    @IBOutlet weak var contentView: UIView! // this is a view inside the main view, contentView has the same size that template UIImageView

    // MARK: - Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            lastPoint = touch.location(in: self.view)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self.view)
            lastPoint = currentPoint
        }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            template.image = drawText(fromPoint: lastPoint, toPoint: lastPoint, text: "X")
        }

    func drawText(fromPoint:CGPoint,toPoint:CGPoint, text: String) -> UIImage {
            let scale = UIScreen.main.scale
            UIGraphicsBeginImageContextWithOptions(self.contentView.frame.size, false, scale)
            let imageRect = CGRect(x: 0, y: 0, width: self.contentView.frame.width, height: self.contentView.frame.height)
            let newRatio = AVMakeRect(aspectRatio: template.image!.size, insideRect: imageRect)
            template.image?.draw(in: newRatio)

            tool.center = toPoint

            let textColor = UIColor.red
            let textFont = UIFont(name: "Helvetica Bold", size: 17)!

            let textFontAttributes = [
                NSFontAttributeName: textFont,
                NSForegroundColorAttributeName: textColor,
                ] as [String : Any]

            let textRect = CGRect(x: fromPoint.x, y: fromPoint.y, width: self.contentView.frame.width, height: self.contentView.frame.height)
            text.draw(in: textRect, withAttributes: textFontAttributes)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage
        }
}
</code>```

Body:
I am trying to write text into an image but when I do it the text show in the wrong coordinates, I think that the problem is that the image is set as Aspect Fit in the storyboard because is bigger than the screen size, this is my code:

class ExteriorSketchViewController: UIViewController {

    // MARK: - Properties

    var lastPoint = CGPoint.zero

    // MARK: - Outlets

    @IBOutlet weak var template: UIImageView!

    // MARK: - Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            lastPoint = touch.location(in: self.view)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self.view)
            lastPoint = currentPoint
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        template.image = textToImage(drawText: "x", inImage: template.image!, atPoint: lastPoint)
    }

    func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
        let textColor = UIColor.red
        let textFont = UIFont(name: "Helvetica Bold", size: 32)!

        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            ] as [String : Any]
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

        let rect = CGRect(origin: point, size: image.size)
        text.draw(in: rect, withAttributes: textFontAttributes)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }

}

Body:
I would like to share the code that solved my problem:

    import UIKit
    import AVFoundation

    class ExteriorSketchViewController: UIViewController {

        // MARK: - Properties

    var lastPoint = CGPoint.zero

    // MARK: - Outlets

    @IBOutlet weak var template: UIImageView!

    @IBOutlet weak var contentView: UIView! // this is a view inside the main view, contentView has the same size that template UIImageView

    // MARK: - Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            lastPoint = touch.location(in: self.view)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.location(in: self.view)
            lastPoint = currentPoint
        }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            template.image = drawText(fromPoint: lastPoint, toPoint: lastPoint, text: "X")
        }

    func drawText(fromPoint:CGPoint,toPoint:CGPoint, text: String) -> UIImage {
            let scale = UIScreen.main.scale
            UIGraphicsBeginImageContextWithOptions(self.contentView.frame.size, false, scale)
            let imageRect = CGRect(x: 0, y: 0, width: self.contentView.frame.width, height: self.contentView.frame.height)
            let newRatio = AVMakeRect(aspectRatio: template.image!.size, insideRect: imageRect)
            template.image?.draw(in: newRatio)

            tool.center = toPoint

            let textColor = UIColor.red
            let textFont = UIFont(name: "Helvetica Bold", size: 17)!

            let textFontAttributes = [
                NSFontAttributeName: textFont,
                NSForegroundColorAttributeName: textColor,
                ] as [String : Any]

            let textRect = CGRect(x: fromPoint.x, y: fromPoint.y, width: self.contentView.frame.width, height: self.contentView.frame.height)
            text.draw(in: textRect, withAttributes: textFontAttributes)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage
        }
}


问:
How do I identify language of a text document in Java?
Is there an existing Java library that could tell me whether a String contains English language text or not (e.g. I need to be able to distinguish French or Italian text -- the function needs to return false for French and Italian, and true for English)?</p>

答:
If you are looking at individual characters or words, this is a tough problem. Since you're working with a whole document, however, there might be some hope. Unfortunately, I don't know of an existing library to do this.

In general, one would need a fairly comprehensive word list for each language. Then examine each word in the document. If it appears in the dictionary for a language, give that language a "vote". Some words will appear in more than one language, and sometimes a document in one language will use loanwords from another language, but a document wouldn't have to be very long before you saw a very clear trend toward one language.

Some of the best word lists for English are those used by Scrabble players. These lists probably exist for other languages too. The raw lists can be hard to find via Google, but they are out there.

OwnerDisplayName: anonymous coward

LastEditorDisplayName: Neil Coffey

OwnerDisplayName: erickson


问:
Traversing tree made from  DefaultMutableTreeNode
We have a tree structure implemented using the DefaultMutableTreeNode specified in Java.

Is there any way of traversing it, that is inbuilt?

If not, please suggest other techniques.

答: Correct, breadtFirst is inorder. Preorder (First root, then children) is supported as well (preorderEnumeration)</p>


问:
Jest.mock outside variable reference
There is need to mock 1 react component, just simple dummy mock, for snapshot testing.

When I try to call React.Component inside the mock function, i got an error:

The second argument of jest.mock() is not allowed to reference any
  outside variables.

But if i call require('react').Component, that works!
Is there any human-ish way to do it correctly?

My code:

```<code>//This one fails
import React from ('react');
...
    jest.mock('...', () => { return class ... extends React.Component {
            render(){
                return <span/>
            }

    }});

//This one works
import React from ('react');
...
jest.mock('...', () => { return class ... extends require('react').Component {
            render(){
                return <span/>
            }

    }});
</code>```

答:
Based on GitHub thread

This used to be a bug that we fixed. In a mock you can only require
  things locally and you aren't allowed to access external variables.

you can change your code this way to make it work

```<code>jest.mock('...', () => {
  const React = require ('react')
  return class ... extends React.Component {
    render() {
      return <span />
    }
  }
})
</code>```

Title: Jest.mock outside variable reference

Body:
There is need to mock 1 react component, just simple dummy mock, for snapshot testing.

When I try to call React.Component inside the mock function, i got an error:

The second argument of jest.mock() is not allowed to reference any
  outside variables.

But if i call require('react').Component, that works!
Is there any human-ish way to do it correctly?

My code:

//This one fails
import React from ('react');
...
    jest.mock('...', () => { return class ... extends React.Component {
            render(){
                return
            }

    }});

//This one works
import React from ('react');
...
jest.mock('...', () => { return class ... extends require('react').Component {
            render(){
                return
            }

    }});

Body:
Based on GitHub thread

This used to be a bug that we fixed. In a mock you can only require
  things locally and you aren't allowed to access external variables.

you can change your code this way to make it work

jest.mock('...', () => {
  const React = require ('react')
  return class ... extends React.Component {
    render() {
      return <span />
    }
  }
})


问:
phpMailer - Why is this not working?
```<code><?php

session_start();

include 'sign_up.php';

$_SESSION['email'] = $_POST['email'];

if (isset($_POST['btn_signup'])) {

    $email = $mysqli->escape_string($_POST['email']);
    $email = trim($_POST['email']);
    $email = strip_tags($email);
    $email = htmlspecialchars($email);

    $name = $mysqli->escape_string($_POST['username']);
    $name = trim($_POST['username']);
    $name = strip_tags($name);
    $name = htmlspecialchars($name);

    $pass = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
    $pass = trim($_POST['password']);
    $pass = strip_tags($pass);
    $pass = htmlspecialchars($pass);

    $hash = $mysqli->escape_string( md5( rand(0,1000) ) );

    $sql = "INSERT INTO users (email, username, password, hash) VALUES ('$email', '$name', '$pass', '$hash')";
    $result = $mysqli->query($sql);

    require_once './PHPMailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;

    //$mail->SMTPDebug = 1;

    $mail->isSMTP();                            // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';             // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                     // Enable SMTP authentication
    $mail->Username = 'myGmail@gmail.com'; // SMTP username
    $mail->Password = 'myPassword';            // SMTP password
    $mail->SMTPSecure = 'tls';                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                          // TCP port to connect to

    $mail->setFrom('myGmail@gmail.com', 'SpreAd Creator');
    $mail->addAddress($_POST['email']);   // Add a recipient
    //$mail->addReplyTo('info@gmail.com', 'Info');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    $mail->isHTML(true);  // Set email format to HTML

    $bodyContent = '<h1>How to Send Email using PHP in Localhost</h1>';
    $bodyContent .= '<p>This is the HTML email sent from localhost using PHP</p>';

    $mail->Subject = 'Email from Localhost';
    $mail->Body    = $bodyContent;

    header("location: other_page.php");
}?>
</code>```

When the user clicks the submit button if (isset($_POST['btn_signup'])) {... it should send a confirmation to his email. I don't understand why it doesn't send it. I'm using phpMailer instead of mail() function which didn't even work. Am I forgetting something?

答:
I think you forgot this at last before header

```<code> if (!$mail->send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
  echo "Message sent!";
 }
</code>```

Also check spam folder

Title: phpMailer - Why is this not working?

Body:
<?php

session_start();

include 'sign_up.php';

$_SESSION['email'] = $_POST['email'];

if (isset($_POST['btn_signup'])) {

    $email = $mysqli->escape_string($_POST['email']);
    $email = trim($_POST['email']);
    $email = strip_tags($email);
    $email = htmlspecialchars($email);

    $name = $mysqli->escape_string($_POST['username']);
    $name = trim($_POST['username']);
    $name = strip_tags($name);
    $name = htmlspecialchars($name);

    $pass = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
    $pass = trim($_POST['password']);
    $pass = strip_tags($pass);
    $pass = htmlspecialchars($pass);

    $hash = $mysqli->escape_string( md5( rand(0,1000) ) );

    $sql = "INSERT INTO users (email, username, password, hash) VALUES ('$email', '$name', '$pass', '$hash')";
    $result = $mysqli->query($sql);

    require_once './PHPMailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;

    //$mail->SMTPDebug = 1;

    $mail->isSMTP();                            // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';             // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                     // Enable SMTP authentication
    $mail->Username = 'myGmail@gmail.com'; // SMTP username
    $mail->Password = 'myPassword';            // SMTP password
    $mail->SMTPSecure = 'tls';                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                          // TCP port to connect to

    $mail->setFrom('myGmail@gmail.com', 'SpreAd Creator');
    $mail->addAddress($_POST['email']);   // Add a recipient
    //$mail->addReplyTo('info@gmail.com', 'Info');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    $mail->isHTML(true);  // Set email format to HTML

    $bodyContent = '
How to Send Email using PHP in Localhost
';
    $bodyContent .= '
This is the HTML email sent from localhost using PHP
';

    $mail->Subject = 'Email from Localhost';
    $mail->Body    = $bodyContent;

    header("location: other_page.php");
}?>

When the user clicks the submit button if (isset($_POST['btn_signup'])) {... it should send a confirmation to his email. I don't understand why it doesn't send it. I'm using phpMailer instead of mail() function which didn't even work. Am I forgetting something?

Body:
I think you forgot this at last before header

 if (!$mail->send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
  echo "Message sent!";
 }

Also check spam folder


问:
What's the point of .slice(0) here?
I was studying the jQuery source when I found this (v1.5 line 2295):

```<code>namespace = new RegExp("(^|\\.)" +
  jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
</code>```

My question is, why use slice(0) here?

答:
In addition to what @Anon said:

The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

Example1:

```<code>var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
</code>```

The result of citrus will be:

```<code>Orange,Lemon
</code>```

Example2:

```<code>var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(-3, -1);
</code>```

The result of citrus will be:

```<code>Lemon,Apple
</code>```

Further information can be found here.

Title: What's the point of .slice(0) here?

Body:
I was studying the jQuery source when I found this (v1.5 line 2295):

namespace = new RegExp("(^|\\.)" +
  jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");

My question is, why use slice(0) here?

Body:
In addition to what @Anon said:

The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

Example1:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

The result of citrus will be:

Orange,Lemon

Example2:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(-3, -1);

The result of citrus will be:

Lemon,Apple

Further information can be found here.


问:
OpenLayers 4 only getting user's location on localhost
So, I'm using OpenLayers 4 and trying to get the User location to set a marker on the map. On localhost it works fine, it tracks user's location and set the marker on the map But when I acess the site via local ip from another device it don't even ask the permission to use the GPS.

Here is the code:

```<code>function initMap(eId) {
        map = new ol.Map({
            target: eId,
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            controls: ol.control.defaults().extend([
                new app.generateGeoJSONControl()
            ]),
            view: new ol.View({
                center: ol.proj.fromLonLat([-47.88281816303313, -15.79413706965552]),
                zoom: 12
            })
        });
        map.on('singleclick', click, this);
        trackMe(map.getView());
    };

function trackMe(view) {
        var geolocation = new ol.Geolocation({
            tracking: true
        });
        geolocation.on('change:position', function (evt) {
            var coordinate = geolocation.getPosition();
            userLonLat = coordinate;
            setMarker({
                longitude: coordinate[0],
                latitude: coordinate[1],
                id: -1
            }, '/assets/marker-user.png', 1000);
        });
    };

function setMarker(ua, imageSrc, zIndex){
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.transform([parseFloat(ua.longitude), parseFloat(ua.latitude)], 'EPSG:4326', 'EPSG:3857')),
            data: ua,
        });
        iconFeature.setId(ua.id);
        var vectorSource = new ol.source.Vector({
            features: [iconFeature]
        });

        var iconStyle = new ol.style.Style({
            image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
                anchor: [0.5, 27],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                opacity: 1,
                src: imageSrc
            }))
        });

        var vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style: iconStyle
        });

        if(zIndex){
            vectorLayer.setZIndex(zIndex);
        }

        map.addLayer(vectorLayer);
    }
</code>```

答: Apparently it has something to do with the website certificate. Since my website don't have a certificate the browser don't allow it to get user's location. I tried with Chrome, Firefox, Edge and Safari, the only one who let the website get user's location was Edge.</p>

Body:
So, I'm using OpenLayers 4 and trying to get the User location to set a marker on the map. On localhost it works fine, it tracks user's location and set the marker on the map But when I acess the site via local ip from another device it don't even ask the permission to use the GPS.

Here is the code:

function initMap(eId) {
        map = new ol.Map({
            target: eId,
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            controls: ol.control.defaults().extend([
                new app.generateGeoJSONControl()
            ]),
            view: new ol.View({
                center: ol.proj.fromLonLat([-47.88281816303313, -15.79413706965552]),
                zoom: 12
            })
        });
        map.on('singleclick', click, this);
        trackMe(map.getView());
    };

function trackMe(view) {
        var geolocation = new ol.Geolocation({
            tracking: true
        });
        geolocation.on('change:position', function (evt) {
            var coordinate = geolocation.getPosition();
            userLonLat = coordinate;
            setMarker({
                longitude: coordinate[0],
                latitude: coordinate[1],
                id: -1
            }, '/assets/marker-user.png', 1000);
        });
    };

function setMarker(ua, imageSrc, zIndex){
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.transform([parseFloat(ua.longitude), parseFloat(ua.latitude)], 'EPSG:4326', 'EPSG:3857')),
            data: ua,
        });
        iconFeature.setId(ua.id);
        var vectorSource = new ol.source.Vector({
            features: [iconFeature]
        });

        var iconStyle = new ol.style.Style({
            image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
                anchor: [0.5, 27],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                opacity: 1,
                src: imageSrc
            }))
        });

        var vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style: iconStyle
        });

        if(zIndex){
            vectorLayer.setZIndex(zIndex);
        }

        map.addLayer(vectorLayer);
    }


问:
How do I shift categorical scatter markers to left and right above xticks (multiple data sets per category)?
I have a simple pandas dataframe that I want to plot with matplotlib:

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel('SAT_data.xlsx', index_col = 'State')

plt.figure()
plt.scatter(df['Year'], df['Reading'], c = 'blue', s = 25)
plt.scatter(df['Year'], df['Math'], c = 'orange', s = 25)
plt.scatter(df['Year'], df['Writing'], c = 'red', s = 25)
</code>```

Here is what my plot looks like:

I'd like to shift the blue data points a bit to the left, and the red ones a bit to the right, so each year on the x-axis has three mini-columns of scatter data above it instead of all three datasets overlapping.  I tried and failed to use the 'verts' argument properly.  Is there a better way to do this?

答:
A quick and dirty way would be to create a small offset dx and subtract it from x values of blue points and add to x values of red points.

```<code>dx = 0.1
plt.scatter(df['Year'] - dx, df['Reading'], c = 'blue', s = 25)
plt.scatter(df['Year'],      df['Math'], c = 'orange', s = 25)
plt.scatter(df['Year'] + dx, df['Writing'], c = 'red', s = 25)
</code>```

One more option could be to use stripplot function from seaborn library. It would be necessary to melt the original dataframe into long form so that each row contains a year, a test and a score. Then make a stripplot specifying year as x, score as y and test as hue. The split keyword argument is what controls plotting categories as separate stripes for each x. There's also the jitter argument that will add some noise to x values so that they take up some small area instead of being on a single vertical line.

```<code>import pandas as pd
import seaborn as sns

# make up example data
np.random.seed(2017)
df = pd.DataFrame(columns = ['Reading','Math','Writing'],
                  data = np.random.normal(540,30,size=(1000,3)))
df['Year'] = np.random.choice(np.arange(2006,2016),size=1000)

# melt the data into long form
df1 = pd.melt(df, var_name='Test', value_name='Score',id_vars=['Year'])

# make a stripplot
fig, ax = plt.subplots(figsize=(10,7))
sns.stripplot(data = df1, x='Year', y = 'Score', hue = 'Test',
              jitter = True, split = True, alpha = 0.7,
              palette = ['blue','orange','red'])
</code>```

Output:

Body:
I have a simple pandas dataframe that I want to plot with matplotlib:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_excel('SAT_data.xlsx', index_col = 'State')

plt.figure()
plt.scatter(df['Year'], df['Reading'], c = 'blue', s = 25)
plt.scatter(df['Year'], df['Math'], c = 'orange', s = 25)
plt.scatter(df['Year'], df['Writing'], c = 'red', s = 25)

Here is what my plot looks like:

I'd like to shift the blue data points a bit to the left, and the red ones a bit to the right, so each year on the x-axis has three mini-columns of scatter data above it instead of all three datasets overlapping.  I tried and failed to use the 'verts' argument properly.  Is there a better way to do this?

Body:
A quick and dirty way would be to create a small offset dx and subtract it from x values of blue points and add to x values of red points.

dx = 0.1
plt.scatter(df['Year'] - dx, df['Reading'], c = 'blue', s = 25)
plt.scatter(df['Year'],      df['Math'], c = 'orange', s = 25)
plt.scatter(df['Year'] + dx, df['Writing'], c = 'red', s = 25)

One more option could be to use stripplot function from seaborn library. It would be necessary to melt the original dataframe into long form so that each row contains a year, a test and a score. Then make a stripplot specifying year as x, score as y and test as hue. The split keyword argument is what controls plotting categories as separate stripes for each x. There's also the jitter argument that will add some noise to x values so that they take up some small area instead of being on a single vertical line.

import pandas as pd
import seaborn as sns

# make up example data
np.random.seed(2017)
df = pd.DataFrame(columns = ['Reading','Math','Writing'],
                  data = np.random.normal(540,30,size=(1000,3)))
df['Year'] = np.random.choice(np.arange(2006,2016),size=1000)

# melt the data into long form
df1 = pd.melt(df, var_name='Test', value_name='Score',id_vars=['Year'])

# make a stripplot
fig, ax = plt.subplots(figsize=(10,7))
sns.stripplot(data = df1, x='Year', y = 'Score', hue = 'Test',
              jitter = True, split = True, alpha = 0.7,
              palette = ['blue','orange','red'])

Output:


问:
How to comment multiple lines in Visual Studio Code?
I cannot find a way to comment and uncomment multiple lines of code in Visual Studio Code.

Is it possible to comment and uncomment multiple lines in Visual Studio Code using some shortcut? If yes, how to do it?

答:
Select all line you want comments

CTRL + /

ContentLicense: CC BY-SA 4.0


答:
If the thing you want is a thing you tap and UIButton can be made to work, use it.  That way the default accessibility is just correct (for vision impaired users).

If you need features of a UIImageView, but also want to be able to tap it, then use that and add a gesture.  You should also consider using the accessibility features to make it possible for vision impaired users to know that you intend the image to be tappable.

Title: Swift: UIButton vs UIView

Body:
In Swift, it appears as though similar behavior can be achieved from a UIButton and a UIView. To give functionality to a button, addTarget can be called, whereas addGestureRecognizer can be called for a UIView. When should one be used over another? In particular, when images are involved, is it better to use a UIButton paired with setImage or UIImageView paired with my_image_view.image = UIImage(...)?

Additionally, what does a UIButton offer that a UIView doesn't (and vice versa)? Thanks!


问:
Having trouble manipulating the DOM using JQuery
I am working on Hands-On: Manipulating the DOM using JQuery in Microsoft Dev211.1 introduction to HTML and JavaScript. This code is supposed to update the H1 and H3 elements in html. I have went over the code compared to what is in the instructions and I cant get it to work. Here is my code:</p>

```<code> <!DOCTYPE html>
 <html lang="en-US">
    <head>
       <title>HTML Page</title>
       <script type="text/javascript" src="https://code.jquery.com/jquery-   2.2.2.min.js"></script>
       <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <h1>H1 Header</h1>
        <hr />
        <h3>H3 Header</h3>
        <hr />
        <h3>Another H3 Header</h3>
    </body>
</html>

//JavaScript Code
$(document).ready(function () {
    manipulateDOM();
});

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
}

 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');
</code>```

答:
You need to place the JavaScript code inside  tags for it to work. And place it before closing html tags.

```<code> <!DOCTYPE html>
 <html lang="en-US">
    <head>
       <title>HTML Page</title>
       <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
       <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <h1>H1 Header</h1>
        <hr />
        <h3>H3 Header</h3>
        <hr />
        <h3>Another H3 Header</h3>
    </body>
    <script type="text/javascript">
//JavaScript Code
$(document).ready(function () {
    manipulateDOM();
});

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');
}

</script>
</html>
</code>```

also remove the space from https://code.jquery.com/jquery-   2.2.2.min.js thus making it https://code.jquery.com/jquery-2.2.2.min.js

Also your

```<code> h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');
</code>```

should come inside the function.

therefore making your function look like:

```<code>function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
         h1Headers.text('Hello World');
    h3Headers.css('color', '#37887D');
    h3Headers.first().css('text-decoration', 'line-through');
}
</code>```

A running demo can be seen here:

H1 Header

H3 Header

Another H3 Header

        ```

Body:
I am working on Hands-On: Manipulating the DOM using JQuery in Microsoft Dev211.1 introduction to HTML and JavaScript. This code is supposed to update the H1 and H3 elements in html. I have went over the code compared to what is in the instructions and I cant get it to work. Here is my code:

 <!DOCTYPE html>

       <title>HTML Page</title>

H1 Header

H3 Header

Another H3 Header

//JavaScript Code
$(document).ready(function () {
    manipulateDOM();
});

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
}

 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');

Body:
You need to place the JavaScript code inside <script></script> tags for it to work. And place it before closing html tags.

 <!DOCTYPE html>
 <html lang="en-US">
    <head>
       <title>HTML Page</title>
       <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
       <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <h1>H1 Header</h1>
        <hr />
        <h3>H3 Header</h3>
        <hr />
        <h3>Another H3 Header</h3>
    </body>
    <script type="text/javascript">
//JavaScript Code
$(document).ready(function () {
    manipulateDOM();
});

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');
}

</script>
</html>

also remove the space from https://code.jquery.com/jquery-   2.2.2.min.js thus making it https://code.jquery.com/jquery-2.2.2.min.js

Also your

 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');

should come inside the function.

therefore making your function look like:

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
         h1Headers.text('Hello World');
    h3Headers.css('color', '#37887D');
    h3Headers.first().css('text-decoration', 'line-through');
}

A running demo can be seen here:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>H1 Header</h1>
            <hr />
            <h3>H3 Header</h3>
            <hr />
            <h3>Another H3 Header</h3>
        <script type="text/javascript">
    //JavaScript Code
    $(document).ready(function () {
        manipulateDOM();
    });

    function manipulateDOM() {
        var h1Headers = $('h1');
        var h3Headers = $('h3');
             h1Headers.text('Hello World');
     h3Headers.css('color', '#37887D');
     h3Headers.first().css('text-decoration', 'line-through');
    }
    </script>


问:
Angular 2: how to use a custom pipe in component logic code, not in template
I used to create custom filters with ionic 1 (angularjs) and then use them either in the template {{data | customfilter }} or in the controller str = $filter('customfilter')(data);.

Now I just created a pipe with angular 2, but how to use it in the typescript code ?

Thanks

src/pipes/nospace.ts:

```<code>import {Pipe} from '@angular/core';

@Pipe({
  name: 'nospace'
})
export class Nospace {
  transform(value, args) {
    return (!value) ? '' : value.replace(/ /g, '');
  }
}
</code>```

src/pages/page.ts:

```<code>import {Component} from '@angular/core';
import {Nospace} from '../../pipes/nospace';

@Component({
  templateUrl: 'build/pages/home/home.html',
  pipes: [Nospace]
})
export class HomePage {

  myString: any;

  constructor() {
    this.myString = "Pipes are super cool";
    //I want to use the pipe here !
  }
}
</code>```

答:
Here is my Angular Concepts Repository. Please check that if gives a very simple idea of how to use pipes and also has a working demo.

```<code>import { SquarePipe } from './square.pipe';

describe('SquarePipe', () => {

  let pipe :SquarePipe;

  beforeEach(() => {
    pipe = new SquarePipe();
  });

  it('transforms 2 to 4', () => {
    let value: any = 2;
    expect(pipe.transform(value)).toEqual(4);
  });

});
</code>```

Check this link for more info link

Body:
I used to create custom filters with ionic 1 (angularjs) and then use them either in the template {{data | customfilter }} or in the controller str = $filter('customfilter')(data);.

Now I just created a pipe with angular 2, but how to use it in the typescript code ?

Thanks

src/pipes/nospace.ts:

import {Pipe} from '@angular/core';

@Pipe({
  name: 'nospace'
})
export class Nospace {
  transform(value, args) {
    return (!value) ? '' : value.replace(/ /g, '');
  }
}

src/pages/page.ts:

import {Component} from '@angular/core';
import {Nospace} from '../../pipes/nospace';

@Component({
  templateUrl: 'build/pages/home/home.html',
  pipes: [Nospace]
})
export class HomePage {

  myString: any;

  constructor() {
    this.myString = "Pipes are super cool";
    //I want to use the pipe here !
  }
}

Body:
Here is my Angular Concepts Repository. Please check that if gives a very simple idea of how to use pipes and also has a working demo.

import { SquarePipe } from './square.pipe';

describe('SquarePipe', () => {

  let pipe :SquarePipe;

  beforeEach(() => {
    pipe = new SquarePipe();
  });

  it('transforms 2 to 4', () => {
    let value: any = 2;
    expect(pipe.transform(value)).toEqual(4);
  });

});

Check this link for more info link


答:
The following query returns correct result

```<code>SELECT AVG(
        DATEDIFF(i.date, (SELECT MAX(date)
                          FROM intervals WHERE date < i.date)
                 )
           )
FROM intervals i
</code>```

but it runs a dependent subquery which might be really inefficient with no index and on a larger number of rows.

Title: MySQL: Average interval between records

Body:
Assume this table:

id    date
----------------
1     2010-12-12
2     2010-12-13
3     2010-12-18
4     2010-12-22
5     2010-12-23

How do I find the average intervals between these dates, using MySQL queries only?

For instance, the calculation on this table will be

  (
    ( 2010-12-13 - 2010-12-12 )
  + ( 2010-12-18 - 2010-12-13 )
  + ( 2010-12-22 - 2010-12-18 )
  + ( 2010-12-23 - 2010-12-22 )
  ) / 4
----------------------------------
= ( 1 DAY + 5 DAY + 4 DAY + 1 DAY ) / 4
= 2.75 DAY

Body:
The following query returns correct result

SELECT AVG(
        DATEDIFF(i.date, (SELECT MAX(date)
                          FROM intervals WHERE date < i.date)
                 )
           )
FROM intervals i

but it runs a dependent subquery which might be really inefficient with no index and on a larger number of rows.


问:
How to combine outputs of multiple tasks performed using Matlab SGE?
I have the following batch file launching some m-files (main.m and f.m which are scripts) 4 times (4 tasks).

```<code>#$ -S /bin/bash
#$ -l h_vmem=2G
#$ -l tmem=2G
#$ -cwd
#$ -j y

#Run 4 tasks where each task has a different $SGE_TASK_ID ranging from 1 to 4
#$ -t 1-4

#$ -N example

#Output the Task ID
echo "Task ID is $SGE_TASK_ID"

cat main.m f.m | matlab -nodisplay -nodesktop -nojvm -nosplash
</code>```

At the end I obtain 4 outputs that are example.o[...].1,example.o[...].2, example.o[...].3, example.o[...].4. Each of them looks like

```<code>...
Task ID is ...

                        < M A T L A B (R) >
                                ...
>> >> >> >> >> >> >> >> >> >> >>
output =

    4.0234   -3.4763
</code>```

How can I combine these 4 outputs in a matrix 4x2 and save it?

答:
You should save the relevant output from within f.m using MATLAB's save or something similar.

If you use the -r flag to call main and f from the command line you can add a variable which will contain the task ID and you can then access that from within f.m

```<code>matlab -nodisplay -nodesktop -nojvm -nosplash -r "main; ID = $SGE_TASK_ID; f; exit"
</code>```

Then within f.m

```<code>% You theoretically generate some numeric result
result = rand(1, 2);

filename = sprintf('Result.%d.mat', ID);
save(filename, 'result')
</code>```

This will  save Result.0.mat, Result.1.mat etc.

Alternately, you could modify f.m such that it loads the data from the file, appends to it, and re-saves it every time

```<code>result = rand(1,2);

filename = 'Results.mat';

% If this is the first task, then create a new file, otherwise append to the old
if ID == 1
    data = result;
else
    tmp = load(filename, '-mat');
    data = tmp.data;
    data(ID,:) = result;
end

save(filename, 'data')
</code>```

Body:
I have the following batch file launching some m-files (main.m and f.m which are scripts) 4 times (4 tasks).

#$ -S /bin/bash
#$ -l h_vmem=2G
#$ -l tmem=2G
#$ -cwd
#$ -j y

#Run 4 tasks where each task has a different $SGE_TASK_ID ranging from 1 to 4
#$ -t 1-4

#$ -N example

#Output the Task ID
echo "Task ID is $SGE_TASK_ID"

cat main.m f.m | matlab -nodisplay -nodesktop -nojvm -nosplash

At the end I obtain 4 outputs that are example.o[...].1,example.o[...].2, example.o[...].3, example.o[...].4. Each of them looks like

...
Task ID is ...

                        < M A T L A B (R) >
                                ...
>> >> >> >> >> >> >> >> >> >> >>
output =

    4.0234   -3.4763

How can I combine these 4 outputs in a matrix 4x2 and save it?

Body:
You should save the relevant output from within f.m using MATLAB's save or something similar.

If you use the -r flag to call main and f from the command line you can add a variable which will contain the task ID and you can then access that from within f.m

matlab -nodisplay -nodesktop -nojvm -nosplash -r "main; ID = $SGE_TASK_ID; f; exit"

Then within f.m

% You theoretically generate some numeric result
result = rand(1, 2);

filename = sprintf('Result.%d.mat', ID);
save(filename, 'result')

This will  save Result.0.mat, Result.1.mat etc.

Alternately, you could modify f.m such that it loads the data from the file, appends to it, and re-saves it every time

result = rand(1,2);

filename = 'Results.mat';

% If this is the first task, then create a new file, otherwise append to the old
if ID == 1
    data = result;
else
    tmp = load(filename, '-mat');
    data = tmp.data;
    data(ID,:) = result;
end

save(filename, 'data')


问:
How to debug objects from Angular template (html file)
Creating a template, I have some Angular code within some HTML elements:

```<code><button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon"
        ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'current') )"
...
</code>```

I want to debug the ng-if condition to check the values of my CoursesVm object. How would I do this in Chrome for example?

答:
Option 1: Modify your code  (For Angular2+ and AngularJS)

Angular2+

...in the component add this temporal function

```<code>checkIf(value: any){
    debugger;  //open the devtools and go to the view...code execution will stop here!
    //..code to be checked... `value` can be inspected now along with all of the other component attributes
}
</code>```

... in the view: add an *ngIf with the created function providing the value you want to debug

```<code><button *ngIf="checkIf(CoursesVm)">Button</button>
</code>```

AngularJS

You can enclose the code inside the ng-if ((!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'current') )) inside a controller function and then debug that function.

Something like this:

```<code>//...controller
function checkIf(){
    debugger;  //open the devtools and go to the view...code execution will stop here!
    //..code to be checked
}

<!--view supposing myCtrl is the alias for the controller here-->
<button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon"
        ng-if="myCtrl.checkIf()"
<!-- ... -->
</code>```

Option 2: Directly in chrome devtools (For AngularJS (Known to some people as Angular 1))

Capture the scope like this:

var scope = angular.element(document.getElementById('#btnMainMenu')).scope();

Access to the object like this (supposing the controller of this view is myCtrl):

scope.myCtrl.CoursesVm

Body:
Creating a template, I have some Angular code within some HTML elements:

<button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon"
        ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'current') )"
...

I want to debug the ng-if condition to check the values of my CoursesVm object. How would I do this in Chrome for example?

Body:
Option 1: Modify your code  (For Angular2+ and AngularJS)

Angular2+

...in the component add this temporal function

checkIf(value: any){
    debugger;  //open the devtools and go to the view...code execution will stop here!
    //..code to be checked... `value` can be inspected now along with all of the other component attributes
}

... in the view: add an *ngIf with the created function providing the value you want to debug

<button *ngIf="checkIf(CoursesVm)">Button</button>

AngularJS

You can enclose the code inside the ng-if ((!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'current') )) inside a controller function and then debug that function.

Something like this:

//...controller
function checkIf(){
    debugger;  //open the devtools and go to the view...code execution will stop here!
    //..code to be checked
}

<!--view supposing myCtrl is the alias for the controller here-->
<button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon"
        ng-if="myCtrl.checkIf()"
<!-- ... -->

Option 2: Directly in chrome devtools (For AngularJS (Known to some people as Angular 1))

Capture the scope like this:

var scope = angular.element(document.getElementById('#btnMainMenu')).scope();

Access to the object like this (supposing the controller of this view is myCtrl):

scope.myCtrl.CoursesVm


问:
Optimise android apps for phones with the new ratio's like the S8 (18.5:9)?
Just got the new S8 and I'm trying to update my android (react-native) apps because there is a black bar on top of the screen because of the app scaling of the ratio 37:18 / 18.5:9. Adding fixed height and width to the app doesn't work I still get that black bar in top. Removing the statusbar seems like removing a bit on top and at the bottom.

As an example I created a new react-native app but a native Android has the same problems.

答:
Got it! Jeej.

Found out via a post of Nato Marin you can just add <meta-data android:name="android.max_aspect" android:value="2.1" /> in the <application> element in your AndroidManifest.xml.

Result: Black bar gone :)


问:
How can add a new column in df1 called value that looks up the value from df2 based on the year column?
I have two DataFrames,

df1

```<code>Name    Year
A       2008
A       2009
B       2008
B       2008
</code>```

df2

```<code>year    value
2008    10
2009    15
</code>```

How can add a new column in df1 called value that looks up the value from df2 based on the year column?

Goal

```<code>Name  Year  Value
A     2008  10
A     2009  15
B     2008  10
B     2009  15
</code>```

My issue ended up being datatypes..

```<code> df = df.convert_objects(convert_numeric=True)
</code>```

The map solution was the fastest with 76,000 rows

答:
I'd use pd.merge() on your Year column.

```<code>df1 = df1.merge(df2, on='Year', how='left')
</code>```

Body:
I have two DataFrames,

df1

Name    Year
A       2008
A       2009
B       2008
B       2008

df2

year    value
2008    10
2009    15

How can add a new column in df1 called value that looks up the value from df2 based on the year column?

Goal

Name  Year  Value
A     2008  10
A     2009  15
B     2008  10
B     2009  15

My issue ended up being datatypes..

 df = df.convert_objects(convert_numeric=True)

The map solution was the fastest with 76,000 rows

Body:
I'd use pd.merge() on your Year column.

df1 = df1.merge(df2, on='Year', how='left')


问:
T-SQL: calculate age then add character to result
Been stuck on this one for a while now. Let's say I have a Client table like the one here:

```<code>Name   BirthDayNum   BirthMonthNum   BirthYearNum
--------------------------------------------------
John       23             12             1965
Jane        4              9             1975
Joe         6              3             1953
</code>```

Currently I am calculating the age using this syntax: (sorry if it is hard to read)

```<code>DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE())
- (CASE WHEN dateadd(YY, DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE()),
CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101)) > getdate() THEN 1 ELSE 0 END) AS 'Client Age'
</code>```

This will give me the age in years. Of course if I want months, I just change the DATEDIFF(year to month. So, what I am trying to do now is this.

Continue to calculate the age, but instead of returning either years or months, I would like to return the age in years and months, but also, concat a 'y' and 'm' within the value as well.  Ex.  41y 11m for Jane above.

So basically I am trying to figure out how to add a char to the return value, as well as calculate the remaining months beyond the year calculation.

Any help would be greatly appreciated!

答:
Tired of twisting myself into knots with date calculations, I created a Table-Valued-Function to calculate elapsed time in Years, Months, Days, Hours, Minutes, and Seconds.

Example

```<code>Declare @YourTable table (Name varchar(50),BirthDayNum int, BirthMonthNum int, BirthYearNum int)
Insert Into @YourTable values
('John', 23, 12, 1965),
('Jane',  4, 9,  1975),
('Joe',   6, 3,  1953)

Select A.Name
      ,B.*
      ,Age =  concat(C.Years,'y ',C.Months,'m')
 From @YourTable A
 Cross Apply (Select DOB = DateFromParts(A.BirthYearNum,A.BirthMonthNum,A.BirthDayNum)) B
 Cross Apply [dbo].[udf-Date-Elapsed](B.DOB,GetDate()) C
</code>```

Returns

```<code>Name    DOB         Age
John    1965-12-23  51y 3m
Jane    1975-09-04  41y 6m
Joe     1953-03-06  64y 0m
</code>```

The UDF - May look like overkill, but it is very performant

```<code>CREATE FUNCTION [dbo].[udf-Date-Elapsed] (@D1 DateTime,@D2 DateTime)
Returns Table
Return (
    with cteBN(N)   as (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cteRN(R)   as (Select Row_Number() Over (Order By (Select NULL))-1 From cteBN a,cteBN b,cteBN c),
         cteYY(N,D) as (Select Max(R),Max(DateAdd(YY,R,@D1))From cteRN R Where DateAdd(YY,R,@D1)<=@D2),
         cteMM(N,D) as (Select Max(R),Max(DateAdd(MM,R,D))  From (Select Top 12 R From cteRN Order By 1) R, cteYY P Where DateAdd(MM,R,D)<=@D2),
         cteDD(N,D) as (Select Max(R),Max(DateAdd(DD,R,D))  From (Select Top 31 R From cteRN Order By 1) R, cteMM P Where DateAdd(DD,R,D)<=@D2),
         cteHH(N,D) as (Select Max(R),Max(DateAdd(HH,R,D))  From (Select Top 24 R From cteRN Order By 1) R, cteDD P Where DateAdd(HH,R,D)<=@D2),
         cteMI(N,D) as (Select Max(R),Max(DateAdd(MI,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteHH P Where DateAdd(MI,R,D)<=@D2),
         cteSS(N,D) as (Select Max(R),Max(DateAdd(SS,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteMI P Where DateAdd(SS,R,D)<=@D2)

    Select [Years]   = cteYY.N
          ,[Months]  = cteMM.N
          ,[Days]    = cteDD.N
          ,[Hours]   = cteHH.N
          ,[Minutes] = cteMI.N
          ,[Seconds] = cteSS.N
     From  cteYY,cteMM,cteDD,cteHH,cteMI,cteSS
)
--Max 1000 years
--Select * from [dbo].[udf-Date-Elapsed] ('1991-09-12 21:00:00.000',GetDate())
</code>```

Just to Illustrate

The TVF without any secondary string manipulation would return

```<code>Select A.Name
      ,B.*
 From @YourTable A
 Cross Apply [dbo].[udf-Date-Elapsed](DateFromParts(A.BirthYearNum,A.BirthMonthNum,A.BirthDayNum),GetDate()) B
</code>```

EDIT - READ ONLY VERSION

```<code>Select A.Name
      ,B.*
      ,Age =  concat(DateDiff(MONTH,B.DOB,GetDate())/12,'y ',DateDiff(MONTH,B.DOB,GetDate()) % 12,'m')
 From @YourTable A
 Cross Apply (Select DOB = DateFromParts(A.BirthYearNum,A.BirthMonthNum,A.BirthDayNum)) B
</code>```

Body:
Been stuck on this one for a while now. Let's say I have a Client table like the one here:

Name   BirthDayNum   BirthMonthNum   BirthYearNum
--------------------------------------------------
John       23             12             1965
Jane        4              9             1975
Joe         6              3             1953

Currently I am calculating the age using this syntax: (sorry if it is hard to read)

DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE())
- (CASE WHEN dateadd(YY, DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE()),
CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101)) > getdate() THEN 1 ELSE 0 END) AS 'Client Age'

This will give me the age in years. Of course if I want months, I just change the DATEDIFF(year to month. So, what I am trying to do now is this.

Continue to calculate the age, but instead of returning either years or months, I would like to return the age in years and months, but also, concat a 'y' and 'm' within the value as well.  Ex.  41y 11m for Jane above.

So basically I am trying to figure out how to add a char to the return value, as well as calculate the remaining months beyond the year calculation.

Any help would be greatly appreciated!

Body:
Tired of twisting myself into knots with date calculations, I created a Table-Valued-Function to calculate elapsed time in Years, Months, Days, Hours, Minutes, and Seconds.

Example

Declare @YourTable table (Name varchar(50),BirthDayNum int, BirthMonthNum int, BirthYearNum int)
Insert Into @YourTable values
('John', 23, 12, 1965),
('Jane',  4, 9,  1975),
('Joe',   6, 3,  1953)

Select A.Name
      ,B.*
      ,Age =  concat(C.Years,'y ',C.Months,'m')
 From @YourTable A
 Cross Apply (Select DOB = DateFromParts(A.BirthYearNum,A.BirthMonthNum,A.BirthDayNum)) B
 Cross Apply [dbo].[udf-Date-Elapsed](B.DOB,GetDate()) C

Returns

Name    DOB         Age
John    1965-12-23  51y 3m
Jane    1975-09-04  41y 6m
Joe     1953-03-06  64y 0m

The UDF - May look like overkill, but it is very performant

CREATE FUNCTION [dbo].[udf-Date-Elapsed] (@D1 DateTime,@D2 DateTime)
Returns Table
Return (
    with cteBN(N)   as (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cteRN(R)   as (Select Row_Number() Over (Order By (Select NULL))-1 From cteBN a,cteBN b,cteBN c),
         cteYY(N,D) as (Select Max(R),Max(DateAdd(YY,R,@D1))From cteRN R Where DateAdd(YY,R,@D1)<=@D2),
         cteMM(N,D) as (Select Max(R),Max(DateAdd(MM,R,D))  From (Select Top 12 R From cteRN Order By 1) R, cteYY P Where DateAdd(MM,R,D)<=@D2),
         cteDD(N,D) as (Select Max(R),Max(DateAdd(DD,R,D))  From (Select Top 31 R From cteRN Order By 1) R, cteMM P Where DateAdd(DD,R,D)<=@D2),
         cteHH(N,D) as (Select Max(R),Max(DateAdd(HH,R,D))  From (Select Top 24 R From cteRN Order By 1) R, cteDD P Where DateAdd(HH,R,D)<=@D2),
         cteMI(N,D) as (Select Max(R),Max(DateAdd(MI,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteHH P Where DateAdd(MI,R,D)<=@D2),
         cteSS(N,D) as (Select Max(R),Max(DateAdd(SS,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteMI P Where DateAdd(SS,R,D)<=@D2)

    Select [Years]   = cteYY.N
          ,[Months]  = cteMM.N
          ,[Days]    = cteDD.N
          ,[Hours]   = cteHH.N
          ,[Minutes] = cteMI.N
          ,[Seconds] = cteSS.N
     From  cteYY,cteMM,cteDD,cteHH,cteMI,cteSS
)
--Max 1000 years
--Select * from [dbo].[udf-Date-Elapsed] ('1991-09-12 21:00:00.000',GetDate())

Just to Illustrate

The TVF without any secondary string manipulation would return

Select A.Name
      ,B.*
 From @YourTable A
 Cross Apply [dbo].[udf-Date-Elapsed](DateFromParts(A.BirthYearNum,A.BirthMonthNum,A.BirthDayNum),GetDate()) B

EDIT - READ ONLY VERSION

Select A.Name
      ,B.*
      ,Age =  concat(DateDiff(MONTH,B.DOB,GetDate())/12,'y ',DateDiff(MONTH,B.DOB,GetDate()) % 12,'m')
 From @YourTable A
 Cross Apply (Select DOB = DateFromParts(A.BirthYearNum,A.BirthMonthNum,A.BirthDayNum)) B