问:
to pass data around using event handling
Anyone can detail the pros and cons to pass data from one class to another using event mechanism? When is the best time to use event to pass data?</p>

答:
Let's take an example. You have a system where 20 people are subscribed to a weather station for changes in weather. Do you want the weather station to keep track of all the people and services that are subscribed?

In my opinion the weather station should not know anything about the people or services that are waiting for weather changes. The weather station should just dispatch an event, and whoever is listening to it will get notified :-)

So the point is, you use events to notify observers about an action or state change that occurred in the object. Observers can be difference type of objects since you don't have to know anything about them. If someone listens to the object, then he takes care of it.

If it was one to one relation and the object waiting for something to happen is always of the same type, then you wouldn't really need an event for that case.

Events are also great to decouple systems, like seen in my example above with the weather station. The weather station can run on its own without knowing about the services or users that are listening to it.


来源: stackexchange

问:
R purrr function: Sensitivity with multiple parameters
I have been working on this problem and can't seem to figure it out.

I have a dataset show below in which I want to run a cashflow sensitivity to price.  The dataset will have appended rows, but the problem I am running into is using the different prices with the unique labor cost and matching them to their unique stations.

```<code>a <- data.frame(Name = "station1", units_sold = seq(2000, 3000, by = 2))
b <- data.frame(Name = "station2", units_sold = seq(1000, 2000, by = 2))

monthly_sales <- rbind(a, b)

price_1 <- c(2,3,4,5,6) #price for station_1
price_2 <- c(3,4,5,6,7) #price for station_2

labor1 <- c(1000) #labor for station_1
labor2 <- c(2000) #labor for station_2
</code>```

I am using the code below and I am not able to apply price_1 and labor_1 to station_1, and then price_2 and labor_2 to station_2 for my sensitivity.

How do I setup my cf_model function or the map function to match the unique labor and price parameters?

Any help would be greatly appreciated!

```<code>cf_model <- function(x)
{
  data.frame(Scenario = (monthly_sales$units_sold * price_1[x]))
}
sensitivity_model <- data.frame(map(1:5, cf_model))
</code>```

答:
I believe what you are trying to do is to use map with 2 parameters, which would be map2.

In this case your function cf_model would be a function which takes in two parameters, being the parameter for price_1 and price_2; you should never really need to index it.

In this example it would be:

```<code>cf_model <- function(price_1, price_2){
  data.frame(Scenario = (a$units_sold*price_1 + b$units_sold*price_2))
}
sensitivity_model <- data.frame(map2(price_1, price_2, cf_model))

head(sensitivity_model)
</code>```

Notice I did not use your table monthly_sales. If I was to use it it would be:

```<code>monthly_sales <- data.frame(station1=a$units_sold,
                            station2=b$units_sold)
sensitivity_model <- data.frame(map2(price_1, price_2,
                       ~ list(Sensitivity=.x*monthly_sales$station1 + .y*monthly_sales$station2)))
</code>```

In both cases it will have the same output:

```<code>> head(sensitivity_model)
  Scenario Scenario.1 Scenario.2 Scenario.3 Scenario.4
1     7000      10000      13000      16000      19000
2     7010      10014      13018      16022      19026
3     7020      10028      13036      16044      19052
4     7030      10042      13054      16066      19078
5     7040      10056      13072      16088      19104
6     7050      10070      13090      16110      19130
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been working on this problem and can't seem to figure it out.

I have a dataset show below in which I want to run a cashflow sensitivity to price.  The dataset will have appended rows, but the problem I am running into is using the different prices with the unique labor cost and matching them to their unique stations.

a <- data.frame(Name = "station1", units_sold = seq(2000, 3000, by = 2))
b <- data.frame(Name = "station2", units_sold = seq(1000, 2000, by = 2))

monthly_sales <- rbind(a, b)

price_1 <- c(2,3,4,5,6) #price for station_1
price_2 <- c(3,4,5,6,7) #price for station_2

labor1 <- c(1000) #labor for station_1
labor2 <- c(2000) #labor for station_2

I am using the code below and I am not able to apply price_1 and labor_1 to station_1, and then price_2 and labor_2 to station_2 for my sensitivity.

How do I setup my cf_model function or the map function to match the unique labor and price parameters?

Any help would be greatly appreciated!

cf_model <- function(x)
{
  data.frame(Scenario = (monthly_sales$units_sold * price_1[x]))
}
sensitivity_model <- data.frame(map(1:5, cf_model))

Body:
I believe what you are trying to do is to use map with 2 parameters, which would be map2.

In this case your function cf_model would be a function which takes in two parameters, being the parameter for price_1 and price_2; you should never really need to index it.

In this example it would be:

cf_model <- function(price_1, price_2){
  data.frame(Scenario = (a$units_sold*price_1 + b$units_sold*price_2))
}
sensitivity_model <- data.frame(map2(price_1, price_2, cf_model))

head(sensitivity_model)

Notice I did not use your table monthly_sales. If I was to use it it would be:

monthly_sales <- data.frame(station1=a$units_sold,
                            station2=b$units_sold)
sensitivity_model <- data.frame(map2(price_1, price_2,
                       ~ list(Sensitivity=.x*monthly_sales$station1 + .y*monthly_sales$station2)))

In both cases it will have the same output:

> head(sensitivity_model)
  Scenario Scenario.1 Scenario.2 Scenario.3 Scenario.4
1     7000      10000      13000      16000      19000
2     7010      10014      13018      16022      19026
3     7020      10028      13036      16044      19052
4     7030      10042      13054      16066      19078
5     7040      10056      13072      16088      19104
6     7050      10070      13090      16110      19130


问:
RecyclerView Item Getting Clicked When Click on FloatingActionButton in Android
I have a FloatingActionButton over a RecyclerView in my app. The Button is showing ok, but when I click on it, the RecyclerView item below it is getting the click event, instead of the button. If I set the RecyclerView to show over the FloatingActionButton, the Button works as intended.

How to solve this, and make the Button to get the click event?

Thank you.

答:
It can only happen if you don't set  onClick Listener on FloatingActionButton. So just set onClick Listener on FloatingActionButton Your problem will be solved....

```<code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Your code to do something if you have
        }
});
</code>```

If have on action to do just implement a empty listener like above ..

Body:
It can only happen if you don't set  onClick Listener on FloatingActionButton. So just set onClick Listener on FloatingActionButton Your problem will be solved....

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Your code to do something if you have
        }
});

If have on action to do just implement a empty listener like above ..


问:
Android emulator shows nothing but blank screen
I am a complete nOOb to Android programming and trying my hands at it for the first time by going through the tutorials. The problem is that I have created multiple emulators using android 4.4.2 API and none of them show anything but blank screen..I tried an AVD with Google API 19..thats not working either..Can anyone please guide me figuring out what's wrong with it..Thanks in advance</p>

答:
I just started with android development recently and I had the problem with emulator showing black screen even when I was using software GPU acceleration.
On executing the following command in tools folder in Sdk folder of Android

```<code> $./emulator -accel-check
</code>```

The output which is given below showed that KVM was installed correctly and was usable.

```<code>    accel:
    0
    KVM (version 12) is installed and usable.
    accel
</code>```

So I installed the following packages

```<code>$ sudo apt-get install qemu-kvm libvirt-bin ubuntu-vm-builder bridge-utils ia32-libs-multiarch
</code>```

As I use Manjaro I didn't find all the packages in software repo. I was able to find only the following packages

qemu

libvirt

bridge-utils

Installing these helped me run AVD in both software and hardware GPU accleration.

Source: - https://developer.android.com/studio/run/emulator-acceleration.html

Body:
I just started with android development recently and I had the problem with emulator showing black screen even when I was using software GPU acceleration.
On executing the following command in tools folder in Sdk folder of Android

 $./emulator -accel-check

The output which is given below showed that KVM was installed correctly and was usable.

    accel:
    0
    KVM (version 12) is installed and usable.
    accel

So I installed the following packages

$ sudo apt-get install qemu-kvm libvirt-bin ubuntu-vm-builder bridge-utils ia32-libs-multiarch

As I use Manjaro I didn't find all the packages in software repo. I was able to find only the following packages

qemu

libvirt

bridge-utils

Installing these helped me run AVD in both software and hardware GPU accleration.

Source: - https://developer.android.com/studio/run/emulator-acceleration.html


问:
How can I include the CSS or JS files from a ZIP folder in my HTML page?
I have a zipped folder of all the CSS and JS files for my desktop Electron application. I am trying to refer a CSS file from this zip using the below syntax which isn't working:

```<code><link rel="stylesheet" type="text/css"
  href="../css/resources.zip/assets/styles/style.min.css">
