问:
How to update LiveData of a ViewModel from background service and Update UI
Recently I am exploring Android Architecture, that has been introduced recently by google. From the Documentation I have found this:

```<code>public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // do async operation to fetch users
    }
}
</code>```

the activity can access this list as follows:

```<code>public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}
</code>```

My Question is, I am going to do this:

in the loadUsers() function I am fetching the data asynchronously where I will first check the database(Room) for that data

If I do not get the data there I will make an API call to fetch the data from the web server.

I will insert the fetched data into the database(Room) and update the UI according the data.

What is the recommended approach to do this?

If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData<List<User>> users variable from that Service?

答:
... in the loadUsers() function I am fetching the data asynchronously ...
  If I start a Service to call the API from the loadUsers() method, how
  can I update the MutableLiveData> users variable from that
  Service?

If the app is fetching user data on a background thread, postValue (rather than setValue) will be useful.

In the loadData method there is a reference to the MutableLiveData "users" object. The loadData method also fetches some fresh user data from somewhere (for example, a repository).

Now, if execution is on a background thread, MutableLiveData.postValue() updates outside observers of the MutableLiveData object.

Maybe something like this:

```<code>private MutableLiveData<List<User>> users;

.
.
.

private void loadUsers() {
    // do async operation to fetch users
    ExecutorService service =  Executors.newSingleThreadExecutor();
    service.submit(new Runnable() {
        @Override
        public void run() {
            // on background thread, obtain a fresh list of users
            List<String> freshUserList = aRepositorySomewhere.getUsers();

            // now that you have the fresh user data in freshUserList,
            // make it available to outside observers of the "users"
            // MutableLiveData object
            users.postValue(freshUserList);
        }
    });

}
</code>```

Body:
Recently I am exploring Android Architecture, that has been introduced recently by google. From the Documentation I have found this:

public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> users;
    public LiveData<List<User>> getUsers() {
        if (users == null) {
            users = new MutableLiveData<List<Users>>();
            loadUsers();
        }
        return users;
    }

    private void loadUsers() {
        // do async operation to fetch users
    }
}

the activity can access this list as follows:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

My Question is, I am going to do this:

in the loadUsers() function I am fetching the data asynchronously where I will first check the database(Room) for that data

If I do not get the data there I will make an API call to fetch the data from the web server.

I will insert the fetched data into the database(Room) and update the UI according the data.

What is the recommended approach to do this?

If I start a Service to call the API from the loadUsers() method, how can I update the MutableLiveData<List<User>> users variable from that Service?

Body:
... in the loadUsers() function I am fetching the data asynchronously ...
  If I start a Service to call the API from the loadUsers() method, how
  can I update the MutableLiveData> users variable from that
  Service?

If the app is fetching user data on a background thread, postValue (rather than setValue) will be useful.

In the loadData method there is a reference to the MutableLiveData "users" object. The loadData method also fetches some fresh user data from somewhere (for example, a repository).

Now, if execution is on a background thread, MutableLiveData.postValue() updates outside observers of the MutableLiveData object.

Maybe something like this:

private MutableLiveData<List<User>> users;

.
.
.

private void loadUsers() {
    // do async operation to fetch users
    ExecutorService service =  Executors.newSingleThreadExecutor();
    service.submit(new Runnable() {
        @Override
        public void run() {
            // on background thread, obtain a fresh list of users
            List<String> freshUserList = aRepositorySomewhere.getUsers();

            // now that you have the fresh user data in freshUserList,
            // make it available to outside observers of the "users"
            // MutableLiveData object
            users.postValue(freshUserList);
        }
    });

}


来源: stackexchange

问:
SSL certs on Windows and Linux
I'm trying to create certification to enable HTTPS for our company's domain. It should work on both Windows and Linux system.

I know on Linux, I need to start from openssl .key file, to .csr file, finally to .crt file, then configure the apache server.

Will Windows instance using the same key files? Or Windows should have its own certification file format, such as .p7b, .pem, .cer files?

Confused here.. Which file should I create first if I want it work on both Windows and Linux systems?

答:
You have to create a pfx file from your crt and key file in this way:

```<code>openssl pkcs12 -export -out domainname.pfx -inkey domainname.key -in domainname.crt
</code>```

Then, use this pfx on windows.

ContentLicense: CC BY-SA 3.0

Title: SSL certs on Windows and Linux

Body:
You have to create a pfx file from your crt and key file in this way:

openssl pkcs12 -export -out domainname.pfx -inkey domainname.key -in domainname.crt

Then, use this pfx on windows.


问:
How to debug a rails app in docker with pry?
I have a rails app running in a docker container in development environment.

When I try to debug it with placing binding.pry somewhere in the code and attaching to the container I can see the pry prompt in the output but it doesn't pause on it and I can't interact with it like it was without docker container.

So how do I debug a containerized app?

答:
If you don't use docker-compose though, you can simply run the container with -it option.

For example:

```<code>docker run -v /Users/adam/Documents/Rails/Blog/:/usr/src/app -p 3000:3000 -it blog
</code>```

Body:
If you don't use docker-compose though, you can simply run the container with -it option.

For example:

docker run -v /Users/adam/Documents/Rails/Blog/:/usr/src/app -p 3000:3000 -it blog


问:
How to split a string by "," except between certain characters in python?
How to split a string by "," except between certain characters in python?
My data is like:

```<code>('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')
</code>```

I need to split them by "," except for 'Aa,Ab'.

The result should be:

```<code>("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")
</code>```

Do you know how to do that?

答:
I'll take a stab at some code.
Splits a string by needle if it's outside quotes.
Assumes both needle and quotes are one character long.

```<code>#!python3

def splitExceptBetween(istr, needle, quotes):
    inside = -1
    res = []
    oldt = 0
    for index, letter in enumerate(istr):
        if letter==quotes:
            inside = -inside
        elif letter==needle and inside == -1:
            res.append(istr[oldt:index])
            oldt = index+1
    if oldt<len(istr):
        res.append(istr[oldt:])
    return res

istr = "as'das'd.asdas'd.a'sdas.drth..rt'h.r'th.'"
print(splitExceptBetween(istr, ".", "'"))
istr = "00012+1357,LSC   2,'Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,M0.5,+019,+135,NULL,NULL,NULL,NULL,000113.19+135830.3"
print(splitExceptBetween(istr, ",", "'"))
</code>```

Body:
How to split a string by "," except between certain characters in python?
My data is like:

('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')

I need to split them by "," except for 'Aa,Ab'.

The result should be:

("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")

Do you know how to do that?

Body:
I'll take a stab at some code.
Splits a string by needle if it's outside quotes.
Assumes both needle and quotes are one character long.

#!python3

def splitExceptBetween(istr, needle, quotes):
    inside = -1
    res = []
    oldt = 0
    for index, letter in enumerate(istr):
        if letter==quotes:
            inside = -inside
        elif letter==needle and inside == -1:
            res.append(istr[oldt:index])
            oldt = index+1
    if oldt<len(istr):
        res.append(istr[oldt:])
    return res

istr = "as'das'd.asdas'd.a'sdas.drth..rt'h.r'th.'"
print(splitExceptBetween(istr, ".", "'"))
istr = "00012+1357,LSC   2,'Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,M0.5,+019,+135,NULL,NULL,NULL,NULL,000113.19+135830.3"
print(splitExceptBetween(istr, ",", "'"))


问:
initialize swift class from objective c library
Hello I am currently importing a project from objective C to swift. The objective C project uses a custom library which in one of the classes it has a function that takes a Class object, which, when the data is loaded it initializes an id obj with the class(code below). On the objective C side this works great! I am using the same library on swift with a bridge header but unfortunately my object is nil once the data is loaded. I verified the data object used to initialize the object has content. The custom swift class also requires me to implement an init(data: Data) initializer when I add a custom init(), I am new to swift any help would be great! Thank you!

Objective C:

Library:

```<code>-(id) buildRetObject:(Class)clss fromData(NSData*) data{
id obj = nil;
if (data != nil) {
obj = [[clss alloc] initWithData:data];
}
}
</code>```

Custom Object, is a subclass of another custom object, not in library but on main app:

Item.m:

```<code>-(id)init{
    if ([super init]){
       //do something
    }

    return self
}
</code>```

Same Item object in swift:

```<code>//customClass super class is abstactCustomClass which is a sub abstract class of NSObject class, init functions are in here, the abstract class
class Item: customClass {

//variables

override init() {
   super.init()
   // do something
}

required init!(data: Data){
   //fatalError(message here)
   /*tried calling supers method
    super.init(data:Data) gives error: fatal error: use of unimplemented initializer 'init(dictionary:)'*/
}

//methods
</code>```

}

答:
After a lot of digging I was finally able to figure it out, objective C knows from the abstract class what the initializers are, swift doesn't. So all I need to do was implement this initializers and it works. </p>

```<code>required init!(data: Data){
    super.init(data:Data)
}

override init(dictionary: [AnyHashable: Any]!){
    super.init(Dictionary:dictionary)
}
</code>```

Body:
Hello I am currently importing a project from objective C to swift. The objective C project uses a custom library which in one of the classes it has a function that takes a Class object, which, when the data is loaded it initializes an id obj with the class(code below). On the objective C side this works great! I am using the same library on swift with a bridge header but unfortunately my object is nil once the data is loaded. I verified the data object used to initialize the object has content. The custom swift class also requires me to implement an init(data: Data) initializer when I add a custom init(), I am new to swift any help would be great! Thank you!

Objective C:

Library:

-(id) buildRetObject:(Class)clss fromData(NSData*) data{
id obj = nil;
if (data != nil) {
obj = [[clss alloc] initWithData:data];
}
}

Custom Object, is a subclass of another custom object, not in library but on main app:

Item.m:

-(id)init{
    if ([super init]){
       //do something
    }

    return self
}

Same Item object in swift:

//customClass super class is abstactCustomClass which is a sub abstract class of NSObject class, init functions are in here, the abstract class
class Item: customClass {

//variables

override init() {
   super.init()
   // do something
}

required init!(data: Data){
   //fatalError(message here)
   /*tried calling supers method
    super.init(data:Data) gives error: fatal error: use of unimplemented initializer 'init(dictionary:)'*/
}

//methods

}

Body:
After a lot of digging I was finally able to figure it out, objective C knows from the abstract class what the initializers are, swift doesn't. So all I need to do was implement this initializers and it works.

required init!(data: Data){
    super.init(data:Data)
}

override init(dictionary: [AnyHashable: Any]!){
    super.init(Dictionary:dictionary)
}


问:
PHP random string function preventing duplicate outputs when called multiple times
The following function will create a random string output what is the best way to prevent duplicate outputs / collisions if called multiple times.