</code>```

Is this even possible or am I making some syntax errors?

答: I don't think it's possible without extensions. A zipped folder is rather a file than a directory, a folder with items not accessible by normal means.</p>

Body:
I have a zipped folder of all the CSS and JS files for my desktop Electron application. I am trying to refer a CSS file from this zip using the below syntax which isn't working:

<link rel="stylesheet" type="text/css"
  href="../css/resources.zip/assets/styles/style.min.css">

Is this even possible or am I making some syntax errors?


问:
Sidebar menu and hover submenus with CSS
I'm looking for improve my sidebar menu in my Django application. I would like to display submenus with a hover effect when users put their mouses on each menu titles.

This is my script :

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 170px;
  bottom: 0;
  height: 80%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<div class="area"></div>
<nav class="main-menu">
  <ul>
    <li>

        <i class="fa fa-home fa-2x"></i>
        <span class="nav-text">
           Accueil
        </span>

    </li>
    <li class="has-subnav">
      <i class="fa fa-file-text-o fa-2x"></i>
        <span class="nav-text">Fiches Identifications</span>
      <ul>
        <li>Accueil</li>
        <li>Individus</li>
        <li>Sociétés</li>
      </ul>
    </li>
    <li>

        <i class="fa fa-bar-chart-o fa-2x"></i>
        <span class="nav-text">
           Statistiques
        </span>

    </li>
    <li>

        <i class="fa fa-folder fa-2x"></i>
        <span class="nav-text">
           DatasystemsDOC
        </span>

    </li>
    <li>

        <i class="fa fa-cog fa-spin fa-2x fa-fw"></i>
        <span class="nav-text">
           Configurations
        </span>

    </li>
    <li>

        <i class="fa fa-life-ring fa-2x"></i>
        <span class="nav-text">
          Aide et Support
        </span>

    </li>
    <li>

        <i class="fa fa-info fa-2x"></i>
        <span class="nav-text">
           Documentation
        </span>

    </li>
  </ul>

  <ul class="logout">
    <li>

        <i class="fa fa-power-off fa-2x"></i>
        <span class="nav-text">
           Logout
        </span>

    </li>
  </ul>
</nav></code>```

My preview is available there : see preview

I would like to display submenus Accueil Individus Sociétés when I put my mouse on Fiches Identifications with a vertical hover effect.

Do you have any idea to do that ?

答:
This will solve your problem.

```<code>li.has-subnav ul {
    display: none;
}

li.has-subnav:hover ul {
    display: block;
}
</code>```

What I am doing here is that by default the sub-menu is hidden. But on hover, the submenu is shown.

        li.has-subnav ul {
            display: none;
        }

        li.has-subnav:hover ul {
            display: block;
        }

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 170px;
  bottom: 0;
  height: 80%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="main-menu">
  <ul>
    <li>

        <i class="fa fa-home fa-2x"></i>
        <span class="nav-text">
           Accueil
        </span>

    </li>
    <li class="has-subnav">
      <i class="fa fa-file-text-o fa-2x"></i>
        <span class="nav-text">Fiches Identifications</span>
      <ul>
        <li>Accueil</li>
        <li>Individus</li>
        <li>Sociétés</li>
      </ul>
    </li>
    <li>

        <i class="fa fa-bar-chart-o fa-2x"></i>
        <span class="nav-text">
           Statistiques
        </span>

    </li>
    <li>

        <i class="fa fa-folder fa-2x"></i>
        <span class="nav-text">
           DatasystemsDOC
        </span>

    </li>
    <li>

        <i class="fa fa-cog fa-spin fa-2x fa-fw"></i>
        <span class="nav-text">
           Configurations
        </span>

    </li>
    <li>

        <i class="fa fa-life-ring fa-2x"></i>
        <span class="nav-text">
          Aide et Support
        </span>

    </li>
    <li>

        <i class="fa fa-info fa-2x"></i>
        <span class="nav-text">
           Documentation
        </span>

    </li>
  </ul>

  <ul class="logout">
    <li>

        <i class="fa fa-power-off fa-2x"></i>
        <span class="nav-text">
           Logout
        </span>

    </li>
  </ul>
</nav></code>```

Body:
I'm looking for improve my sidebar menu in my Django application. I would like to display submenus with a hover effect when users put their mouses on each menu titles.

This is my script :

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 170px;
  bottom: 0;
  height: 80%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

           Accueil

        Fiches Identifications

Accueil

Individus

Sociétés

           Statistiques

           DatasystemsDOC

           Configurations

          Aide et Support

           Documentation

           Logout

My preview is available there : see preview

I would like to display submenus Accueil Individus Sociétés when I put my mouse on Fiches Identifications with a vertical hover effect.

Do you have any idea to do that ?

Body:
This will solve your problem.

li.has-subnav ul {
    display: none;
}

li.has-subnav:hover ul {
    display: block;
}

What I am doing here is that by default the sub-menu is hidden. But on hover, the submenu is shown.

        li.has-subnav ul {
            display: none;
        }

        li.has-subnav:hover ul {
            display: block;
        }

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 170px;
  bottom: 0;
  height: 80%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}

<nav class="main-menu">
  <ul>
    <li>
      <a href="{% url " accueil " %}">
        <i class="fa fa-home fa-2x"></i>
        <span class="nav-text">
           Accueil
        </span>
      </a>
    </li>
    <li class="has-subnav">
      <a href="#"><i class="fa fa-file-text-o fa-2x"></i>
        <span class="nav-text">Fiches Identifications</span></a>
      <ul>
        <li><a href="#">Accueil</a></li>
        <li><a href="#">Individus</a></li>
        <li><a href="#">Sociétés</a></li>
      </ul>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-bar-chart-o fa-2x"></i>
        <span class="nav-text">
           Statistiques
        </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-folder fa-2x"></i>
        <span class="nav-text">
           DatasystemsDOC
        </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-cog fa-spin fa-2x fa-fw"></i>
        <span class="nav-text">
           Configurations
        </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-life-ring fa-2x"></i>
        <span class="nav-text">
          Aide et Support
        </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-info fa-2x"></i>
        <span class="nav-text">
           Documentation
        </span>
      </a>
    </li>
  </ul>

  <ul class="logout">
    <li>
      <a href="#">
        <i class="fa fa-power-off fa-2x"></i>
        <span class="nav-text">
           Logout
        </span>
      </a>
    </li>
  </ul>
</nav>


问:
why did not got any error while validating my xml?
My Xml is not getting correctly validated against the XSD.
I expect the browser to through atleast some kind of generic error messages when i open xml file

My Xml file is below
note.Xml

```<code>    <?xml version="1.0"?>
    <note
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:SchemaLocation="note.xsd">
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
      </note>
</code>```

My Xsd file is below
note.xsd

```<code>      <?xml version="1.0"?>
      <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       targetNamespace="http://www.w3schools.com"
       xmlns="http://www.w3schools.com"
         elementFormDefault="qualified"><xs:element name="note">
        <xs:complexType>
         <xs:sequence>
         <xs:element name="from" type="xs:string"/>
         <xs:element name="heading" type="xs:string"/>
         <xs:element name="body" type="xs:string"/>
         </xs:sequence>
        <xs:attribute name="to" type="xs:string" use="required"/>
         </xs:complexType>
          </xs:element></xs:schema>
</code>```

Both the note.xml and note.xsd files are in the same folder.
Can somebody guide why i am not getting any error? So Can anyone help me how to validate my xml file with xsd? Thank you,

答:
Three problems:

xsi:schemaLocation attribute value
should be a white-space separate
sequence of namespace URI and schema
document URI, like xsi:schemaLocation="http://www.w3schools.com note.xsd"

You wrote:

I expect the browser to through
  atleast some kind of generic error

It's not clear that you are actually
using some validation tool. No
browser validates XML Schema when
you open an XML document.

Your schema targets the
http://www.w3schools.com namespace
URI, but your document is under null
(or empty) namespace URI. This will
end up in validation error, even if
you use the
xsi:noNamespaceSchemaLocation
instead of the xsi:schemaLocation
attribute. Maybe you want to add a
default namespace declaration in
your input source like
xmlns="http://www.w3schools.com"...

ContentLicense: CC BY-SA 2.5

Body:
My Xml is not getting correctly validated against the XSD.
I expect the browser to through atleast some kind of generic error messages when i open xml file

My Xml file is below
note.Xml

    <?xml version="1.0"?>
    <note
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:SchemaLocation="note.xsd">
      <from>Jani</from>
      <heading>Reminder</heading>
      Don't forget me this weekend!
      </note>

My Xsd file is below
note.xsd

      <?xml version="1.0"?>
      <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       targetNamespace="http://www.w3schools.com"
       xmlns="http://www.w3schools.com"
         elementFormDefault="qualified"><xs:element name="note">
        <xs:complexType>
         <xs:sequence>
         <xs:element name="from" type="xs:string"/>
         <xs:element name="heading" type="xs:string"/>
         <xs:element name="body" type="xs:string"/>
         </xs:sequence>
        <xs:attribute name="to" type="xs:string" use="required"/>
         </xs:complexType>
          </xs:element></xs:schema>

Both the note.xml and note.xsd files are in the same folder.
Can somebody guide why i am not getting any error? So Can anyone help me how to validate my xml file with xsd? Thank you,


问:
How can I find out which PHP script a process is running in Linux?
Running Linux, Apache, PHP 5.3 with FastCGI Handler.

Is it possible to find out the script that is being executed for a linux process? I've been searching on google and haven't been able to find anything useful.

答:
You can use pgrep for that, e.g.

```<code>pgrep -l php
</code>```

or:

```<code>pgrep php && echo PHP script is running || echo PHP script is NOT running
</code>```

Body:
You can use pgrep for that, e.g.

pgrep -l php

or:

pgrep php && echo PHP script is running || echo PHP script is NOT running


问:
If condition wrongly working
The Following PHP if condition statement is processing wrong and is not working.

File $fname has text values: "990,1000" with a comma in between:

```<code>$myfile = fopen($fname, "r") or die("<script
type='text/javascript'>window.location.href =
'http://www.autorekrooter.com/activation.html';</script>");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?
echo "<br>myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " .
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "<script>alert('You can't proceed further');</script>";
//echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
exit();
}
else{
echo "<script type='text/javascript'>window.location.href =
'gui.php';</script>";
echo "You can proceed";
exit();
}
</code>```

When I run the above in a php file the if statement always takes value of myArray[0] >= myArray[1] as true and show the reigster.html whereas in the $fname file it is 990,1000 myArray[0]=990 and myArray[1]=1000 so myArray[0] should not be greater than myArray[1] and the else statement should run but the opposite is happening.

Any suggestions as to why this is not working?

Many Thanks in advance for your answers.

答:
You can use intval to get the integer value only.

Try this

```<code>if (intval($myArray[0])>=intval($myArray[1])){
     echo "<script>alert('You can't proceed further');</script>";
//echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
exit();
}
else{
echo "<script type='text/javascript'>window.location.href =
'gui.php';</script>";
echo "You can proceed";
exit();
}
</code>```

I thing it will work for you.

Title: If condition wrongly working

Body:
The Following PHP if condition statement is processing wrong and is not working.

File $fname has text values: "990,1000" with a comma in between:

$myfile = fopen($fname, "r") or die("");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?
echo "
myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " .
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "";
//echo "";
exit();
}
else{
echo "";
echo "You can proceed";
exit();
}

When I run the above in a php file the if statement always takes value of myArray[0] >= myArray[1] as true and show the reigster.html whereas in the $fname file it is 990,1000 myArray[0]=990 and myArray[1]=1000 so myArray[0] should not be greater than myArray[1] and the else statement should run but the opposite is happening.

Any suggestions as to why this is not working?

Many Thanks in advance for your answers.

Body:
You can use intval to get the integer value only.

Try this

if (intval($myArray[0])>=intval($myArray[1])){
     echo "<script>alert('You can't proceed further');</script>";
//echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
exit();
}
else{
echo "<script type='text/javascript'>window.location.href =
'gui.php';</script>";
echo "You can proceed";
exit();
}

I thing it will work for you.


问:
How to make angular2 custom validators to run after we get the value
If I pass hard coded values in offerCheck validator it is working fine. But if I get values from api, null values is getting passed in paramets. Form is getting executed before we get the values from service. Please help me to make validate check after getting values from api.

this.newOffer = "aaa";
this.oldOffer = "aaa";

constructor(fb: FormBuilder) {
    this.formGroup = fb.group({
      'offer': [null, Validators.compose([Validators.required, this.offerCheck(newOfer, oldOffer)])],
    })

    offerCheck(new, old) {
      return (control: FormControl) => {
        if (new == old) {
          return true;
        }
      }
    }```

答:
What you want is probably the AsyncValidatorFn, here's a very simple example of how to create one:

```<code>export const OfferCheck: AsyncValidatorFn = (control: AbstractControl): Observable<boolean> => {

 if (new == old) {
   return Observable.of(this.http.get('/some-endpoint').first().map(res => res.data));
 }
};
</code>```

You don't provide enough information so this is just a guess on how you'd want it to be. But it should point you in the right decision.

An alternative method would be to use setValidators of the control(s) after you've fetched the data:

```<code>this.formGroup.get('offer').setValidators([Validators.required, this.offerCheck(newOfer, oldOffer)]);
</code>```

I hope this helps.

Body:
What you want is probably the AsyncValidatorFn, here's a very simple example of how to create one:

export const OfferCheck: AsyncValidatorFn = (control: AbstractControl): Observable<boolean> => {

 if (new == old) {
   return Observable.of(this.http.get('/some-endpoint').first().map(res => res.data));
 }
};

You don't provide enough information so this is just a guess on how you'd want it to be. But it should point you in the right decision.

An alternative method would be to use setValidators of the control(s) after you've fetched the data:

this.formGroup.get('offer').setValidators([Validators.required, this.offerCheck(newOfer, oldOffer)]);

I hope this helps.


问:
Data Not displaying while passing from controller
In asp.net MVC getting the model value but while passing to view nothing displayed.

Controller

```<code>  public ActionResult Index(plan plan1)
        {
            var myCharge = new StripeChargeCreateOptions();

            string apiKey = "";
            var stripeClient = new StripeClient(apiKey);
            var planService = new StripePlanService(apiKey);
            StripePlan response = planService.Get("1234");
            plan1.Amount = (response.Amount).ToString();

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

view

```<code><div>
    @Html.TextBoxFor(m => m.Amount)

</div>
</code>```

How to display the Amount value inside textbox

答:
Hope your View is strongly bound with the Model class (the instance is plan1). So, You need to specify your model in your return statement

```<code>return View(plan1);
</code>```

Body:
In asp.net MVC getting the model value but while passing to view nothing displayed.

Controller

  public ActionResult Index(plan plan1)
        {
            var myCharge = new StripeChargeCreateOptions();

            string apiKey = "";
            var stripeClient = new StripeClient(apiKey);
            var planService = new StripePlanService(apiKey);
            StripePlan response = planService.Get("1234");
            plan1.Amount = (response.Amount).ToString();

            return View();
        }

view

    @Html.TextBoxFor(m => m.Amount)

How to display the Amount value inside textbox

Body:
Hope your View is strongly bound with the Model class (the instance is plan1). So, You need to specify your model in your return statement

return View(plan1);

ContentLicense: CC BY-SA 4.0


问:
i can't hold old entries
```<code>#include <stdio.h>
#include <stdlib.h>

void push(int p)
{
    static int i=0;
    int b;
    int *ptr =(int *)malloc((10)*sizeof(int));
    ptr[i]=p;
    for(b=0;b<=i;b++){
    printf("%d",ptr[b]);
    printf("\n");
    }
    i++;
}
int main()
{
    int a;
    while(1)
    {
    scanf("%d",&a);
    push(a);
    }
}
</code>```

When i put new values , function is not hold old entries.I wait for your helps.

答:
Each time you call push(), new memory is allocated to hold 10 integers. You are not doing anything to save the pointer to that memory.

This is called a memory leak, because you're allocating memory but you never free it. If you call push() enough times, you could run out of memory.

Title: i can't hold old entries

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

void push(int p)
{
    static int i=0;
    int b;
    int *ptr =(int *)malloc((10)*sizeof(int));
    ptr[i]=p;
    for(b=0;b<=i;b++){
    printf("%d",ptr[b]);
    printf("\n");
    }
    i++;
}
int main()
{
    int a;
    while(1)
    {
    scanf("%d",&a);
    push(a);
    }
}

When i put new values , function is not hold old entries.I wait for your helps.


问:
Discard curl downloads below a minimum file size
I regularly need to iterate through some image downloads via curl and want to discard those downloads that are below a certain file size, because they obviously don't exist, i. e. the returned "image" is a 404 page. curl has a --max-filesize option, but not one for minimum file sizes.

I was thinking of something where I would pass the URL image location and the minimum file size to the script curlmin, such as

curlmin url minfilesize

I believe that since I'm using sequences of alphanumeric series using [ ] to iterate through days, I need to be able to delete those files below a certain file size "on the fly". My attempt below is anything but complete, because I'm stuck on how to reference the "current" file in the 'if' statement and how to actually delete the file. But it might as well be that my one liner wouldn't work in first place either.

```<code>#!/bin/bash
curl -O $1 | if [ $(wc -c <"$1") -le $2 ]; then delete_file_here; fi
                            ^^                  ^^^^^^^^^^^^^^^^