```<code>function random_string($length) {
            $key = '';
            $keys = array_merge(range('A', 'Z'), range('a', 'z'), array('_'));

            for ($i = 0; $i < $length; $i++) {
                $key .= $keys[array_rand($keys)];
            }

            return $key;
        }
echo "First : " . random_string(rand(3, 50));
//These have a small percentage of a chance of matching the previous random output lets eliminate all possibility of getting the same output.
echo "Second : " . random_string(rand(3, 50));
echo "Third : " . random_string(rand(3, 50));
echo "Fourth : " . random_string(rand(3, 50));
</code>```

I did read on the PHP documentation that array_unique could achieve what i want but would it be the best solution or is there a more efficient way.

答:
Here's a simple solution:</p>

```<code>// array to store required strings
$stringsCollection = [];
// 4 is the number of strings that you need
while (sizeof($stringsCollection) != 4) {
    // generate new string
    $randString = random_string($length);
    // if string is not in `stringsCollection` - add it as a key
    if (!isset($stringsCollection[$randString])) {
        $stringsCollection[$randString] = 1;
    }
}
print_r(array_keys($stringsCollection));
</code>```

Body:
The following function will create a random string output what is the best way to prevent duplicate outputs / collisions if called multiple times.

function random_string($length) {
            $key = '';
            $keys = array_merge(range('A', 'Z'), range('a', 'z'), array('_'));

            for ($i = 0; $i < $length; $i++) {
                $key .= $keys[array_rand($keys)];
            }

            return $key;
        }
echo "First : " . random_string(rand(3, 50));
//These have a small percentage of a chance of matching the previous random output lets eliminate all possibility of getting the same output.
echo "Second : " . random_string(rand(3, 50));
echo "Third : " . random_string(rand(3, 50));
echo "Fourth : " . random_string(rand(3, 50));

I did read on the PHP documentation that array_unique could achieve what i want but would it be the best solution or is there a more efficient way.

Body:
Here's a simple solution:

// array to store required strings
$stringsCollection = [];
// 4 is the number of strings that you need
while (sizeof($stringsCollection) != 4) {
    // generate new string
    $randString = random_string($length);
    // if string is not in `stringsCollection` - add it as a key
    if (!isset($stringsCollection[$randString])) {
        $stringsCollection[$randString] = 1;
    }
}
print_r(array_keys($stringsCollection));


问:
SQL Query to Bucket Table Items
I am trying to bucket values within my table by the range they fall in, for example, if my table is the following:

```<code>course_name | current enrollment
course_1    | 10
course_2    | 200
course_3    | 500
</code>```

I get the following result:

```<code>enrollment_range | courses
10               | 1
100              | 1
500              | 1
</code>```

So far, I have the following:

```<code>SELECT
  CASE
    WHEN courses.current_enrollment >= 500 THEN 500
    WHEN courses.current_enrollment >= 250 THEN 250
    WHEN courses.current_enrollment >= 100 THEN 100
    WHEN courses.current_enrollment >= 50 THEN 50
    WHEN courses.current_enrollment >= 30 THEN  30
    WHEN courses.current_enrollment >= 10 THEN 10
  END enrollment_range, count() AS total
FROM courses
GROUP BY enrollment_range
ORDER BY enrollment_range ASC
</code>```

but I end up with an extra result that is the total number of courses I have, so I get something like the following:

```<code>enrollment_range | courses
10               | 1
100              | 1
500              | 1
                 | 3
</code>```

答: The extra result was the count of courses that did not fall within the specified brackets, in this case, courses with enrollment below 10.</p>

Title: SQL Query to Bucket Table Items

Body:
I am trying to bucket values within my table by the range they fall in, for example, if my table is the following:

course_name | current enrollment
course_1    | 10
course_2    | 200
course_3    | 500

I get the following result:

enrollment_range | courses
10               | 1
100              | 1
500              | 1

So far, I have the following:

SELECT
  CASE
    WHEN courses.current_enrollment >= 500 THEN 500
    WHEN courses.current_enrollment >= 250 THEN 250
    WHEN courses.current_enrollment >= 100 THEN 100
    WHEN courses.current_enrollment >= 50 THEN 50
    WHEN courses.current_enrollment >= 30 THEN  30
    WHEN courses.current_enrollment >= 10 THEN 10
  END enrollment_range, count() AS total
FROM courses
GROUP BY enrollment_range
ORDER BY enrollment_range ASC

but I end up with an extra result that is the total number of courses I have, so I get something like the following:

enrollment_range | courses
10               | 1
100              | 1
500              | 1
                 | 3


问:
Javascript script doesn't load in HTML
```<code><!DOCTYPE html>
<html>
  <head>
    <title>Breakout</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>

    <canvas width="900" height="450" class="canvas"></canvas>

    <script src="scripts/base.js"></script>
  </body>
</html>
</code>```

This is the index file

```<code>*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}
</code>```

This is the CSS file

```<code>var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();
</code>```

And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.

答:
var context = canvas.getContext('2d'); should be var context = canvas[0].getContext('2d'); because you're using document.getElementsByClassName which will return a collection of all the elements with that class name. and you want the context of the first one.

context.drawRect should be context.rect.

context.fillStyle is not a function it should be context.fillStyle = "#0022ff";

context.endPath(); should be context.closePath();

In your case you don't need context.beginPath(); and context.closePath();. context.rect already creates the path.

var canvas = document.getElementsByClassName('canvas');
var context = canvas[0].getContext('2d');

context.rect(20, 30, 50, 40);
context.fillStyle = "#0022ff";
context.fill();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

.canvas {
  background-color: #b7b7b7;
}</code>```

<canvas width="900" height="450" class="canvas"></canvas>```

Title: Javascript script doesn't load in HTML

Body:
<!DOCTYPE html>

    <title>Breakout</title>
    <link rel="stylesheet" href="css/style.css">

    <canvas width="900" height="450" class="canvas"></canvas>

This is the index file

*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}

This is the CSS file

var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();

And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.

Body:
var context = canvas.getContext('2d'); should be var context = canvas[0].getContext('2d'); because you're using document.getElementsByClassName which will return a collection of all the elements with that class name. and you want the context of the first one.

context.drawRect should be context.rect.

context.fillStyle is not a function it should be context.fillStyle = "#0022ff";

context.endPath(); should be context.closePath();

In your case you don't need context.beginPath(); and context.closePath();. context.rect already creates the path.

var canvas = document.getElementsByClassName('canvas');
var context = canvas[0].getContext('2d');

context.rect(20, 30, 50, 40);
context.fillStyle = "#0022ff";
context.fill();

* {
  margin: 0;
  padding: 0;
}

.canvas {
  background-color: #b7b7b7;
}

<canvas width="900" height="450" class="canvas"></canvas>


问:
How to hover over ggplot with transformed values in shiny
I want to display some of the data in tooltip when hovering on the plot in shiny. I have used this script, and the data is showing nicely when I use the variables as they are (p and min_p). However what I really need is to display a log-transformed p and min_p, so my ggplot would be the following:

```<code>ggplot(dataset, aes(x = -log10(p), y = -log10(min_p))) +
    geom_point()
</code>```

And that's the problem, because hover_info does not recognize the data anymore, and I get the following error:

Error: replacement table has 0 rows, replaced table has 20

I am not sure how this can be fixed, and I admit I don't fully understand how the hovering works.

Here is the code with a sample data:

```<code>library(shiny)
library(shinydashboard)
library(ggplot2)

sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem("Plot result", tabName = "scatterplot", icon = icon("area-chart"))
  ))

body <- dashboardBody(
  tabItems(
    tabItem(tabName = "scatterplot",
            fluidRow(
              box(
                uiOutput("scatterPlotButton"),
                width = 5
              ),
              box(
                title="PLOT",solidHeader = TRUE, status="primary",
                plotOutput("plot",
                           hover = hoverOpts("plot_hover", delay = 100, delayType = "debounce")),
                uiOutput("hover_info"),
                width=9
              )
            )
    )
  )
)

ui=dashboardPage(
  dashboardHeader(title = "analysis"),
  sidebar,
  body
)

server=shinyServer(function(input, output, session) {
  dataset <- structure(list(p = c(6.03934743495282e-02, 1.50433174696588e-01,
                                  2.08047037184403e-03, 5.89297106629446e-05, 0.000102485231497565,
                                  0.0010651774924444, 0.0126458836222225, 0.000210364148948929,
                                  0.00274720409905674, 0.281095738489031, 0.000316170681574214,
                                  0.0316321461125659, 0.000369171267912158, 0.000369171267912158,
                                  0.0395213746526263, 0.475174078010843, 0.000718770258398781,
                                  0.760859052164441, 0.000810153915789446, 0.000875314011490406),
                            ratio_p_group_min = c(1.57380553778931, 1.11245772000324,
                                  1.504084996599, 1.00963266560562, 1.28098052443163, 1.49882201127675,
                                  1.10761702001084, 0.767267328293303, 1.03412495601202, 1.33508933929913,
                                  0.835478202626155, 0.998537147454481, 1.2008830437325, 1.2008830437325,
                                  1.15710746065582, 0.99677375722945, 1.37744067975694, 1.3666109673056,
                                  1.34583027836758, 1.34766012381264),
                            min_p = c(0.15789, 0.25772, 0.56599, 0.99632, 0.00004, 0.00275, 0.10761,
                                      0.76726, 0.00103, 0.00013, 0.83547, 0.99853, 0.00120, 0.12008,
                                      0.01157, 0.99677, 0.01377, 0.13666, 0.14583, 0.01347),
                            genes = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5", "Gene6", "Gene7",
                                      "Gene8", "Gene9", "Gene10", "Gene11", "Gene12", "Gene13", "Gene14",
                                      "Gene15", "Gene16", "Gene17", "Gene18", "Gene19", "Gene20")),
                       .Names = c("p", "ratio_p_group_min","min_p","genes"),
                       row.names = c(NA, 20L), class = "data.frame")

output$scatterPlotButton <- renderUI({
  actionButton("scatterPlotButton", "Generate Plot", class="btn-block btn-primary")
})

scatterPlot <- eventReactive(input$scatterPlotButton,{
  if (is.null(input$scatterPlotButton)) return()
  dataset <- dataset[which(round(dataset$ratio_p_group_min,digits=2)>=0 & round(-log10(dataset$p),digits=2)>=0 & !is.na(dataset$ratio_p_group_min)),]
  dataset$ratio_p_group_min=ifelse(dataset$ratio_p_group_min>2 & dataset$p>0.05,1,dataset$ratio_p_group_min)
  ggplot(dataset, aes(x = -log10(p), y = -log10(min_p))) +
    geom_point()
})

output$plot <- renderPlot({ scatterPlot() })

output$hover_info <- renderUI({
  if (is.null(input$scatterPlotButton)) return()
  dataset <- dataset[which(round(dataset$ratio_p_group_min,digits=2)>=0 & round(-log10(dataset$p),digits=2)>=0 & !is.na(dataset$ratio_p_group_min)),]
  hover <- input$plot_hover
  point <- nearPoints(dataset, hover, threshold = 5, maxpoints = 1, addDist = TRUE)
  if (nrow(point) == 0) return(NULL)

  left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left)
  top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom)

  left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left)
  top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top)

  style <- paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
                  "left:", left_px + 2, "px; top:", top_px + 2, "px;")
  wellPanel(
    style = style,
    p(HTML(paste0(point)))
  )
})
})

shinyApp(ui=ui, server=server)
</code>```