</code>```

Any idea? Thanks.

答:
Using wget along with curly brace expansion [ Check here ] to solve the problem

```<code>wget http://www.bom.gov.au/gms/IDE00135.201707{031630..031637}.jpg
</code>```

Body:
I regularly need to iterate through some image downloads via curl and want to discard those downloads that are below a certain file size, because they obviously don't exist, i. e. the returned "image" is a 404 page. curl has a --max-filesize option, but not one for minimum file sizes.

I was thinking of something where I would pass the URL image location and the minimum file size to the script curlmin, such as

curlmin url minfilesize

I believe that since I'm using sequences of alphanumeric series using [ ] to iterate through days, I need to be able to delete those files below a certain file size "on the fly". My attempt below is anything but complete, because I'm stuck on how to reference the "current" file in the 'if' statement and how to actually delete the file. But it might as well be that my one liner wouldn't work in first place either.

#!/bin/bash
curl -O $1 | if [ $(wc -c <"$1") -le $2 ]; then delete_file_here; fi
                            ^^                  ^^^^^^^^^^^^^^^^

Any idea? Thanks.

Body:
Using wget along with curly brace expansion [ Check here ] to solve the problem

wget http://www.bom.gov.au/gms/IDE00135.201707{031630..031637}.jpg


问:
Join path that overlaps
In java, I have a string that looks like :

```<code>"c:\abc\def\ghi"
</code>```

and another that is

```<code>"def\ghi\jkl.txt"
</code>```

How can I do the intersection of both to have

```<code>"c:\abc\def\ghi\jkl.txt"
</code>```

edit :

The rules are :

replace the maximum of the end of the first string with the maximum of the beginning of the second string.

For example with

b\a\n\a\n\a and a\n\a\n\a\s the result should be b\a\n\a\n\a\s

with "c:\abc\def\ghi" joined to "def\gji\jkl.txt", we have "c:\abc\def\ghi\def\gji\jkl.txt"

答:
I would simply look at the first string and check if it ends with the largest possible beginning of the second string. To be a little bit faster I check on every existing backslash:</p>

```<code>public static String join(String begin, String end) {
    for (int i = end.lastIndexOf("\\"); i >= 0; i = end.lastIndexOf("\\", i - 1)) {
        if (begin.endsWith(end.substring(0, i)) && begin.charAt(begin.length() - (i+1)) == '\\') {
            return begin + end.substring(i);
        }
    }
    return "strings dont contain same folder sequence";
}
</code>```

Title: Join path that overlaps

Body:
In java, I have a string that looks like :

"c:\abc\def\ghi"

and another that is

"def\ghi\jkl.txt"

How can I do the intersection of both to have

"c:\abc\def\ghi\jkl.txt"

edit :

The rules are :

replace the maximum of the end of the first string with the maximum of the beginning of the second string.

For example with

b\a\n\a\n\a and a\n\a\n\a\s the result should be b\a\n\a\n\a\s

with "c:\abc\def\ghi" joined to "def\gji\jkl.txt", we have "c:\abc\def\ghi\def\gji\jkl.txt"

Body:
I would simply look at the first string and check if it ends with the largest possible beginning of the second string. To be a little bit faster I check on every existing backslash:

public static String join(String begin, String end) {
    for (int i = end.lastIndexOf("\\"); i >= 0; i = end.lastIndexOf("\\", i - 1)) {
        if (begin.endsWith(end.substring(0, i)) && begin.charAt(begin.length() - (i+1)) == '\\') {
            return begin + end.substring(i);
        }
    }
    return "strings dont contain same folder sequence";
}


问:
how to get access token for fb page for 2 months or more
Hi I had an access token for an facebook page.
I can get the access token for fb account but fb page it is getting only for one hour
i had 7 fb pages in my account. So is there any process to get access token for 2 months or more </p>

答: The docs give instructions for swapping a short-lived token for a long-lived token: https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension</p>


问:
Apache Reverse Proxy and localhost - "Mixed content, the content must be served over HTTPS"
I have created a reverse proxy for my node server that runs on localhost, so that it can be served over HTTPS.

The forwarding works grate, however when the app tries to make requests I get:

Mixed Content: The page at 'https://foo.com/' was loaded over HTTPS,
  but requested an insecure XMLHttpRequest endpoint
  'http://localhost:8888/graphql?query=%7Bnotifications(userid)%7Bid%2C…
  This request has been blocked; the content must be served over HTTPS.

Vhost config:

```<code><VirtualHost *:443>
   ServerName www.foo.com
   ServerAlias foo.com
   DocumentRoot /var/www/foo/
   ErrorLog /var/www/foo/error.log
   CustomLog /var/www/foo/requests.log combined

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
   SSLCertificateFile "/etc/letsencrypt/live/foo.com/cert.pem"
   SSLCertificateKeyFile "/etc/letsencrypt/live/foo.com/privkey.pem"

   ProxyPreserveHost On
   ProxyRequests Off
   ProxyPass / http://localhost:8888/
   ProxyPassReverse / http://localhost:8888/

</VirtualHost>
</code>```

What is missing from my setup?

答:
You need to add a SSL certificate to your node.js app. Enabling it on apache won't help since the apache is forwarding the requests to your node.js app on port 8888 (which communicates on plain http and not https). That's why you get the mixed content error. The initial request is on https on apache then forwarded to http to node.js

Steps to configure node.js app with a SSL certificate (you can use a self-signed certificate or a commercial one).

First you have to use ssl-root-cas available via npm. The configure it as follows:

```<code>'use strict';

var https = require('https')
  , cas
  ;

// This will add the well-known CAs
// to `https.globalAgent.options.ca`
require('ssl-root-cas').inject();

cas = https.globalAgent.options.ca;

cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '01-ssl-intermediary-a.pem')));
cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '02-ssl-intermediary-b.pem')));
cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '03-ssl-site.pem')));
</code>```

Try and see if that works!

Body:
I have created a reverse proxy for my node server that runs on localhost, so that it can be served over HTTPS.

The forwarding works grate, however when the app tries to make requests I get:

Mixed Content: The page at 'https://foo.com/' was loaded over HTTPS,
  but requested an insecure XMLHttpRequest endpoint
  'http://localhost:8888/graphql?query=%7Bnotifications(userid)%7Bid%2C…
  This request has been blocked; the content must be served over HTTPS.

Vhost config:

<VirtualHost *:443>
   ServerName www.foo.com
   ServerAlias foo.com
   DocumentRoot /var/www/foo/
   ErrorLog /var/www/foo/error.log
   CustomLog /var/www/foo/requests.log combined

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
   SSLCertificateFile "/etc/letsencrypt/live/foo.com/cert.pem"
   SSLCertificateKeyFile "/etc/letsencrypt/live/foo.com/privkey.pem"

   ProxyPreserveHost On
   ProxyRequests Off
   ProxyPass / http://localhost:8888/
   ProxyPassReverse / http://localhost:8888/

</VirtualHost>

What is missing from my setup?

Body:
You need to add a SSL certificate to your node.js app. Enabling it on apache won't help since the apache is forwarding the requests to your node.js app on port 8888 (which communicates on plain http and not https). That's why you get the mixed content error. The initial request is on https on apache then forwarded to http to node.js

Steps to configure node.js app with a SSL certificate (you can use a self-signed certificate or a commercial one).

First you have to use ssl-root-cas available via npm. The configure it as follows:

'use strict';

var https = require('https')
  , cas
  ;

// This will add the well-known CAs
// to `https.globalAgent.options.ca`
require('ssl-root-cas').inject();

cas = https.globalAgent.options.ca;

cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '01-ssl-intermediary-a.pem')));
cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '02-ssl-intermediary-b.pem')));
cas.push(fs.readFileSync(path.join(__dirname, 'ssl', '03-ssl-site.pem')));

Try and see if that works!


答:
You must allocate only once. At the moment you are creating a memory leak each time you call the function push. Nobody refers to the memory once you leave the function. You can make it static to keep the information. Be aware that you are also limiting the number of values that you can hold at 10.

```<code>void push(int p)
{
    static int i=0;
    static int *ptr =(int *)malloc((10)*sizeof(int)); // To keep the values
    int b;
    ptr[i]=p;
    for(b=0;b<=i;b++){
        printf("%d",ptr[b]);
        printf("\n");
    }
    i++;
    if( i >= 10 ) i = 0; // To make sure there is no overflow
}
</code>```

Better yet you could pass in the location where you want to save the information.

```<code>void push(int p, int *ptr)
{
    static int i=0;
    int b;
    ptr[i] = b;
    for(b=0;b<=i;b++){
       printf("%d",ptr[b]);
       printf("\n");
    }
    i++;
    if( i >= 10 ) i = 0; // To make sure there is no overflow
}
int main()
{
    int a;
    int values[10];
    while(1)
    {
       scanf("%d",&a);
       push(a, values);
    }
}
</code>```

Title: i can't hold old entries

Body:
You must allocate only once. At the moment you are creating a memory leak each time you call the function push. Nobody refers to the memory once you leave the function. You can make it static to keep the information. Be aware that you are also limiting the number of values that you can hold at 10.

void push(int p)
{
    static int i=0;
    static int *ptr =(int *)malloc((10)*sizeof(int)); // To keep the values
    int b;
    ptr[i]=p;
    for(b=0;b<=i;b++){
        printf("%d",ptr[b]);
        printf("\n");
    }
    i++;
    if( i >= 10 ) i = 0; // To make sure there is no overflow
}

Better yet you could pass in the location where you want to save the information.

void push(int p, int *ptr)
{
    static int i=0;
    int b;
    ptr[i] = b;
    for(b=0;b<=i;b++){
       printf("%d",ptr[b]);
       printf("\n");
    }
    i++;
    if( i >= 10 ) i = 0; // To make sure there is no overflow
}
int main()
{
    int a;
    int values[10];
    while(1)
    {
       scanf("%d",&a);
       push(a, values);
    }
}


问:
Unable to assign value to textbox in angularjs
Hi I am developing web application in angularjs. I have one textbox and i am trying to bind data using some API's. Below is my html code.

```<code>  <input class="with-icon" type="text" name="groupname" placeholder="{{ 'Group Name' | translate }}" ng-model="user.name" required my-maxlength="50" ng-readonly="groupname">
</code>```

Below is my Angular code.

```<code>function getgroupbyID(groupID) {
            var getsavedvechilceUrl = baseurl + "api/RolesPermission/getbyID/" + groupID;
            $http.get(getsavedvechilceUrl).then(function (response) {
                $scope.user.name = response.data.dataAPI.groupname;
            }, function (error) {

            })
        }
</code>```

When the above code runs i ended up in error  Cannot set property 'name' of undefined in the $scope.user.name. May i know hwy i am getting this error? Any help would be appreciated. Thank you

答:
define the user object first </p>

```<code>$scope.user = {};

function getgroupbyID(groupID) {
    var getsavedvechilceUrl = baseurl + "api/RolesPermission/getbyID/" + groupID;
    $http.get(getsavedvechilceUrl).then(function(response) {
        $scope.user.name = response.data.dataAPI.groupname;
    }, function(error) {

    })
}
</code>```

Body:
Hi I am developing web application in angularjs. I have one textbox and i am trying to bind data using some API's. Below is my html code.

  <input class="with-icon" type="text" name="groupname" placeholder="{{ 'Group Name' | translate }}" ng-model="user.name" required my-maxlength="50" ng-readonly="groupname">

Below is my Angular code.

function getgroupbyID(groupID) {
            var getsavedvechilceUrl = baseurl + "api/RolesPermission/getbyID/" + groupID;
            $http.get(getsavedvechilceUrl).then(function (response) {
                $scope.user.name = response.data.dataAPI.groupname;
            }, function (error) {

            })
        }

When the above code runs i ended up in error  Cannot set property 'name' of undefined in the $scope.user.name. May i know hwy i am getting this error? Any help would be appreciated. Thank you

Body:
define the user object first

$scope.user = {};

function getgroupbyID(groupID) {
    var getsavedvechilceUrl = baseurl + "api/RolesPermission/getbyID/" + groupID;
    $http.get(getsavedvechilceUrl).then(function(response) {
        $scope.user.name = response.data.dataAPI.groupname;
    }, function(error) {

    })
}


问:
How to resume RxJs Observable Interval on Error
I am merging two Observables.
The first one gets the current temperature on init.
The second one polls at a certain interval the API.
If the Api call fails, then the Observable interval is not resumed.

How could I resume it?

```<code>getCurrentTemp(): Observable<number> {
    return this.http.get(this.environmentService.getTemperatureUrl())
      .map((res: Response) => res.json())
      .switchMap(() => res.temp);
  }

  pollCurrentTemperature(): Subscription {
    const temp$ = this.getCurrentTemp();
    const tempInterval$ = Observable
      .interval(3000)
      .flatMap(() => this.getCurrentTemp());

    return temp$
      .take(1)
      .merge(tempInterval$)
      .subscribe((temp: number) => {
        console.log('temp', temp);
      }, (err) => {
        console.log('error', err);
        // When the api fails my interval does not resume. How can I retry it?
      });
  }
</code>```

Any ideas? Ty

答:
Use catch.

Catch: recover from an onError notification by continuing the sequence without error

```<code>getCurrentTemp(): Observable<number> {
    return this.http.get(this.environmentService.getTemperatureUrl())
      .map((res: Response) => res.json())
      .catch(error => {
          console.log('Error occured');
          return Observable.empty();
       });
      .switchMap(() => res.temp);
}
</code>```

It will catch the error and silently return an empty observable in its place. In effect, the switchmap will skip over the failed api call silently as it will not emit for the empty observable.

Of course, you could have an alternate behaviour on error, but you need to catch it to avoid the problem you are facing.

Body:
I am merging two Observables.
The first one gets the current temperature on init.
The second one polls at a certain interval the API.
If the Api call fails, then the Observable interval is not resumed.

How could I resume it?

getCurrentTemp(): Observable<number> {
    return this.http.get(this.environmentService.getTemperatureUrl())
      .map((res: Response) => res.json())
      .switchMap(() => res.temp);
  }

  pollCurrentTemperature(): Subscription {
    const temp$ = this.getCurrentTemp();
    const tempInterval$ = Observable
      .interval(3000)
      .flatMap(() => this.getCurrentTemp());

    return temp$
      .take(1)
      .merge(tempInterval$)
      .subscribe((temp: number) => {
        console.log('temp', temp);
      }, (err) => {
        console.log('error', err);
        // When the api fails my interval does not resume. How can I retry it?
      });
  }

Any ideas? Ty

Body:
Use catch.

Catch: recover from an onError notification by continuing the sequence without error

getCurrentTemp(): Observable<number> {
    return this.http.get(this.environmentService.getTemperatureUrl())
      .map((res: Response) => res.json())
      .catch(error => {
          console.log('Error occured');
          return Observable.empty();
       });
      .switchMap(() => res.temp);
}

It will catch the error and silently return an empty observable in its place. In effect, the switchmap will skip over the failed api call silently as it will not emit for the empty observable.

Of course, you could have an alternate behaviour on error, but you need to catch it to avoid the problem you are facing.


问:
How to enable CORS on server-side code in java
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

```<code>import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}
</code>```

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .

答:
You have to enable it in your server first, check the website below to see how to configure your server (i.e., Tomcat) to enable CORS

https://enable-cors.org/server.html

Body:
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .


问:
Reach redux state from static function
I have a React Native application where I have a class which name is Helpers. These are a set of application related static helper function. Mostly I call them like Helpers.functionName(). What is the best way to reach the redux store from this static method? I want to modify it and read it.

I have the Helpers like this:

```<code>class Helpers extends Component {
  static getState(){
    return state;
  }
}
</code>```

I tried to use the connect, but inside the getState function the this.props is undefined.

答:
If you used the Provider component, so you can access to the redux store (and by consequence to the state of your store), using the context API provided by React.

In order to expose the context, you have to define the contextTypes inside your Helpers components.

```<code>static contextTypes = {
  store: PropTypes.object
}
</code>```

After that, inside your component you can read the store from this.context

Title: Reach redux state from static function

Body:
I have a React Native application where I have a class which name is Helpers. These are a set of application related static helper function. Mostly I call them like Helpers.functionName(). What is the best way to reach the redux store from this static method? I want to modify it and read it.

I have the Helpers like this:

class Helpers extends Component {
  static getState(){
    return state;
  }
}

I tried to use the connect, but inside the getState function the this.props is undefined.

Body:
If you used the Provider component, so you can access to the redux store (and by consequence to the state of your store), using the context API provided by React.

In order to expose the context, you have to define the contextTypes inside your Helpers components.

static contextTypes = {
  store: PropTypes.object
}

After that, inside your component you can read the store from this.context


问:
I created several stored procedures in phpmyadmin, how to call them using an sql query?
I created several stored procedures in phpmyadmin, how is it possible to call them using an sql query (mysql) ?</p>

答: As far as I know phpmyadmin doesn't support this.</p>


问:
Searching pages in Electron?
I’m currently working on designing a program in Electron. One of the key parts to this program will be a search option. Similar to other websites that you can search the whole site for pages that match your inquiry, I would like to search within the “pages”/“html files” of my program and have it display the search results. Preferably a letter at a time display in real time so one can see results as they type, but even an option with search will do. I just need to search within my program pages, not an external site. I’m having trouble figuring out how to get started implementing this, since PHP isn’t supported in Electron. I know react can do the letter at a time real time searching, but I’m not sure how to do the search of other pages or how to parse them for searching. Any suggestions, guidelines, or frameworks to get me on the right track would be helpful. Thanks!

EDIT: I’m also aware of the webcontents.findInPage() function, but that only searches the current page, not other pages in the project path. I am fine defining which pages to search manually if I can find a way to actually search them.

答:
If you store all your pages in a directory like "views" you can use fs to read each file and search its content.

I have made a quick example of something you could make to do this:

```<code>// The directory containing all your pages
let directoryToYourPagesOrHTMLFiles = "/your/directory/";

// Require fs so you can get all the files and file content
const fs = require("fs");