UPDATE

I have found a not so elegant solution: create new variables in dataset for -log10(p) and -log10(min_p) and use these new variables in ggplot.

```<code>dataset$LogP = -log10(dataset$p)
dataset$LogMinP = -log10(dataset$min_p)
ggplot(dataset, aes(x = LogP, y = LogMinP)) +
    geom_point()
</code>```

But I am still wondering if this could have been avoided somehow.

答: You could also use the plotly package. Simply call ggploty() after your ggplot object. </p>

Body:
I want to display some of the data in tooltip when hovering on the plot in shiny. I have used this script, and the data is showing nicely when I use the variables as they are (p and min_p). However what I really need is to display a log-transformed p and min_p, so my ggplot would be the following:

ggplot(dataset, aes(x = -log10(p), y = -log10(min_p))) +
    geom_point()

And that's the problem, because hover_info does not recognize the data anymore, and I get the following error:

Error: replacement table has 0 rows, replaced table has 20

I am not sure how this can be fixed, and I admit I don't fully understand how the hovering works.

Here is the code with a sample data:

library(shiny)
library(shinydashboard)
library(ggplot2)

sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem("Plot result", tabName = "scatterplot", icon = icon("area-chart"))
  ))

body <- dashboardBody(
  tabItems(
    tabItem(tabName = "scatterplot",
            fluidRow(
              box(
                uiOutput("scatterPlotButton"),
                width = 5
              ),
              box(
                title="PLOT",solidHeader = TRUE, status="primary",
                plotOutput("plot",
                           hover = hoverOpts("plot_hover", delay = 100, delayType = "debounce")),
                uiOutput("hover_info"),
                width=9
              )
            )
    )
  )
)

ui=dashboardPage(
  dashboardHeader(title = "analysis"),
  sidebar,
  body
)

server=shinyServer(function(input, output, session) {
  dataset <- structure(list(p = c(6.03934743495282e-02, 1.50433174696588e-01,
                                  2.08047037184403e-03, 5.89297106629446e-05, 0.000102485231497565,
                                  0.0010651774924444, 0.0126458836222225, 0.000210364148948929,
                                  0.00274720409905674, 0.281095738489031, 0.000316170681574214,
                                  0.0316321461125659, 0.000369171267912158, 0.000369171267912158,
                                  0.0395213746526263, 0.475174078010843, 0.000718770258398781,
                                  0.760859052164441, 0.000810153915789446, 0.000875314011490406),
                            ratio_p_group_min = c(1.57380553778931, 1.11245772000324,
                                  1.504084996599, 1.00963266560562, 1.28098052443163, 1.49882201127675,
                                  1.10761702001084, 0.767267328293303, 1.03412495601202, 1.33508933929913,
                                  0.835478202626155, 0.998537147454481, 1.2008830437325, 1.2008830437325,
                                  1.15710746065582, 0.99677375722945, 1.37744067975694, 1.3666109673056,
                                  1.34583027836758, 1.34766012381264),
                            min_p = c(0.15789, 0.25772, 0.56599, 0.99632, 0.00004, 0.00275, 0.10761,
                                      0.76726, 0.00103, 0.00013, 0.83547, 0.99853, 0.00120, 0.12008,
                                      0.01157, 0.99677, 0.01377, 0.13666, 0.14583, 0.01347),
                            genes = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5", "Gene6", "Gene7",
                                      "Gene8", "Gene9", "Gene10", "Gene11", "Gene12", "Gene13", "Gene14",
                                      "Gene15", "Gene16", "Gene17", "Gene18", "Gene19", "Gene20")),
                       .Names = c("p", "ratio_p_group_min","min_p","genes"),
                       row.names = c(NA, 20L), class = "data.frame")

output$scatterPlotButton <- renderUI({
  actionButton("scatterPlotButton", "Generate Plot", class="btn-block btn-primary")
})

scatterPlot <- eventReactive(input$scatterPlotButton,{
  if (is.null(input$scatterPlotButton)) return()
  dataset <- dataset[which(round(dataset$ratio_p_group_min,digits=2)>=0 & round(-log10(dataset$p),digits=2)>=0 & !is.na(dataset$ratio_p_group_min)),]
  dataset$ratio_p_group_min=ifelse(dataset$ratio_p_group_min>2 & dataset$p>0.05,1,dataset$ratio_p_group_min)
  ggplot(dataset, aes(x = -log10(p), y = -log10(min_p))) +
    geom_point()
})

output$plot <- renderPlot({ scatterPlot() })

output$hover_info <- renderUI({
  if (is.null(input$scatterPlotButton)) return()
  dataset <- dataset[which(round(dataset$ratio_p_group_min,digits=2)>=0 & round(-log10(dataset$p),digits=2)>=0 & !is.na(dataset$ratio_p_group_min)),]
  hover <- input$plot_hover
  point <- nearPoints(dataset, hover, threshold = 5, maxpoints = 1, addDist = TRUE)
  if (nrow(point) == 0) return(NULL)

  left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left)
  top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom)

  left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left)
  top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top)

  style <- paste0("position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); ",
                  "left:", left_px + 2, "px; top:", top_px + 2, "px;")
  wellPanel(
    style = style,
    p(HTML(paste0(point)))
  )
})
})

shinyApp(ui=ui, server=server)

UPDATE

I have found a not so elegant solution: create new variables in dataset for -log10(p) and -log10(min_p) and use these new variables in ggplot.

dataset$LogP = -log10(dataset$p)
dataset$LogMinP = -log10(dataset$min_p)
ggplot(dataset, aes(x = LogP, y = LogMinP)) +
    geom_point()

But I am still wondering if this could have been avoided somehow.


答:
or is there a more efficient way

You are heading to "overengeneering land", trying to fix things you cannot even name :) Is it slow? Sluggish? Then profile and fix relevant parts. "Efficient" is buzzword w/o defining what efficiency means for you.

what is the best way to prevent duplicate outputs / collisions if called multiple times

First, I'd use hashing functions with detailed (i.e. seconds or millis) timestamp + some mt_rand as input like instead. It's limited in length but you can call it multiple times and concatenate results (+ trim if needed). And if you want to be 1000% the value was never returned before, you must keep track of them, however you most likely can assume this is not going to happen if you will have input string long enough

Title: PHP random string function preventing duplicate outputs when called multiple times


问:
Transform relative path into absolute URL using PHP
How to, using php, transform relative path to absolute URL?</p>

答:
```<code>function rel2abs($rel, $base)
{
    /* return if already absolute URL */
    if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;

    /* queries and anchors */
    if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;

    /* parse base URL and convert to local variables:
       $scheme, $host, $path */
    extract(parse_url($base));

    /* remove non-directory element from path */
    $path = preg_replace('#/[^/]*$#', '', $path);

    /* destroy path if relative url points to root */
    if ($rel[0] == '/') $path = '';

    /* dirty absolute URL */
    $abs = "$host$path/$rel";

    /* replace '//' or '/./' or '/foo/../' with '/' */
    $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
    for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}

    /* absolute URL is ready! */
    return $scheme.'://'.$abs;
}
</code>```

ContentLicense: CC BY-SA 4.0


问:
javascript optimization for pair finding algorithm
I am working on a javascript function which takes an array of integers and a target as arguments. The task is to find the first pair of integers in the array whose sum is equal to the target.  I have tried this several different ways, but I keep getting a timeout error for larger input arrays. Can someone please give me some pointers on how to better optimize this code? Thanks!</p>

```<code>var sum_pairs = function(ints, s){
  var r = [];
  var a = true;
  var l = ints.length;
  for(var j = 0; j < l; j++){
    if(a){
      for(var i = 0; i < j; i++){
        if(ints[j] + ints[i] == s){
          r[0] = ints[i];
          r[1] = ints[j];
          a = false;
          break;
        }
      }
    }
    else{
      console.log('breaking');
      break;
    }
  }
return r[0] == null ? null : r;
}
</code>```

答:
You could use some speeding mechanisms, like

single loop,

hash table for visited values

variable a for element array[i]

very short variable names (just kidding)

Long list needs 153 ms.

var sum_pairs = function (array, s) {
    var a, i,
        hash = Object.create(null);

    for (i = 0; i < array.length; i++) {
        a = array[i];
        if (hash[s - a]) {
            return [s - a, a];
        }
        if (!hash[a]) {
            hash[a] = true;
        }
    }
};

console.log(sum_pairs([11, 3, 7, 5], 10));        // [3, 7]
console.log(sum_pairs([4, 3, 2, 3, 4], 6));       // [4, 2]
console.log(sum_pairs([0, 0, -2, 3], 2));         // undefined
console.log(sum_pairs([10, 5, 2, 3, 7, 5], 10));  // [3, 7]
console.log(sum_pairs([1, 2, 3, 4, 1, 0], 2));    // [1, 1]
console.log(sum_pairs([1, -2, 3, 0, -6, 1], -6)); // [0, -6]
console.log(sum_pairs([0, 2, 0], 0));             // [0, 0]
console.log(sum_pairs([5, 9, 13, -3], 10));       // [13, -3]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I am working on a javascript function which takes an array of integers and a target as arguments. The task is to find the first pair of integers in the array whose sum is equal to the target.  I have tried this several different ways, but I keep getting a timeout error for larger input arrays. Can someone please give me some pointers on how to better optimize this code? Thanks!

var sum_pairs = function(ints, s){
  var r = [];
  var a = true;
  var l = ints.length;
  for(var j = 0; j < l; j++){
    if(a){
      for(var i = 0; i < j; i++){
        if(ints[j] + ints[i] == s){
          r[0] = ints[i];
          r[1] = ints[j];
          a = false;
          break;
        }
      }
    }
    else{
      console.log('breaking');
      break;
    }
  }
return r[0] == null ? null : r;
}