// Require html-to-text so you can parse the HTML in the files
// into text so you can search on the data easier
let htmlToText = require('html-to-text'); // npm install --save html-to-text

// Run this function when a user enters a character
function userTyped(inputValue) {
    // Foreach file in the directory
    fs.readdir(directoryToYourPagesOrHTMLFiles).forEach(filename => {
        // Read the file contents
        fs.readFile(directoryToYourPagesOrHTMLFiles + "/" + filename, "utf8", (err, data) => {
            // If there was an error reading the file log it
            if(err) {
                console.log(err);
            } else {
                // If there was no error, parse the HTML into text
                let text = htmlToText.fromString(data);

                // Perform your search on the next using the inputValue

                // Example Search:
                if(text.indexOf(inputValue) > -1) {
                    // Display the page in your search results
                    displaySearchResult(directoryToYourPagesOrHTMLFiles + "/" + filename);
                }
            }
        });
    });
}

function displaySearchResult(pagePath) {
    /*
        Add the page to a results page
     */
}
</code>```

I didn't test this because it did it in a rush but it shows the concept of what you need to do!

Hope this helps you!

Title: Searching pages in Electron?

Body:
If you store all your pages in a directory like "views" you can use fs to read each file and search its content.

I have made a quick example of something you could make to do this:

// The directory containing all your pages
let directoryToYourPagesOrHTMLFiles = "/your/directory/";

// Require fs so you can get all the files and file content
const fs = require("fs");

// Require html-to-text so you can parse the HTML in the files
// into text so you can search on the data easier
let htmlToText = require('html-to-text'); // npm install --save html-to-text

// Run this function when a user enters a character
function userTyped(inputValue) {
    // Foreach file in the directory
    fs.readdir(directoryToYourPagesOrHTMLFiles).forEach(filename => {
        // Read the file contents
        fs.readFile(directoryToYourPagesOrHTMLFiles + "/" + filename, "utf8", (err, data) => {
            // If there was an error reading the file log it
            if(err) {
                console.log(err);
            } else {
                // If there was no error, parse the HTML into text
                let text = htmlToText.fromString(data);

                // Perform your search on the next using the inputValue

                // Example Search:
                if(text.indexOf(inputValue) > -1) {
                    // Display the page in your search results
                    displaySearchResult(directoryToYourPagesOrHTMLFiles + "/" + filename);
                }
            }
        });
    });
}

function displaySearchResult(pagePath) {
    /*
        Add the page to a results page
     */
}

I didn't test this because it did it in a rush but it shows the concept of what you need to do!

Hope this helps you!


问:
Performance : SQL Queries vs Server-Side PHP Loops (MYSQL vs PHP)
I have not seen much info on this topic and require some data . I am new to using complex MySQL queries and i was wondering about the performance costs of Complex queries in comparison to a simple query and then run server side php calculations on it .

E.g :

'Simple' query :

```<code>SELECT id as ID, date(x_date),  v_price as price
                From tableX
                WHERE v_price IN
                (
                    select MIN(v_price) from tableX
                    GROUP BY week(x_date)
                )
            )
</code>```

Now lets say i want to count the number of times similar prices occurred .

I can do it in 2 ways .

A) Use a foreach loop server side php and calculate the data

B) Do another select in sql

```<code>group by price
ORDER BY COUNT(price) DESC
</code>```

Which is the best way to proceed ? via SQL or server code (php)

What are the performance costs , time , server load etc.....

答:
First, doing the work in the database is almost always better.  This is discussed many times for each context where someone wants to do RBAR (row-by-agonizing row) processing.

Second, it is highly unlikely that this "simple" query does what you want:

```<code>SELECT id as ID, date(x_date), v_price as price
From tableX
WHERE v_price IN (select MIN(v_price) from tableX FROM tableX GROUP BY week(x_date))
</code>```

This returns all rows in tableX where the minimum price matches any week's minimum price.  More likely, you want:

```<code>SELECT id as ID, date(x_date), v_price as price
From tableX
WHERE (yearweek(x_date), v_price) IN (
          select yearweek(x_date), MIN(v_price)
          from tableX
          group by yearweek(x_date)
         );
</code>```

Note that this also takes the year into account.

Body:
I have not seen much info on this topic and require some data . I am new to using complex MySQL queries and i was wondering about the performance costs of Complex queries in comparison to a simple query and then run server side php calculations on it .

E.g :

'Simple' query :

SELECT id as ID, date(x_date),  v_price as price
                From tableX
                WHERE v_price IN
                (
                    select MIN(v_price) from tableX
                    GROUP BY week(x_date)
                )
            )

Now lets say i want to count the number of times similar prices occurred .

I can do it in 2 ways .

A) Use a foreach loop server side php and calculate the data

B) Do another select in sql

group by price
ORDER BY COUNT(price) DESC

Which is the best way to proceed ? via SQL or server code (php)

What are the performance costs , time , server load etc.....

Body:
First, doing the work in the database is almost always better.  This is discussed many times for each context where someone wants to do RBAR (row-by-agonizing row) processing.

Second, it is highly unlikely that this "simple" query does what you want:

SELECT id as ID, date(x_date), v_price as price
From tableX
WHERE v_price IN (select MIN(v_price) from tableX FROM tableX GROUP BY week(x_date))

This returns all rows in tableX where the minimum price matches any week's minimum price.  More likely, you want:

SELECT id as ID, date(x_date), v_price as price
From tableX
WHERE (yearweek(x_date), v_price) IN (
          select yearweek(x_date), MIN(v_price)
          from tableX
          group by yearweek(x_date)
         );

Note that this also takes the year into account.


问:
Loading async data into a data model on init
How do I load data from an async callback into the parent class attributes?

I have a database in Firebase which holds my user profiles. I want to be able to pass in the node key and have it populate the object with the given values.

Because it works async, I am getting the default values from the object because the callback completes after the class init.

Obviously I'm new to Swift so apologies if the terminology is sketchy.

I read this thread which talked about inversion of control pattern, and whilst it made sense, I couldn't work out how to actually initiate the class.

UserProfile.swift:

```<code>import UIKit
import Firebase
import FBSDKCoreKit

class UserProfile{

    var ref: DatabaseReference!

    var uid : String = ""
    var name : String = ""
    var location : String = ""
    //var posts = [String]()

    init(uid : String) {
        self.ref = Database.database().reference().child("user_profiles").child(uid)
        self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
            let userObj = snapshot.value as? [String : AnyObject] ?? [:]
            self.uid = uid
            self.name = userObj["name"] as! String
            self.location = userObj["location"] as! String
        })
    }
}
</code>```

ViewController.swift

```<code>let user = UserProfile(uid : "NODEKEYINFIREBASE")
print(user)
</code>```

Output:

```<code>()
</code>```

答:
You can make a protocol that will be called after the object is initialized.

```<code>import UIKit
import Firebase
import FBSDKCoreKit

protocol UserProfileProtocol {
    func userLoaded(userProfile: UserProfile);
}

class UserProfile{

var ref: DatabaseReference!

var uid : String = ""
var name : String = ""
var location : String = ""
//var posts = [String]()

init(uid : String, listener: UserProfileProtocol) {
    self.ref = Database.database().reference().child("user_profiles").child(uid)
    self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
        let userObj = snapshot.value as? [String : AnyObject] ?? [:]
        self.uid = uid
        self.name = userObj["name"] as! String
        self.location = userObj["location"] as! String
        listener.userLoaded(userProfile: self)
    })
  }
}
</code>```

Add the protocol to the parent class as UserProfileProtocol

class parentViewController: UIViewController, UserProfileProtocol

I hope this works. Otherwise try the solution of @Vlad Pulichev

Body:
How do I load data from an async callback into the parent class attributes?

I have a database in Firebase which holds my user profiles. I want to be able to pass in the node key and have it populate the object with the given values.

Because it works async, I am getting the default values from the object because the callback completes after the class init.

Obviously I'm new to Swift so apologies if the terminology is sketchy.

I read this thread which talked about inversion of control pattern, and whilst it made sense, I couldn't work out how to actually initiate the class.

UserProfile.swift:

import UIKit
import Firebase
import FBSDKCoreKit

class UserProfile{

    var ref: DatabaseReference!

    var uid : String = ""
    var name : String = ""
    var location : String = ""
    //var posts = [String]()

    init(uid : String) {
        self.ref = Database.database().reference().child("user_profiles").child(uid)
        self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
            let userObj = snapshot.value as? [String : AnyObject] ?? [:]
            self.uid = uid
            self.name = userObj["name"] as! String
            self.location = userObj["location"] as! String
        })
    }
}

ViewController.swift

let user = UserProfile(uid : "NODEKEYINFIREBASE")
print(user)

Output:

()

Body:
You can make a protocol that will be called after the object is initialized.

import UIKit
import Firebase
import FBSDKCoreKit

protocol UserProfileProtocol {
    func userLoaded(userProfile: UserProfile);
}

class UserProfile{

var ref: DatabaseReference!

var uid : String = ""
var name : String = ""
var location : String = ""
//var posts = [String]()

init(uid : String, listener: UserProfileProtocol) {
    self.ref = Database.database().reference().child("user_profiles").child(uid)
    self.ref.observeSingleEvent(of: .value, with: { (snapshot) in
        let userObj = snapshot.value as? [String : AnyObject] ?? [:]
        self.uid = uid
        self.name = userObj["name"] as! String
        self.location = userObj["location"] as! String
        listener.userLoaded(userProfile: self)
    })
  }
}

Add the protocol to the parent class as UserProfileProtocol

class parentViewController: UIViewController, UserProfileProtocol

I hope this works. Otherwise try the solution of @Vlad Pulichev


问:
Filter JSON data in TextField
Version that I use:

```<code>psycopg2==2.6.2
django=1.10.5
postgres=9.3
</code>```

I want to store JSON data to the database using Django, but I can't use JSONField() because it needs jsonb type that only present in PostgreSQL >=9.4.

My Django model is as follows:

```<code>class Inspection(models.Model):
    data = models.TextField(null=False, blank=False)
</code>```

In the data field I want to store JSON data.

The data is as follows:

Record1:

```<code>{
  "url": "some_url",
  "user": [
    {
      "id": "1",
      "email": "myemail@hotmail.com",
      "first_name": "My_First_Name",
      "last_name": "My_Last_Name"
    }
  ]
}
</code>```

Record2:

```<code>{
      "url": "some_url",
      "user": [
        {
          "id": "2",
          "email": "myemail_2@hotmail.com",
          "first_name": "My_First_Name_2",
          "last_name": "My_Last_Name_2"
        }
      ]
    }
</code>```

Can I filter on user id?

答: You can implement you own filter. Take a look at this article. You can write SQL query directly, and put it in custom filter.</p>

Title: Filter JSON data in TextField

Body:
Version that I use:

psycopg2==2.6.2
django=1.10.5
postgres=9.3

I want to store JSON data to the database using Django, but I can't use JSONField() because it needs jsonb type that only present in PostgreSQL >=9.4.

My Django model is as follows:

class Inspection(models.Model):
    data = models.TextField(null=False, blank=False)

In the data field I want to store JSON data.

The data is as follows:

Record1:

{
  "url": "some_url",
  "user": [
    {
      "id": "1",
      "email": "myemail@hotmail.com",
      "first_name": "My_First_Name",
      "last_name": "My_Last_Name"
    }
  ]
}

Record2:

{
      "url": "some_url",
      "user": [
        {
          "id": "2",
          "email": "myemail_2@hotmail.com",
          "first_name": "My_First_Name_2",
          "last_name": "My_Last_Name_2"
        }
      ]
    }

Can I filter on user id?


问:
NodeJS sync flow
Hello i have been using a library called deasync it allows me to get things done in a cleaner way, i have a method like this,

```<code>syncGetMany: function(model, query){
        var ret;
        setTimeout(function(){

         model.find(query, (error, body) => {
            if(body){
                //Awesome got the data
                ret=  body
            }
            else{

                 //What a cruel world

                // No data, fall back to an empty array
                ret = [];
            }

        });

        },0);
        while(ret === undefined) {
            require('deasync').sleep(0);
        }

        //returns an empty array or the real data
        return ret;
},
</code>```

Then i simply call it like this.

```<code>var data = syncGetMany(MongooseModel, queryObj);
// the rest of my code
</code>```

QUESTION: is there a way to get this done using ES6, or any similar library.

PS: Not duplicate as other questions are not relevant to my context

答:
simplest way to get this code more cleaner is to use async/await, it's available in node.js version => 7.0. If I think well your model.find method returns promise.

```<code>async syncGetMany (model, query) {
    let ret;
    ret = await model.find(query);
    //ret is keeping body from response now, if error occured error is throwed as promise exception
    //Could do some sync ops on ret variable
    return ret;
}
</code>```

When you are using async/await you should put your method execution into try/catch. But you can also catch errors inside syncGetMany method, probably it should looks like this:

```<code>async syncGetMany(model, query) {
    let ret;
    try {
        ret = await model.find(query);
        return ret;
    } catch(err) {
        console.error(err);
        return []; //empty array or any error string/object
    }
}
</code>```

And your execution looks like you wrote with additional await operator (using es6 provide let/const operators for var operator replacement)
let data = await syncGetMany(MongooseModel, queryObj);

Article with async/await explanation:
https://blog.risingstack.com/async-await-node-js-7-nightly/

If you don't want to use Node v7.0 you should code something like this using promises and generators.

https://medium.com/@rdsubhas/es6-from-callbacks-to-promises-to-generators-87f1c0cd8f2e

I hope I helped.

Update
So when your mongoose instance doesn't supports promises there are three options (depends I think on node versions). In my opinion promises are cleaner way to make asynchronous request so I suggest using them.

First option (native promises):

```<code>syncGetMany(model, query) {
    return new Promise((resolve, reject) => {
        model.find(query, (err, res) => {
            if(err) {
                return reject(err);
            }
            resolve(res);
        });
    });
}
</code>```

Second option (bluebird library, added Async postfix to all methods):

```<code>const mongoose = require( 'mongoose' );
const Promise = require('bluebird');
Promise.promisifyAll( mongoose );