Body:
You could use some speeding mechanisms, like

single loop,

hash table for visited values

variable a for element array[i]

very short variable names (just kidding)

Long list needs 153 ms.

var sum_pairs = function (array, s) {
    var a, i,
        hash = Object.create(null);

    for (i = 0; i < array.length; i++) {
        a = array[i];
        if (hash[s - a]) {
            return [s - a, a];
        }
        if (!hash[a]) {
            hash[a] = true;
        }
    }
};

console.log(sum_pairs([11, 3, 7, 5], 10));        // [3, 7]
console.log(sum_pairs([4, 3, 2, 3, 4], 6));       // [4, 2]
console.log(sum_pairs([0, 0, -2, 3], 2));         // undefined
console.log(sum_pairs([10, 5, 2, 3, 7, 5], 10));  // [3, 7]
console.log(sum_pairs([1, 2, 3, 4, 1, 0], 2));    // [1, 1]
console.log(sum_pairs([1, -2, 3, 0, -6, 1], -6)); // [0, -6]
console.log(sum_pairs([0, 2, 0], 0));             // [0, 0]
console.log(sum_pairs([5, 9, 13, -3], 10));       // [13, -3]

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Docker continuum/miniconda3 container not showing "conda"
I have a Docker container running the continuum/miniconda3 image with a Django project that is successfully serving to localhost:8000, and I can see my project running in the browser. The container is built with the following Dockerfile

```<code>FROM continuumio/miniconda3
ENV PYTHONUNBUFFERED 1
RUN mkdir /pft
WORKDIR /pft
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
RUN apt-get update && apt-get install -y && \
apt-get install build-essential libssl-dev -y && \
rm -rf /var/lib/apt/lists/*
RUN conda create --name pft python=3
RUN source activate pft
RUN pip install 'django==1.10.5'
</code>```

However, when I try and run the "conda" command in the running terminal with the following:

```<code>docker exec -it my_running_container /bin/bash
</code>```

I am getting this error message:

```<code>root@ad9621c5e9bd:/pft# conda
bash: conda: command not found
</code>```

What else is confusing is that in the Dockerfile the official image uses which can be found here https://hub.docker.com/r/continuumio/miniconda3/~/dockerfile/

An image is built with the following command, and I am not seeing  the either /etc/profile.d/conda.sh or /opt/conda.

```<code>RUN echo 'export PATH=/opt/conda/bin:$PATH' > /etc/profile.d/conda.sh && \
wget --quiet https://repo.continuum.io/miniconda/Miniconda3-4.3.14-Linux-x86_64.sh -O ~/miniconda.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm ~/miniconda.sh
</code>```

I am sure that I am attaching to the correct container for one because I can see the mounted volume in the container, and for two I can see there is only one running container when I use:

```<code>docker container ls -a
</code>```

UPDATE:

I am using a docker-compose.yml file which builds the container from the Dockerfile. I am not necessarily convinced that the container the compose creates is what I am thinking it is. When I use:

```<code>docker-compose up
</code>```

It says:

```<code>creating some_container
Attaching to some_container
</code>```

This is the Service I am trying to attach to. I am trying to attach with:

```<code>docker-compose exec -it web bash
</code>```

The following is my docker-compose.yml file.

```<code> version: "3"
 services:

   web:
     build: ./config/src
     command: python manage.py runserver 0.0.0.0:8000
     volumes:
       - ./src:/pft
     ports:
       - "8000:8000"
</code>```

If I run the container based of the the image built with the Dockerfile via:

```<code>docker run -it some_docker_image
</code>```

and I try to attach to it via:

```<code>docker exec -it my_running_container /bin/bash
</code>```0

When I change the command to run in the docker-compose file from

```<code>docker exec -it my_running_container /bin/bash
</code>```1

to:

```<code>docker exec -it my_running_container /bin/bash
</code>```2

I get the following error with docker-compose up.

```<code>ERROR: for web  Cannot start service web: oci runtime error:
container_linux.go:247: starting container process caused "exec: \"source\":
executable file not found in $PATH"
</code>```

What is weird, is if I manually build an image and "docker run" a container based off that image using my Dockerfile, it works as expected. When I look up the image docker-compose automatically creates from the Dockerfile, and try to "docker run" a container from the image, it gives the errors mentioned above. Why is this image different than the image created with the manual "docker build" command?

答:
I found the problem. When you use docker-compose up, and you have changed anything in your Dockerfile that the docker-compose file uses to build the service and containers from, you will need to use :

```<code>docker-compose up --build
</code>```

because docker-compose is going to use the previous image that was built. After, re-building the image I am now able to attach to the running container, and everything is working as expected.

Body:
I have a Docker container running the continuum/miniconda3 image with a Django project that is successfully serving to localhost:8000, and I can see my project running in the browser. The container is built with the following Dockerfile