async syncGetMany(model, query) {
    let ret;
    try {
        ret = await model.findAsync(query);
        return ret;
    } catch(err) {
        console.error(err);
        return []; //empty array or any error string/object
    }
}
</code>```

Third option (Node version => 8.0):

Using native promisify on function:
https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

On our synchronous part (with async operator before function construction):
let data = await syncGetMany(MongooseModel, queryObj);

Title: NodeJS sync flow

Body:
Hello i have been using a library called deasync it allows me to get things done in a cleaner way, i have a method like this,

syncGetMany: function(model, query){
        var ret;
        setTimeout(function(){

         model.find(query, (error, body) => {
            if(body){
                //Awesome got the data
                ret=  body
            }
            else{

                 //What a cruel world

                // No data, fall back to an empty array
                ret = [];
            }

        });

        },0);
        while(ret === undefined) {
            require('deasync').sleep(0);
        }

        //returns an empty array or the real data
        return ret;
},

Then i simply call it like this.

var data = syncGetMany(MongooseModel, queryObj);
// the rest of my code

QUESTION: is there a way to get this done using ES6, or any similar library.

PS: Not duplicate as other questions are not relevant to my context

Body:
simplest way to get this code more cleaner is to use async/await, it's available in node.js version => 7.0. If I think well your model.find method returns promise.

async syncGetMany (model, query) {
    let ret;
    ret = await model.find(query);
    //ret is keeping body from response now, if error occured error is throwed as promise exception
    //Could do some sync ops on ret variable
    return ret;
}

When you are using async/await you should put your method execution into try/catch. But you can also catch errors inside syncGetMany method, probably it should looks like this:

async syncGetMany(model, query) {
    let ret;
    try {
        ret = await model.find(query);
        return ret;
    } catch(err) {
        console.error(err);
        return []; //empty array or any error string/object
    }
}

And your execution looks like you wrote with additional await operator (using es6 provide let/const operators for var operator replacement)
let data = await syncGetMany(MongooseModel, queryObj);

Article with async/await explanation:
https://blog.risingstack.com/async-await-node-js-7-nightly/

If you don't want to use Node v7.0 you should code something like this using promises and generators.

https://medium.com/@rdsubhas/es6-from-callbacks-to-promises-to-generators-87f1c0cd8f2e

I hope I helped.

Update
So when your mongoose instance doesn't supports promises there are three options (depends I think on node versions). In my opinion promises are cleaner way to make asynchronous request so I suggest using them.

First option (native promises):

syncGetMany(model, query) {
    return new Promise((resolve, reject) => {
        model.find(query, (err, res) => {
            if(err) {
                return reject(err);
            }
            resolve(res);
        });
    });
}

Second option (bluebird library, added Async postfix to all methods):

const mongoose = require( 'mongoose' );
const Promise = require('bluebird');
Promise.promisifyAll( mongoose );

async syncGetMany(model, query) {
    let ret;
    try {
        ret = await model.findAsync(query);
        return ret;
    } catch(err) {
        console.error(err);
        return []; //empty array or any error string/object
    }
}

Third option (Node version => 8.0):

Using native promisify on function:
https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

On our synchronous part (with async operator before function construction):
let data = await syncGetMany(MongooseModel, queryObj);


问:
Bind ComboBox items to property of list of radiobuttons wpf
I have a ComboBox which I wish to bind to an ObservableCollection<RadioButton>. However, I wish to list the ToolTip property in the ComboBox and not actual RadioButtons.

Example:

If I have 3 RadioButtons with ToolTips 1, 2, and 3. I wish the ComboBox to contain 3 string items, 1, 2 and 3.

Code:

View:

```<code><ComboBox x:Name="LandmarkIdComboBox" Grid.Column="1" DisplayMemberPath="ToolTip" ItemsSource="{Binding Landmarks, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          SelectedItem="{Binding SelectedLandmark, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
          VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</code>```

ViewModel:

```<code>private ObservableCollection<RadioButton> m_landmarks = new ObservableCollection<RadioButton>();
private RadioButton m_selectedLandmark;

public ObservableCollection<RadioButton> Landmarks
{
    get => m_landmarks;
    set
    {
        m_landmarks = value;
        OnPropertyChanged();
    }
}
public RadioButton SelectedLandmark
{
    get => m_selectedLandmark;
    set
    {
        m_selectedLandmark = value;
        OnPropertyChanged();
    }
}
</code>```

Using the above code I can see the mentioned 1,2 and 3 items, but I cannot select them. I guess because they are not regular items but RadioButtons so clicking them makes them Checked/UnChecked rather than selected.

I could use an additional Strruct/Class to achieve what I need, but of course I prefer not to, if there is another way.

So, is there another way?

答:
It is not the selection that is the issue here but rather the fact that RadioButton is a ContentControl. This means that its Content is displayed when selected in a ComboBox.

You could fix this by defining a custom ControlTemplate:

```<code><ComboBox x:Name="LandmarkIdComboBox" Grid.Column="1" ItemsSource="{Binding Landmarks}" SelectedItem="{Binding SelectedLandmark}"
          HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
          VerticalAlignment="Center" VerticalContentAlignment="Center">
    <ComboBox.Resources>
        <Style TargetType="RadioButton">
            <Setter Property="Content" Value="{Binding ToolTip, RelativeSource={RelativeSource Self}}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="RadioButton">
                        <TextBlock Text="{TemplateBinding ToolTip}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.Resources>
</ComboBox>
</code>```

Defining an ObservableCollection<RadioButton> in a view model breaks the MVVM pattern though but I guess you have your reasons.

Body:
I have a ComboBox which I wish to bind to an ObservableCollection<RadioButton>. However, I wish to list the ToolTip property in the ComboBox and not actual RadioButtons.

Example:

If I have 3 RadioButtons with ToolTips 1, 2, and 3. I wish the ComboBox to contain 3 string items, 1, 2 and 3.

Code:

View:

<ComboBox x:Name="LandmarkIdComboBox" Grid.Column="1" DisplayMemberPath="ToolTip" ItemsSource="{Binding Landmarks, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          SelectedItem="{Binding SelectedLandmark, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
          VerticalAlignment="Center" VerticalContentAlignment="Center"/>

ViewModel:

private ObservableCollection<RadioButton> m_landmarks = new ObservableCollection<RadioButton>();
private RadioButton m_selectedLandmark;

public ObservableCollection<RadioButton> Landmarks
{
    get => m_landmarks;
    set
    {
        m_landmarks = value;
        OnPropertyChanged();
    }
}
public RadioButton SelectedLandmark
{
    get => m_selectedLandmark;
    set
    {
        m_selectedLandmark = value;
        OnPropertyChanged();
    }
}

Using the above code I can see the mentioned 1,2 and 3 items, but I cannot select them. I guess because they are not regular items but RadioButtons so clicking them makes them Checked/UnChecked rather than selected.

I could use an additional Strruct/Class to achieve what I need, but of course I prefer not to, if there is another way.

So, is there another way?

Body:
It is not the selection that is the issue here but rather the fact that RadioButton is a ContentControl. This means that its Content is displayed when selected in a ComboBox.

You could fix this by defining a custom ControlTemplate:

<ComboBox x:Name="LandmarkIdComboBox" Grid.Column="1" ItemsSource="{Binding Landmarks}" SelectedItem="{Binding SelectedLandmark}"
          HorizontalContentAlignment="Center" HorizontalAlignment="Stretch"
          VerticalAlignment="Center" VerticalContentAlignment="Center">
    <ComboBox.Resources>
        <Style TargetType="RadioButton">
            <Setter Property="Content" Value="{Binding ToolTip, RelativeSource={RelativeSource Self}}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="RadioButton">
                        <TextBlock Text="{TemplateBinding ToolTip}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.Resources>
</ComboBox>

Defining an ObservableCollection<RadioButton> in a view model breaks the MVVM pattern though but I guess you have your reasons.


问:
Excel VBA : How to add droplist every time i click?
I want when I click the drop down list button will add directly to each time I click it will be added.
this is my code

```<code>Sub add()
Dim myList$, i%
myList = ""
For i = 1 To 7
myList = myList & "ListItem" & i & ","
Next i
myList = Mid(myList, 1, Len(myList) - 1)
With Range("B4").Validation
.Delete
.Add _
Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=myList
End With

Dim Lig As Long
For Lig = Range("B65536").End(xlUp).Row To 6 Step -1
    If Cells(Lig, 1) = Cells(Lig - 1, 1) Then
        Rows(Lig).Insert Shift:=xlDown
        Lig = Lig - 1

    End If
Next Lig
End Sub
</code>```

Please help :)

答:
I'm not really sure on you need but there is no event, as far as I know, for the dropdown button clicked. But you could se you code in the event Worksheet_SelectionChange, the object Target will contain the new cell selected so you could change it's validation.

Hope it will help.

Body:
I want when I click the drop down list button will add directly to each time I click it will be added.
this is my code

Sub add()
Dim myList$, i%
myList = ""
For i = 1 To 7
myList = myList & "ListItem" & i & ","
Next i
myList = Mid(myList, 1, Len(myList) - 1)
With Range("B4").Validation
.Delete
.Add _
Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=myList
End With

Dim Lig As Long
For Lig = Range("B65536").End(xlUp).Row To 6 Step -1
    If Cells(Lig, 1) = Cells(Lig - 1, 1) Then
        Rows(Lig).Insert Shift:=xlDown
        Lig = Lig - 1

    End If
Next Lig
End Sub

Please help :)


问:
Regular expression: if three letters are included
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

```<code>words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end
</code>```

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

```<code>leters = "abc"
words.select{ |w| w.count(letters) >= 3 }
</code>```

upd 2

Bad solution, example:

```<code>"lllllll".count("lua") #=> 5
</code>```

答:
Looks crazy, but it works:

```<code>leters = "abc"
words.select{ |w| w.count(letters) >= 3 }
</code>```

But it isn't work with cyrillic letters :(

Body:
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

leters = "abc"
words.select{ |w| w.count(letters) >= 3 }

upd 2

Bad solution, example:

"lllllll".count("lua") #=> 5

Body:
Looks crazy, but it works:

leters = "abc"
words.select{ |w| w.count(letters) >= 3 }

But it isn't work with cyrillic letters :(


问:
Adding zip code and address to Coffee for Stripe payment
We have a Python app that takes payment via card, it has been hit hard be people with stolen cards. To help prevent this we want to add zip code and billing address to the payment info. From what I can figure out the StripeCheckout is configured in the Coffee script below. Adding data-zip-code: true and data-billing-address: true just makes the app fail. I'm not familiar with Stripe or Coffee and would appreciate some assistance on adding these variables to the config.

```<code>handler = StripeCheckout.configure
  key: window.stripeKey
  token: (token) ->
    $('.token').val token.id
    $('.buy-form').submit()
</code>```

StripeCheckout Reference: https://stripe.com/docs/checkout#integration-simple-options

答:
You're using the custom integration, so you shouldn't prefix the options with data- -- that prefix is only used when options as passed as HTML attributes in the simple integration.

I don't have much experience with Coffeescript, but this should work:

```<code>handler = StripeCheckout.configure
  key: window.stripeKey
  billingAddress: true
  token: (token) ->
    $('.token').val token.id
    $('.buy-form').submit()
</code>```

On a side note, zipCode: true isn't necessary as the ZIP/postal code will be collected as part of the billing address (i.e. it's implied by billingAddress: true.

Body:
We have a Python app that takes payment via card, it has been hit hard be people with stolen cards. To help prevent this we want to add zip code and billing address to the payment info. From what I can figure out the StripeCheckout is configured in the Coffee script below. Adding data-zip-code: true and data-billing-address: true just makes the app fail. I'm not familiar with Stripe or Coffee and would appreciate some assistance on adding these variables to the config.

handler = StripeCheckout.configure
  key: window.stripeKey
  token: (token) ->
    $('.token').val token.id
    $('.buy-form').submit()

StripeCheckout Reference: https://stripe.com/docs/checkout#integration-simple-options

Body:
You're using the custom integration, so you shouldn't prefix the options with data- -- that prefix is only used when options as passed as HTML attributes in the simple integration.

I don't have much experience with Coffeescript, but this should work:

handler = StripeCheckout.configure
  key: window.stripeKey
  billingAddress: true
  token: (token) ->
    $('.token').val token.id
    $('.buy-form').submit()

On a side note, zipCode: true isn't necessary as the ZIP/postal code will be collected as part of the billing address (i.e. it's implied by billingAddress: true.