FROM continuumio/miniconda3
ENV PYTHONUNBUFFERED 1
RUN mkdir /pft
WORKDIR /pft
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
RUN apt-get update && apt-get install -y && \
apt-get install build-essential libssl-dev -y && \
rm -rf /var/lib/apt/lists/*
RUN conda create --name pft python=3
RUN source activate pft
RUN pip install 'django==1.10.5'

However, when I try and run the "conda" command in the running terminal with the following:

docker exec -it my_running_container /bin/bash

I am getting this error message:

root@ad9621c5e9bd:/pft# conda
bash: conda: command not found

What else is confusing is that in the Dockerfile the official image uses which can be found here https://hub.docker.com/r/continuumio/miniconda3/~/dockerfile/

An image is built with the following command, and I am not seeing  the either /etc/profile.d/conda.sh or /opt/conda.

RUN echo 'export PATH=/opt/conda/bin:$PATH' > /etc/profile.d/conda.sh && \
wget --quiet https://repo.continuum.io/miniconda/Miniconda3-4.3.14-Linux-x86_64.sh -O ~/miniconda.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm ~/miniconda.sh

I am sure that I am attaching to the correct container for one because I can see the mounted volume in the container, and for two I can see there is only one running container when I use:

docker container ls -a

UPDATE:

I am using a docker-compose.yml file which builds the container from the Dockerfile. I am not necessarily convinced that the container the compose creates is what I am thinking it is. When I use:

docker-compose up

It says:

creating some_container
Attaching to some_container

This is the Service I am trying to attach to. I am trying to attach with:

docker-compose exec -it web bash

The following is my docker-compose.yml file.

 version: "3"
 services:

   web:
     build: ./config/src
     command: python manage.py runserver 0.0.0.0:8000
     volumes:
       - ./src:/pft
     ports:
       - "8000:8000"

If I run the container based of the the image built with the Dockerfile via:

docker run -it some_docker_image

and I try to attach to it via:

docker exec -it my_running_container /bin/bash

When I change the command to run in the docker-compose file from

command: python manage.py runserver 0.0.0.0:8000

to:

command: source activate pft && python manage.py runserver 0.0.0.0:8000

I get the following error with docker-compose up.

ERROR: for web  Cannot start service web: oci runtime error:
container_linux.go:247: starting container process caused "exec: \"source\":
executable file not found in $PATH"

What is weird, is if I manually build an image and "docker run" a container based off that image using my Dockerfile, it works as expected. When I look up the image docker-compose automatically creates from the Dockerfile, and try to "docker run" a container from the image, it gives the errors mentioned above. Why is this image different than the image created with the manual "docker build" command?

Body:
I found the problem. When you use docker-compose up, and you have changed anything in your Dockerfile that the docker-compose file uses to build the service and containers from, you will need to use :

docker-compose up --build

because docker-compose is going to use the previous image that was built. After, re-building the image I am now able to attach to the running container, and everything is working as expected.


问:
First steps in python: how to combine two lists
So I just started learning a few basics with Python. Since I am a pretty practical person, I enjoy doing it with the book "Automate the boring stuff with Python".

No there is a chapter introducing lists in python and their advantages.
To be practical one should write a code which asks the user to enter cat names, which then will be added to the list. If no cat name is added anymore, all the cat names should be displayed.

Until now, fair enough. So I thought I should give it a try and go a small step further and extend the functionality by adding the ages of the cats. The desired result would be that the user is asked for the name input, then the age input, the name input again and the age input again and so on. If the user doesn´t put in a name again, it should list the cats with the respective ages.

I created a second list and also the second input and everything kinda works but I just dont know how to combine the both lists or rather the values.

It just gives me the two names first and then the two ages.

Is anyone happy to help me with this beginner problem?

Thanks in advance

```<code>catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter
          nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for name in catNames:
            print(" " + name)
        for age in catAges:
            print(" " + age)
        break
    catNames = catNames + [name]
    catAges = catAges + [age]
</code>```

答:
If I can understand correctly you want it to print the age and the name together?
Well if thats so you can do it like this:

```<code>catNames = []
catAges = []

while True:
    name = input("Enter the name of Cat {} (Or enter nothing to stop): ".format(str(len(catNames) + 1)))
    while name != "":
        age = input("Enter the age of {}: ".format(name)) # Takes inputted name and adds it to the print function.
        catNames.append(name) # Adds the newest name the end of the catNames list.
        catAges.append(age) # Adds the newest age the end of the catNames list.
        break

    if name == "":
        print("\nThe cat names and ages are: ")
        for n in range(len(catNames)):
            print("\nName: {}\nAge: {}".format(catNames[n], catAges[n]))
        break
</code>```

Resulting output:

```<code>Enter the name of Cat 1 (Or enter nothing to stop): Cat1
Enter the age of Cat1: 5
Enter the name of Cat 2 (Or enter nothing to stop): Cat2
Enter the age of Cat2: 7
Enter the name of Cat 3 (Or enter nothing to stop): # I hit enter here so it skips.

The cat names and ages are:

Name: Cat1
Age: 5

Name: Cat2
Age: 7
</code>```

If you have any issues with what I did, please just ask.

Body:
So I just started learning a few basics with Python. Since I am a pretty practical person, I enjoy doing it with the book "Automate the boring stuff with Python".

No there is a chapter introducing lists in python and their advantages.
To be practical one should write a code which asks the user to enter cat names, which then will be added to the list. If no cat name is added anymore, all the cat names should be displayed.

Until now, fair enough. So I thought I should give it a try and go a small step further and extend the functionality by adding the ages of the cats. The desired result would be that the user is asked for the name input, then the age input, the name input again and the age input again and so on. If the user doesn´t put in a name again, it should list the cats with the respective ages.

I created a second list and also the second input and everything kinda works but I just dont know how to combine the both lists or rather the values.

It just gives me the two names first and then the two ages.

Is anyone happy to help me with this beginner problem?

Thanks in advance

catNames = []
catAges = []

while True:
    print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter
          nothing to stop.)")
    name = input()
    while name !="":
        print("Enter the age of cat ")
        age = input()
        break

    if name == "":
        print("The cat names and ages are: ")
        for name in catNames:
            print(" " + name)
        for age in catAges:
            print(" " + age)
        break
    catNames = catNames + [name]
    catAges = catAges + [age]

Body:
If I can understand correctly you want it to print the age and the name together?
Well if thats so you can do it like this:

catNames = []
catAges = []

while True:
    name = input("Enter the name of Cat {} (Or enter nothing to stop): ".format(str(len(catNames) + 1)))
    while name != "":
        age = input("Enter the age of {}: ".format(name)) # Takes inputted name and adds it to the print function.
        catNames.append(name) # Adds the newest name the end of the catNames list.
        catAges.append(age) # Adds the newest age the end of the catNames list.
        break

    if name == "":
        print("\nThe cat names and ages are: ")
        for n in range(len(catNames)):
            print("\nName: {}\nAge: {}".format(catNames[n], catAges[n]))
        break

Resulting output:

Enter the name of Cat 1 (Or enter nothing to stop): Cat1
Enter the age of Cat1: 5
Enter the name of Cat 2 (Or enter nothing to stop): Cat2
Enter the age of Cat2: 7
Enter the name of Cat 3 (Or enter nothing to stop): # I hit enter here so it skips.

The cat names and ages are:

Name: Cat1
Age: 5

Name: Cat2
Age: 7

If you have any issues with what I did, please just ask.


问:
In an array of objects, fastest way to find the index of an object whose attributes match a search
I've been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:

```<code>array[i].id = some number;
array[i].name = some name;
</code>```

What I want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4.
I suppose I could just do something like :

```<code>var indexes = [];
for(i=0; i<array.length; i++) {
  (array[i].id === 0) ? { indexes[0] = i }
  (array[i].id === 1) ? { indexes[1] = i }
  (array[i].id === 2) ? { indexes[2] = i }
  (array[i].id === 3) ? { indexes[3] = i }
  (array[i].id === 4) ? { indexes[4] = i }
}
</code>```

While this would work, it looks to be quite expensive and slow (not to mention ugly), especially if array.length could be large. Any ideas on how to spruce this up a bit? I thought of using array.indexOf somehow but I don't see how to force the syntax. This

```<code>array.indexOf(this.id === 0);
</code>```

for example, returns undefined, as it probably should.

答:
Using the ES6 map function:

```<code>let idToFind = 3;
let index = someArray.map(obj => obj.id).indexOf(idToFind);
</code>```

Body:
I've been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:

array[i].id = some number;
array[i].name = some name;

What I want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4.
I suppose I could just do something like :

var indexes = [];
for(i=0; i<array.length; i++) {
  (array[i].id === 0) ? { indexes[0] = i }
  (array[i].id === 1) ? { indexes[1] = i }
  (array[i].id === 2) ? { indexes[2] = i }
  (array[i].id === 3) ? { indexes[3] = i }
  (array[i].id === 4) ? { indexes[4] = i }
}

While this would work, it looks to be quite expensive and slow (not to mention ugly), especially if array.length could be large. Any ideas on how to spruce this up a bit? I thought of using array.indexOf somehow but I don't see how to force the syntax. This

array.indexOf(this.id === 0);

for example, returns undefined, as it probably should.

Body:
Using the ES6 map function:

let idToFind = 3;
let index = someArray.map(obj => obj.id).indexOf(idToFind);


问:
What is the difference between cropping, resizing and scaling an image?
I am using Perl's
Image::Imlib2
package to generate thumbnails from larger images.

I've done such tasks before with several ImageMagick interfaces (PHP, Ruby, Python) and it was relatively easy. I have no prior experience with Imlib2 and it is a long time since I wrote something in Perl, so I am sorry if this seems naive!

This is what I've tried so far. It is simple, and assumes that scaling an image will keep the aspect ratio, and the generated thumbnail will be an exact miniature copy of the original image.

```<code>use strict;
use warnings;

use Image::Imlib2;

my $dir = 'imgs/*';

my @files = glob ($dir);

foreach my $img ( @files ) {
    my $image = Image::Imlib2->load($img);
    my $cropped_image = $image->create_scaled_image(50, 50);
    $cropped_image->save($img);
}
</code>```

Original image

Generated image

My first look at the image tells me that something is wrong. It may be my ignorance on cropping, resizing and scaling, but the generated image is displaying wrongly on small screens.

I've read What's the difference between cropping and resizing?, and honestly didn't understand anything. Also this one Image scaling.

Could someone explain the differences between those three ideas, and if possible give examples (preferably with Perl) to achieve better results? Or at least describe what I should consider when I want to create thumbnails?

答:
The code you use isn't preserving the aspect-ratio.  From Image::Imlib2::create_scaled_image

If x or y are 0, then retain the aspect ratio given in the other.

So change the line

```<code>my $cropped_image = $image->create_scaled_image(50, 50);
</code>```

to

```<code>my $scaled_image  = $image->create_scaled_image(50, 0);
</code>```

and the new image will be 50 pixels wide, and its height computed so to keep the original aspect-ratio.

Since this is not cropping I've changed the variable name as well.

As for other questions, below is a basic discussion from comments. Please search for tutorials on image processing. Also, documentation of major libraries often have short and good explanations.

This is aggregated from comments deemed helpful. Also see Borodin's short and clear answer.

Imagine that you want to draw a picture (of some nice photograph) yourself in the following way. You draw a grid of, say, 120 (horizontally) by 60 (vertically) boxes. So 120 x 60, 720 boxes. These are your "pixels," and each you may fill with only one color. If the photo you are re-drawing is "mostly" blue at some spot, you color that pixel blue. Etc. It is not easy to end up with a faithful redrawing -- the denser the pixels the beter.

Now imagine that you want to draw another copy of this, just smaller. If you make it 20x20 that will be completely different, since it's a square. The best chance of getting it to "look the same" is to pick 2-to-1 ratio (like 120x60), so say 40x20. That's "aspect-ratio." But there is still a problem, since now you have to decide all over again what color to pick for each box, so to represent what is "mostly" on the photo at that spot. There are algorithms for that ("sampling," see your second link). That's involved with "resizing." The "quality" of the obtained drawing clearly must be much worse.

So "resizing" isn't all that simple. But, for us users, we mostly need to roughly know what is involved, and to find out how to use these features in a library. So read documentation. Some uses are very simple, while sometimes you'll have to decide which "algorithm" to let it use, or some such. Again, what I do is read manuals carefully.

The basic version of "cropping" is simple -- you just cut off a part of the picture.  Say, remove the first and last 20 columns and the bottom and top 10 rows, and from the initial 120x60 you get a picture of 80x40. This is normally done when outer parts of an image have just white areas (or, worse, black!). So you want to "cut out" the picture itself from the whole image. Many graphics tools can do that on their own, by analyzing the image and figuring out those areas. Or, we select and hit a button.

Body:
I am using Perl's
Image::Imlib2
package to generate thumbnails from larger images.

I've done such tasks before with several ImageMagick interfaces (PHP, Ruby, Python) and it was relatively easy. I have no prior experience with Imlib2 and it is a long time since I wrote something in Perl, so I am sorry if this seems naive!

This is what I've tried so far. It is simple, and assumes that scaling an image will keep the aspect ratio, and the generated thumbnail will be an exact miniature copy of the original image.

use strict;
use warnings;

use Image::Imlib2;

my $dir = 'imgs/*';

my @files = glob ($dir);

foreach my $img ( @files ) {
    my $image = Image::Imlib2->load($img);
    my $cropped_image = $image->create_scaled_image(50, 50);
    $cropped_image->save($img);
}

Original image

Generated image

My first look at the image tells me that something is wrong. It may be my ignorance on cropping, resizing and scaling, but the generated image is displaying wrongly on small screens.

I've read What's the difference between cropping and resizing?, and honestly didn't understand anything. Also this one Image scaling.

Could someone explain the differences between those three ideas, and if possible give examples (preferably with Perl) to achieve better results? Or at least describe what I should consider when I want to create thumbnails?

Body:
The code you use isn't preserving the aspect-ratio.  From Image::Imlib2::create_scaled_image

If x or y are 0, then retain the aspect ratio given in the other.

So change the line

my $cropped_image = $image->create_scaled_image(50, 50);

to

my $scaled_image  = $image->create_scaled_image(50, 0);

and the new image will be 50 pixels wide, and its height computed so to keep the original aspect-ratio.

Since this is not cropping I've changed the variable name as well.

As for other questions, below is a basic discussion from comments. Please search for tutorials on image processing. Also, documentation of major libraries often have short and good explanations.

This is aggregated from comments deemed helpful. Also see Borodin's short and clear answer.

Imagine that you want to draw a picture (of some nice photograph) yourself in the following way. You draw a grid of, say, 120 (horizontally) by 60 (vertically) boxes. So 120 x 60, 720 boxes. These are your "pixels," and each you may fill with only one color. If the photo you are re-drawing is "mostly" blue at some spot, you color that pixel blue. Etc. It is not easy to end up with a faithful redrawing -- the denser the pixels the beter.

Now imagine that you want to draw another copy of this, just smaller. If you make it 20x20 that will be completely different, since it's a square. The best chance of getting it to "look the same" is to pick 2-to-1 ratio (like 120x60), so say 40x20. That's "aspect-ratio." But there is still a problem, since now you have to decide all over again what color to pick for each box, so to represent what is "mostly" on the photo at that spot. There are algorithms for that ("sampling," see your second link). That's involved with "resizing." The "quality" of the obtained drawing clearly must be much worse.

So "resizing" isn't all that simple. But, for us users, we mostly need to roughly know what is involved, and to find out how to use these features in a library. So read documentation. Some uses are very simple, while sometimes you'll have to decide which "algorithm" to let it use, or some such. Again, what I do is read manuals carefully.

The basic version of "cropping" is simple -- you just cut off a part of the picture.  Say, remove the first and last 20 columns and the bottom and top 10 rows, and from the initial 120x60 you get a picture of 80x40. This is normally done when outer parts of an image have just white areas (or, worse, black!). So you want to "cut out" the picture itself from the whole image. Many graphics tools can do that on their own, by analyzing the image and figuring out those areas. Or, we select and hit a button.


问:
Cloud Functions for Firebase Async Await style
Looks like Cloud Functions does not support Async-Await notation. Is there a way I could use Babel until they do or is it recommended to use promises?

My current function that sits on Node is like so:

```<code>exports.getToken = async (req, res) => {
  //1. Generate token from Braintree
  const result = await gateway.clientToken.generate();

  //2. Return the client token
  res.json(result.clientToken);
};
</code>```

答:
Cloud Functions runs the LTS version of node.js, which according to the documentation is 6.14.0 at this moment in time. node 6.x supports EcmaScript 6, which does not include async/await.

However, you can write your code in TypeScript and have that transpiled down to ES5/ES6, which will effectively convert the use of async/await into promises.  A web search suggests that perhaps this plugin can be used to help Babel with similar transpiling.

It's worth noting that the Firebase CLI now allow you to initialize a new Cloud Functions project with native TypeScript support, which is what the Firebase team is currently recommending to developers.

If you don't want to use TypeScript, you can now also choose node 8 (which is currently in beta, and does support async/await for plain JavaScript) as a deployment target.  You can follow the documentation to edit your package.json to indicates that your functions should be deployed to node 8.

Body:
Looks like Cloud Functions does not support Async-Await notation. Is there a way I could use Babel until they do or is it recommended to use promises?

My current function that sits on Node is like so:

exports.getToken = async (req, res) => {
  //1. Generate token from Braintree
  const result = await gateway.clientToken.generate();

  //2. Return the client token
  res.json(result.clientToken);
};


问:
Count the number of null values into an Oracle table?
I need to count the number of null values of all the columns in a table in Oracle.

For instance, I execute the following statements to create a table TEST and insert data.

```<code> CREATE TABLE TEST
 (  A VARCHAR2(20 BYTE),
    B VARCHAR2(20 BYTE),
    C VARCHAR2(20 BYTE)
  );
Insert into TEST (A) values ('a');
Insert into TEST (B) values ('b');
Insert into TEST (C) values ('c');
</code>```

Now, I write the following code to compute the number of null values in the table TEST:

```<code>declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, data_type
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.data_type <> 'NOT NULL' then
         select count(*) into temp FROM TEST where r.column_name IS NULL;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/
</code>```

It returns 0, when the expected value is 6.

Where is the error?

Thanks in advance.

答:
Thank you @Lord Peter :

The below PL/SQL script works

```<code>declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, nullable
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.nullable = 'Y' then
         EXECUTE IMMEDIATE 'SELECT count(*) FROM test where '|| r.column_name ||' IS NULL' into temp ;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/
</code>```

The table name test may be replaced the name of table of your interest.

I hope this solution is useful!

Body:
I need to count the number of null values of all the columns in a table in Oracle.

For instance, I execute the following statements to create a table TEST and insert data.

 CREATE TABLE TEST
 (  A VARCHAR2(20 BYTE),
    B VARCHAR2(20 BYTE),
    C VARCHAR2(20 BYTE)
  );
Insert into TEST (A) values ('a');
Insert into TEST (B) values ('b');
Insert into TEST (C) values ('c');

Now, I write the following code to compute the number of null values in the table TEST:

declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, data_type
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.data_type <> 'NOT NULL' then
         select count(*) into temp FROM TEST where r.column_name IS NULL;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/

It returns 0, when the expected value is 6.

Where is the error?

Thanks in advance.

Body:
Thank you @Lord Peter :

The below PL/SQL script works

declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, nullable
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.nullable = 'Y' then
         EXECUTE IMMEDIATE 'SELECT count(*) FROM test where '|| r.column_name ||' IS NULL' into temp ;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/

The table name test may be replaced the name of table of your interest.

I hope this solution is useful!


问:
How to add an infinite number of images to the html5 canvas?
I want to let a user drag and drop as many images as they wish onto an html5 canvas. From tutorials online I gather its something like:

```<code>var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),

    imgs = arr.map(function callback(currentValue, index, array) {
        img = img = document.createElement("img");
    }[, thisArg])
    mouseDown = false,
    brushColor = "rgb(0, 0, 0)",
    hasText = true,
    clearCanvas = function () {
        if (hasText) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            hasText = false;
        }
    };

for (var i=0;i<imgs.length;i++){
    imgs[i].addEventListener("load",function(){
        context.drawImage(img,0,0);
    })
}
</code>```

I know line 4 is completely wrong..., but usually people seem to create their images as variables and then change the source with the dragged image. Since I want as many images as the user wishes to add, that would be an array without any size?

Furthermore, Since this code gets called once, on page load, this array cannot be appended to later (like when the user decides to add another image). So maybe this entire paradigm is incorrect in this case?

Can someone advise me on how to go about this? Thanks!

EDIT:

proposed solution:

```<code>imgs_arr = [];
var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    imgs = imgs_arr.map(function callback(src) {
        var img = document.createElement("img");
        img.src = src;
        return img;
    });
    mouseDown = false,
    brushColor = "rgb(0, 0, 0)",
    hasText = true,
    clearCanvas = function () {
        if (hasText) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            hasText = false;
        }
    };

// Adding instructions
context.fillText("Drop an image onto the canvas", 240, 200);
context.fillText("Click a spot to set as brush color", 240, 220);

function drawImage(element,index,array){
    element.addEventListener("load",function(){
        clearCanvas()
        context.drawImage(element,0,0)
    })
}
imgs_arr.forEach(drawImage);
</code>```

Currently throws : Cannot read property 'appendChild' of null(anonymous function) because my imgs_arr is blank - no one has added images yet.

答:
Assuming your arr is an array of image URLs, your map should look like this:

```<code>imgs = arr.map(function callback(src) {
  var img = document.createElement("img");
  img.src = src;
  return img;
});
</code>```

I renamed currentValue to src to make sense as to what it is, and I removed the extra parameters, but that was all technically optional.

The important parts are:

Create a new img element and assign it to a variable.

Assign the URL to the src of that `img.

Return the image.

The map() function gathers up all the values returned from the callback and turns those into an array. That'll give you an array of Image objects (which are the JS form of the HTML  element).

The rest looks more or less correct (though you really should use ; instead of , for ending your lines to avoid possible weird things).

Also, for adding more after it is initialized, you should just have to push() a new Image onto the array and then redraw it.

Body:
I want to let a user drag and drop as many images as they wish onto an html5 canvas. From tutorials online I gather its something like:

var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),

    imgs = arr.map(function callback(currentValue, index, array) {
        img = img = document.createElement("img");
    }[, thisArg])
    mouseDown = false,
    brushColor = "rgb(0, 0, 0)",
    hasText = true,
    clearCanvas = function () {
        if (hasText) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            hasText = false;
        }
    };

for (var i=0;i<imgs.length;i++){
    imgs[i].addEventListener("load",function(){
        context.drawImage(img,0,0);
    })
}

I know line 4 is completely wrong..., but usually people seem to create their images as variables and then change the source with the dragged image. Since I want as many images as the user wishes to add, that would be an array without any size?

Furthermore, Since this code gets called once, on page load, this array cannot be appended to later (like when the user decides to add another image). So maybe this entire paradigm is incorrect in this case?

Can someone advise me on how to go about this? Thanks!

EDIT:

proposed solution:

imgs_arr = [];
var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    imgs = imgs_arr.map(function callback(src) {
        var img = document.createElement("img");
        img.src = src;
        return img;
    });
    mouseDown = false,
    brushColor = "rgb(0, 0, 0)",
    hasText = true,
    clearCanvas = function () {
        if (hasText) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            hasText = false;
        }
    };

// Adding instructions
context.fillText("Drop an image onto the canvas", 240, 200);
context.fillText("Click a spot to set as brush color", 240, 220);

function drawImage(element,index,array){
    element.addEventListener("load",function(){
        clearCanvas()
        context.drawImage(element,0,0)
    })
}
imgs_arr.forEach(drawImage);

Currently throws : Cannot read property 'appendChild' of null(anonymous function) because my imgs_arr is blank - no one has added images yet.

Body:
Assuming your arr is an array of image URLs, your map should look like this:

imgs = arr.map(function callback(src) {
  var img = document.createElement("img");
  img.src = src;
  return img;
});

I renamed currentValue to src to make sense as to what it is, and I removed the extra parameters, but that was all technically optional.

The important parts are:

Create a new img element and assign it to a variable.

Assign the URL to the src of that `img.

Return the image.

The map() function gathers up all the values returned from the callback and turns those into an array. That'll give you an array of Image objects (which are the JS form of the HTML <img> element).

The rest looks more or less correct (though you really should use ; instead of , for ending your lines to avoid possible weird things).

Also, for adding more after it is initialized, you should just have to push() a new Image onto the array and then redraw it.


问:
Web Config Connection Setting
I heve designed a website in which every pages are given connection with SQL server by writing the codes in each page....Can anybody helps me out to do this job only in the web config file at once...

Thanks in advance..!

答:
```<code><connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=(local);
        Initial Catalog=DbName; Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Web Config Connection Setting


答:
Resizing and scaling is the same; you just change the size of the image. You can make it smaller or bigger.

Depending on the interface, you have to give either the new dimensions or a scaling factor for the operation. A factor less than or greater than 1.0 would make the image smaller or bigger. Smaller images are created by subsampling and bigger images by interpolation.

Cropping is very simple. You select a rectangular region of an image and that's your new image. It's like using scissors.

In your code example the image is named cropped_image although it is created through scaling, or resizing.

The output image is an image of size 50 x 50 pixels. That's what you did here:

```<code>  my $cropped_image = $image->create_scaled_image(50, 50);
</code>```

So no matter how your image looks before, you stuff it into 50 x 50 pixels. In this case not only reducing the resolution but also changing the aspect ratio.

The image is not displayed improperly, it's displayed perfectly fine.

Title: What is the difference between cropping, resizing and scaling an image?

Body:
Resizing and scaling is the same; you just change the size of the image. You can make it smaller or bigger.

Depending on the interface, you have to give either the new dimensions or a scaling factor for the operation. A factor less than or greater than 1.0 would make the image smaller or bigger. Smaller images are created by subsampling and bigger images by interpolation.

Cropping is very simple. You select a rectangular region of an image and that's your new image. It's like using scissors.

In your code example the image is named cropped_image although it is created through scaling, or resizing.

The output image is an image of size 50 x 50 pixels. That's what you did here:

  my $cropped_image = $image->create_scaled_image(50, 50);

So no matter how your image looks before, you stuff it into 50 x 50 pixels. In this case not only reducing the resolution but also changing the aspect ratio.

The image is not displayed improperly, it's displayed perfectly fine.


问:
Constructing printable representation of an object similar to __repr__ in Python
I'm fairly new to C++ mostly have used Python in the past and am looking for a way to easily construct a printable representation of an object - similar in vein to Python's repr. Here are some snippets from my code (it's a bank of course).

```<code>    class Account   {
    private:
        int pin;
        string firstName;
        string lastName;
        char minit;
        int acc_num;
        float balance;
        float limit;
    public:
        float getBalance(void);
        string getName(void);
        void setPin(int);
        void makeDeposit(float);
        void makeWithdrawal(float);
        Account(float initialDeposit, string fname, string lname, char MI = ' ', float x = 0);
    };
Account::Account(float initialDeposit, string fname, string lname, char MI, float x)  {
    cout << "Your account is being created" << endl;
    firstName = fname;
    lastName = lname;
    minit = MI;
    balance = initialDeposit;
    limit = x;
    pin = rand()%8999+1000;
}
</code>```

Account object constructed. I want to have a Bank object which is essentially an array of account objects.

```<code>    class BankSystem    {
    private:
        vector<Account> listOfAccounts;
        int Client_ID;
    public:
        BankSystem(int id);
        void addAccount(Account acc);
        Account getAccount(int j);
    };
BankSystem::BankSystem(int id)  {
    Client_ID = id;
    listOfAccounts.reserve(10);
}
</code>```

I would like to give the Bank class showAccounts method function which displays to the user all the account objects that they have access to. I'd like to make this printable so I can display it in cout. In Python I'd simply just use the __repr__ to "stringify" the account objects e.g.

```<code>def __repr__(self):
    return 'Account(x=%s, y=%s)' % (self.x, self.y)
</code>```

Wondering how I'd go about doing the same in C++. Thanks!

答:
Is this what you are looking for?</p>

```<code>void BankSystem::showAccounts(){
    for (Account a: listOfAccounts){
        a.showAccount();
    }
}

void Account::showAccount(){
    cout << //all your printing information you want using your account
            //class variables
}
</code>```

Body:
I'm fairly new to C++ mostly have used Python in the past and am looking for a way to easily construct a printable representation of an object - similar in vein to Python's repr. Here are some snippets from my code (it's a bank of course).

    class Account   {
    private:
        int pin;
        string firstName;
        string lastName;
        char minit;
        int acc_num;
        float balance;
        float limit;
    public:
        float getBalance(void);
        string getName(void);
        void setPin(int);
        void makeDeposit(float);
        void makeWithdrawal(float);
        Account(float initialDeposit, string fname, string lname, char MI = ' ', float x = 0);
    };
Account::Account(float initialDeposit, string fname, string lname, char MI, float x)  {
    cout << "Your account is being created" << endl;
    firstName = fname;
    lastName = lname;
    minit = MI;
    balance = initialDeposit;
    limit = x;
    pin = rand()%8999+1000;
}

Account object constructed. I want to have a Bank object which is essentially an array of account objects.

    class BankSystem    {
    private:
        vector<Account> listOfAccounts;
        int Client_ID;
    public:
        BankSystem(int id);
        void addAccount(Account acc);
        Account getAccount(int j);
    };
BankSystem::BankSystem(int id)  {
    Client_ID = id;
    listOfAccounts.reserve(10);
}

I would like to give the Bank class showAccounts method function which displays to the user all the account objects that they have access to. I'd like to make this printable so I can display it in cout. In Python I'd simply just use the __repr__ to "stringify" the account objects e.g.

def __repr__(self):
    return 'Account(x=%s, y=%s)' % (self.x, self.y)

Wondering how I'd go about doing the same in C++. Thanks!

Body:
Is this what you are looking for?

void BankSystem::showAccounts(){
    for (Account a: listOfAccounts){
        a.showAccount();
    }
}

void Account::showAccount(){
    cout << //all your printing information you want using your account
            //class variables
}


问:
Can not get the list of input checkboxes
I have a form where there are several choices of checkbox, but I can not retrieve the all selected list.
Here is my form in part:

```<code><form action="error" id="contact" method="post" name="contact">
<div class="form-step animated" id="form-step-1" style="display: block;">
    <h1>What are you or your loved one struggling with?</h1>
    <div class="info">
        <span class="txt">Check all that apply</span>
    </div>
    <ul class="services-list clearfix">
        <li>
            <div class="service">
                <label class="checkbox"><input name="problem" type="checkbox" value="Alcoholism"> <span class="icon"><i class="check"></i></span> <span class="label">Alcoholism</span></label>
            </div>
        </li>
        <li>
            <div class="service">
                <label class="checkbox"><input name="problem" type="checkbox" value="Drug Abuse"> <span class="icon"><i class="check"></i></span> <span class="label">Drug Abuse</span></label>
            </div>
        </li>
        <li>
            <div class="service">
                <label class="checkbox"><input name="problem" type="checkbox" value="Opiates"> <span class="icon"><i class="check"></i></span> <span class="label">Opiates</span></label>
            </div>
        </li>
        <li>
            <div class="service">
                <label class="checkbox"><input name="problem" type="checkbox" value="Eating Disorder"> <span class="icon"><i class="check"></i></span> <span class="label">Eating Disorder</span></label>
            </div>
        </li>
        <li>
            <div class="service">
                <label class="checkbox"><input name="problem" type="checkbox" value="Gambling"> <span class="icon"><i class="check"></i></span> <span class="label">Gambling</span></label>
            </div>
        </li>
        <li>
            <div class="service">
                <label class="checkbox"><input name="problem" type="checkbox" value="Mental Health"> <span class="icon"><i class="check"></i></span> <span class="label">Mental Health</span></label>
            </div>
        </li>
    </ul>
</div>
<input id="realSubmit" type="submit">
</code>```

Here is PHP code for form handler:

```<code>    <?php
$errors = '';
$myemail = 'example@example.com';//<-----Put Your email address here.
if( empty($_POST['problem'])  ||
    empty($_POST['patient_name'])  ||
    empty($_POST['patient_phone'])  ||
    empty($_POST['patient_birth'])  ||
    empty($_POST['patient_address'])  ||
    empty($_POST['insurance'])  ||
    empty($_POST['ins_digits'])  ||
    empty($_POST['ins_provider'])  ||
    empty($_POST['ins_provider_phone'])  ||
    empty($_POST['group_id'])  ||
    empty($_POST['member_id'])) {
    $errors .= "\n Error: All fields are required";
}
// $problem = $_POST['problem'];
$problems = implode("," , $_POST['problem']);
$patient_name = $_POST['patient_name'];
$patient_phone = $_POST['patient_phone'];
$patient_birth = $_POST['patient_birth'];
$patient_address = $_POST['patient_address'];
$insurance = $_POST['insurance'];
$policy_holder_name = $_POST['policy_holder_name'];
$policy_holder_phone = $_POST['policy_holder_phone'];
$policy_holder_birth = $_POST['policy_holder_birth'];
$policy_holder_address = $_POST['policy_holder_address'];
$ins_digits = $_POST['ins_digits'];
$ins_provider = $_POST['ins_provider'];
$ins_provider_phone = $_POST['ins_provider_phone'];
$group_id = $_POST['group_id'];
$member_id = $_POST['member_id'];

if (!preg_match( "/^[1-9][0-9]{0,15}$/", $patient_phone)) {
    $errors_patient_phone .= "\n Error: Invalid Phone Number of Patient";
}

if (!preg_match( "/^[1-9][0-9]{0,15}$/", $policy_holder_phone)) {
    $errors_policy_holder_phone .= "\n Error: Invalid Phone Number of Policy Holder";
}

if (!preg_match( "/^[1-9][0-9]{0,4}$/", $ins_digits)) {
    $errors_ins_digit .= "\n Error: Invalid Social Security Number";
}
if (!preg_match( "/^[1-9][0-9]{0,15}$/", $ins_provider_phone)) {
    $errors_ins_provider_phone .= "\n Error: Invalid Phone Number of Insurance Provider";
}

if( empty($errors_patient_phone) && empty($errors_patient_phone) && empty($errors_ins_digit) && empty($errors_ins_provider_phone))  {
    $to = $myemail;
    $email_subject = "Contact form submission from: $patient_name";
    $email_body = "You have received a new submission. ".
    "Here are the details:\n Patient's Name: $patient_name \n Patient's Phone: $patient_phone \n Patient's Address: $patient_address \n Patient's Problems: $problems \n Insurance: $insurance \n Policy Holder's Name: $policy_holder_name \n Policy Holder's Phone: $policy_holder_phone \n Policy Holder's Address: $policy_holder_address \n    Policy Holder's Social Security Number: $ins_digits \n Insurance Provider: $ins_provider \n Insurance Provider's Phone: $ins_provider_phone \n Group ID# $group_id \n Membar ID# $member_id";

    $headers[] = 'Content-Type: text/plain; charset=UTF-8';
    // $headers .= "Reply-To: $email_address";

    mail($to,$email_subject,$email_body,$headers);
    //redirect to the 'thank you' page
    header('Location: thank-you');
}
?>
</code>```

I can not get the list of the selected checkboxes.

Might be I am not getting an array from the selected input.
Any suggestion?

答:
Change the names of checkboxes from problem to problem[], then your $_POST['problem'] will be an array of your checkboxes values:

```<code><input name="problem[]" type="checkbox" value="Gambling">
</code>```

Body:
I have a form where there are several choices of checkbox, but I can not retrieve the all selected list.
Here is my form in part:

<form action="error" id="contact" method="post" name="contact">

What are you or your loved one struggling with?

        Check all that apply

                <input name="problem" type="checkbox" value="Alcoholism">  Alcoholism

                <input name="problem" type="checkbox" value="Drug Abuse">  Drug Abuse

                <input name="problem" type="checkbox" value="Opiates">  Opiates

                <input name="problem" type="checkbox" value="Eating Disorder">  Eating Disorder

                <input name="problem" type="checkbox" value="Gambling">  Gambling

                <input name="problem" type="checkbox" value="Mental Health">  Mental Health

<input id="realSubmit" type="submit">

Here is PHP code for form handler:

    <?php
$errors = '';
$myemail = 'example@example.com';//<-----Put Your email address here.
if( empty($_POST['problem'])  ||
    empty($_POST['patient_name'])  ||
    empty($_POST['patient_phone'])  ||
    empty($_POST['patient_birth'])  ||
    empty($_POST['patient_address'])  ||
    empty($_POST['insurance'])  ||
    empty($_POST['ins_digits'])  ||
    empty($_POST['ins_provider'])  ||
    empty($_POST['ins_provider_phone'])  ||
    empty($_POST['group_id'])  ||
    empty($_POST['member_id'])) {
    $errors .= "\n Error: All fields are required";
}
// $problem = $_POST['problem'];
$problems = implode("," , $_POST['problem']);
$patient_name = $_POST['patient_name'];
$patient_phone = $_POST['patient_phone'];
$patient_birth = $_POST['patient_birth'];
$patient_address = $_POST['patient_address'];
$insurance = $_POST['insurance'];
$policy_holder_name = $_POST['policy_holder_name'];
$policy_holder_phone = $_POST['policy_holder_phone'];
$policy_holder_birth = $_POST['policy_holder_birth'];
$policy_holder_address = $_POST['policy_holder_address'];
$ins_digits = $_POST['ins_digits'];
$ins_provider = $_POST['ins_provider'];
$ins_provider_phone = $_POST['ins_provider_phone'];
$group_id = $_POST['group_id'];
$member_id = $_POST['member_id'];

if (!preg_match( "/^[1-9][0-9]{0,15}$/", $patient_phone)) {
    $errors_patient_phone .= "\n Error: Invalid Phone Number of Patient";
}

if (!preg_match( "/^[1-9][0-9]{0,15}$/", $policy_holder_phone)) {
    $errors_policy_holder_phone .= "\n Error: Invalid Phone Number of Policy Holder";
}

if (!preg_match( "/^[1-9][0-9]{0,4}$/", $ins_digits)) {
    $errors_ins_digit .= "\n Error: Invalid Social Security Number";
}
if (!preg_match( "/^[1-9][0-9]{0,15}$/", $ins_provider_phone)) {
    $errors_ins_provider_phone .= "\n Error: Invalid Phone Number of Insurance Provider";
}

if( empty($errors_patient_phone) && empty($errors_patient_phone) && empty($errors_ins_digit) && empty($errors_ins_provider_phone))  {
    $to = $myemail;
    $email_subject = "Contact form submission from: $patient_name";
    $email_body = "You have received a new submission. ".
    "Here are the details:\n Patient's Name: $patient_name \n Patient's Phone: $patient_phone \n Patient's Address: $patient_address \n Patient's Problems: $problems \n Insurance: $insurance \n Policy Holder's Name: $policy_holder_name \n Policy Holder's Phone: $policy_holder_phone \n Policy Holder's Address: $policy_holder_address \n    Policy Holder's Social Security Number: $ins_digits \n Insurance Provider: $ins_provider \n Insurance Provider's Phone: $ins_provider_phone \n Group ID# $group_id \n Membar ID# $member_id";

    $headers[] = 'Content-Type: text/plain; charset=UTF-8';
    // $headers .= "Reply-To: $email_address";

    mail($to,$email_subject,$email_body,$headers);
    //redirect to the 'thank you' page
    header('Location: thank-you');
}
?>

I can not get the list of the selected checkboxes.

Might be I am not getting an array from the selected input.
Any suggestion?

Body:
Change the names of checkboxes from problem to problem[], then your $_POST['problem'] will be an array of your checkboxes values:

<input name="problem[]" type="checkbox" value="Gambling">


问:
How to convert date/time string to epoch?
Have the following string:

```<code>"date Thursday June 03 12:02:56 2017"
</code>```

What would be the proper way of convert it to epoch time?

答:
Another solution is to create a time.struct_time structure by parsing with time.strptime() and then pass it into calendar.timegm() to convert to epoch time.

```<code>import time
import calendar
timestr = "date Thursday June 03 12:02:56 2017"
calendar.timegm(time.strptime(timestr, "date %A %B %d %H:%M:%S %Y"))
# returns 1496491376
</code>```

Body:
Have the following string:

"date Thursday June 03 12:02:56 2017"

What would be the proper way of convert it to epoch time?

Body:
Another solution is to create a time.struct_time structure by parsing with time.strptime() and then pass it into calendar.timegm() to convert to epoch time.

import time
import calendar
timestr = "date Thursday June 03 12:02:56 2017"
calendar.timegm(time.strptime(timestr, "date %A %B %d %H:%M:%S %Y"))
# returns 1496491376


问:
Random position of nodes in hierarchical tree with alternate paths
I'm struggling with directed graph hierarchy tree visualization (distributed network in this case). Using graphviz: dot I have this tree:

```<code>digraph G {
    node[width=0.14, height=0.14];
    edge[weight=3, color = "0.000 0.000 0.0"];
    1 -> 2;
    1 -> 3;
    edge[weight=2, color = "0.000 0.000 0.175"];
    2 -> 4;
    2 -> 5;
    3 -> 6;
    3 -> 7;
    edge[weight=1, color = "0.000 0.000 0.825"];
    3 -> 4;
    3 -> 5;
    2 -> 6;
    2 -> 7;
}
</code>```

Resulting in:

You can see that the primary paths (edges with higher weights) are crossed. The goal is to have the preferred path nodes as close as possible. I can do it by changing the order of nodes randomly so the output looks like this:

However I don't want to think about the ordering algorithm as I want to automate this on hundreds of nodes.

From documentation:

The weight of an edge provides another way to keep edges straight. An edge’s weight suggests some measure of an edge’s importance; thus, the heavier the weight, the closer together its nodes should be. dot causes edges with heavier weights to be drawn shorter and straighter.

But this is not the case as the nodes are drawn in random order. What am I doing wrong?

答:
Could you live with a solution like this, which places invisible ranks and invisible edges to enforce the left-to-right ordering of your nodes?  While it adds some white space to the left of the diagram, at least it neatly solves the random-ordering issue within each rank, and lends itself to being automated.</p>

```<code>digraph G {
    node[width=0.14, height=0.14];

    {
    rankdir="TB";
    edge [style=invis];
    rank1 [style=invis];
    rank2 [style=invis];
    rank3 [style=invis];
    rank1 -> rank2 -> rank3 [style=invis];
    }

    edge[weight=3, color = "0.000 0.000 0.0"];
    1 -> 2;
    1 -> 3;
    edge[weight=2, color = "0.000 0.000 0.175"];
    2 -> 4;
    2 -> 5;
    3 -> 6;
    3 -> 7;
    {
    edge [style=invis];
    rank=same;
    rank2 -> 2 -> 3;
    }

    edge[weight=1, color = "0.000 0.000 0.825"];
    3 -> 4;
    3 -> 5;
    2 -> 6;
    2 -> 7;
    {
    rank=same;
    edge [style=invis];
    rank3 -> 4 -> 5 -> 6 -> 7 ;
    }
}
</code>```

Body:
I'm struggling with directed graph hierarchy tree visualization (distributed network in this case). Using graphviz: dot I have this tree:

digraph G {
    node[width=0.14, height=0.14];
    edge[weight=3, color = "0.000 0.000 0.0"];
    1 -> 2;
    1 -> 3;
    edge[weight=2, color = "0.000 0.000 0.175"];
    2 -> 4;
    2 -> 5;
    3 -> 6;
    3 -> 7;
    edge[weight=1, color = "0.000 0.000 0.825"];
    3 -> 4;
    3 -> 5;
    2 -> 6;
    2 -> 7;
}

Resulting in:

You can see that the primary paths (edges with higher weights) are crossed. The goal is to have the preferred path nodes as close as possible. I can do it by changing the order of nodes randomly so the output looks like this:

However I don't want to think about the ordering algorithm as I want to automate this on hundreds of nodes.

From documentation:

The weight of an edge provides another way to keep edges straight. An edge’s weight suggests some measure of an edge’s importance; thus, the heavier the weight, the closer together its nodes should be. dot causes edges with heavier weights to be drawn shorter and straighter.

But this is not the case as the nodes are drawn in random order. What am I doing wrong?

Body:
Could you live with a solution like this, which places invisible ranks and invisible edges to enforce the left-to-right ordering of your nodes?  While it adds some white space to the left of the diagram, at least it neatly solves the random-ordering issue within each rank, and lends itself to being automated.

digraph G {
    node[width=0.14, height=0.14];

    {
    rankdir="TB";
    edge [style=invis];
    rank1 [style=invis];
    rank2 [style=invis];
    rank3 [style=invis];
    rank1 -> rank2 -> rank3 [style=invis];
    }

    edge[weight=3, color = "0.000 0.000 0.0"];
    1 -> 2;
    1 -> 3;
    edge[weight=2, color = "0.000 0.000 0.175"];
    2 -> 4;
    2 -> 5;
    3 -> 6;
    3 -> 7;
    {
    edge [style=invis];
    rank=same;
    rank2 -> 2 -> 3;
    }

    edge[weight=1, color = "0.000 0.000 0.825"];
    3 -> 4;
    3 -> 5;
    2 -> 6;
    2 -> 7;
    {
    rank=same;
    edge [style=invis];
    rank3 -> 4 -> 5 -> 6 -> 7 ;
    }
}


问:
SQL A simple way to select items from the larger category
I have a table with items that can be grouped into two categories. How do I select items from the larger category? For example, if my table looks like

```<code>| ItemID | ItemProperty |
|  1     |     true     |
|  2     |     true     |
|  3     |    false     |
|  4     |    false     |
|  5     |    false     |
|  6     |     true     |
|  7     |     true     |
</code>```

then the result should look like

```<code>| ItemID |
|  1     |
|  2     |
|  6     |
|  7     |
</code>```

This feels like something very simple, and yet I haven't been able to find the answer.

答:
Select itemId
From table_name
Where itemProperty = 'true'</p>

Body:
I have a table with items that can be grouped into two categories. How do I select items from the larger category? For example, if my table looks like

| ItemID | ItemProperty |
|  1     |     true     |
|  2     |     true     |
|  3     |    false     |
|  4     |    false     |
|  5     |    false     |
|  6     |     true     |
|  7     |     true     |

then the result should look like

| ItemID |
|  1     |
|  2     |
|  6     |
|  7     |

This feels like something very simple, and yet I haven't been able to find the answer.


问:
use nginx as a front door for your application in production?
Im tying some loose ends on application deployment for production and my question goes like this

Should you, in production, always have an nginx (or any other web server) to front for your web applications (node, php, python, ruby)?

I guess it makes sense to offload ssl, keepalive connections, error page serving and other http server stuff (caching maybe?) but is there any argument in favor of just having your de facto application server handling everything?  is security a concern in this realm?

Thanks in advance,

答:
To reply this question i would like to invoke the KISS principle as in keep it simple....you know the rest,

After doing a bit of research among fellow devs and ops guys i figured out that unless you actually have a purpose (mitigating a specific security flaw, serving static files, revProxy requests to balance the load among several app servers) having a web server as the front of your web application can do more harm than good, as it is a separate component to administrate and can potentially introduce security issues while increasing the overhead,

Different server-side languages have different specific solutions for their needs, java has tomcat jboss and the old glassfish, and ruby has unicorn + raptor, so it is a matter of checking each apps' needs in production.