问:
Angular2 load configuration from backend on startup
In my Angular2 app, I'm trying to load configurations from backend on bootstrap using HTTP so that I can use the extracted data for creating angular services.

Whenever I try to read the HTTP response saved in my Config, I always get TypeError: Cannot read property 'url' of undefined error.

It appears like the HTTP request completes only when the whole bootstrap method finishes, whereas my code tries to extract the Observable response before it is retrieved.

How can I fix it to extract configuration from server and use it to create angular services on startup? (I want to create services inside providers with extracted data)

Please comment if there is any better way of extracting configuration from server on startup.

My main.ts looks like this:

bootstrap(AppComponent,
    [APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
    .catch(err => console.error(err)
);
```

<p><strong>configuration.service.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>@Injectable()
export class ConfigurationService {

    constructor(private http: Http) {
    }

    load() {
        return this.http.get('config/getConfig').map(response => response.json());
    }

}
</code>```

config.ts

@Injectable()
export class Config {

    public config;

    constructor(public configurationService: ConfigurationService) {
        configurationService.load().subscribe(
            config => this.config = config,
            error => console.error('Error: ' + error)
        );
    }

    get(key: any) {
        return this.config[key];
    }
}
```

<p><strong>app.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>@Component({
    selector: 'app',
    templateUrl: 'app/app.component.html',
    styleUrls: ['app/app.component.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [MyService]
})
export class AppComponent {

    constructor(public myService: MyService) {
    }

}
</code>```

my.service.ts

@Injectable()
export class MyService{

    private url;

    constructor(public config: Config) {
        this.url = config.get('url');
    }
}
```

答:
This is a better way to write the load function

public load() {
    let promise =this.http.get(url).map(res => res.json()).toPromise();
    promise.then(config =>  this.validation = config);
    return promise;
};
```

Body:
In my Angular2 app, I'm trying to load configurations from backend on bootstrap using HTTP so that I can use the extracted data for creating angular services.

Whenever I try to read the HTTP response saved in my Config, I always get TypeError: Cannot read property 'url' of undefined error.

It appears like the HTTP request completes only when the whole bootstrap method finishes, whereas my code tries to extract the Observable response before it is retrieved.

How can I fix it to extract configuration from server and use it to create angular services on startup? (I want to create services inside providers with extracted data)

Please comment if there is any better way of extracting configuration from server on startup.

My main.ts looks like this:

bootstrap(AppComponent,
    [APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
    .catch(err => console.error(err)
);

configuration.service.ts

@Injectable()
export class ConfigurationService {

    constructor(private http: Http) {
    }

    load() {
        return this.http.get('config/getConfig').map(response => response.json());
    }

}

config.ts

@Injectable()
export class Config {

    public config;

    constructor(public configurationService: ConfigurationService) {
        configurationService.load().subscribe(
            config => this.config = config,
            error => console.error('Error: ' + error)
        );
    }

    get(key: any) {
        return this.config[key];
    }
}

app.component.ts

@Component({
    selector: 'app',
    templateUrl: 'app/app.component.html',
    styleUrls: ['app/app.component.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [MyService]
})
export class AppComponent {

    constructor(public myService: MyService) {
    }

}

my.service.ts

@Injectable()
export class MyService{

    private url;

    constructor(public config: Config) {
        this.url = config.get('url');
    }
}


来源: stackexchange

问:
PHP mysql function always return false on update query
I have below function to return status, the query can update the table but it still get status ACCT_NOT_FOUND, I've been try $sql->num_rows or $sql->affected_rows but does not work.

```<code>public function user_exit($uid, $mysqli)
{
    if(empty($uid)){
        return false;
    }
    $q  = "UPDATE `users` SET last_logged_out=now() ";
    $q .= "WHERE uid='".$uid."' ";

    $sql = $mysqli->query($q);

    if($sql->num_rows !== 0){
        return true;
    }
    return false;
}

$exit = $api->user_exit($uid, $mysqli);

if($exit !== FALSE){

    $data = array('status'=>'SUCCESS_LOGOUT');

}else{

    $data = array('status'=>'ACCT_NOT_FOUND');
}
</code>```

答:
you can use num_rows method with select query.

if you want to get affected row you should try affected_rows

Read specific document about affected rows http://php.net/manual/en/mysqli.affected-rows.php

```<code>if($mysqli->affected_rows != 0){
        return true;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have below function to return status, the query can update the table but it still get status ACCT_NOT_FOUND, I've been try $sql->num_rows or $sql->affected_rows but does not work.

public function user_exit($uid, $mysqli)
{
    if(empty($uid)){
        return false;
    }
    $q  = "UPDATE `users` SET last_logged_out=now() ";
    $q .= "WHERE uid='".$uid."' ";

    $sql = $mysqli->query($q);

    if($sql->num_rows !== 0){
        return true;
    }
    return false;
}

$exit = $api->user_exit($uid, $mysqli);

if($exit !== FALSE){

    $data = array('status'=>'SUCCESS_LOGOUT');

}else{

    $data = array('status'=>'ACCT_NOT_FOUND');
}

Body:
you can use num_rows method with select query.

if you want to get affected row you should try affected_rows

Read specific document about affected rows http://php.net/manual/en/mysqli.affected-rows.php

if($mysqli->affected_rows != 0){
        return true;
    }


问:
Method to return username and Id
Hi guys im trying to get Username And id, right now im just getting the id.

This is the Stored Procedure:

```<code> ALTER PROCEDURE [dbo].[spLogin]
    @username VARCHAR(MAX),
    @password VARCHAR(MAX)
    AS
        SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password
</code>```

This is my method:

```<code> public class UserBL
    {
        string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        public int CheckUserLogin(UserL User)
        {
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }
</code>```

This is my User class:

```<code> public class UserL
    {
        public int UserID { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }
</code>```

And im checking if the user exited by id With Ajax but I need to create sessions, and in order to do that I need

答:
use executereader because execute scalar return single value.</p>

```<code>    public class UserBL
        {
            string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            public int CheckUserLogin(UserL User)
            {
                using (SqlConnection con = new SqlConnection(conexion))
                {
                    SqlCommand comObj = new SqlCommand("spLogin", con);
                    comObj.CommandType = CommandType.StoredProcedure;
                    comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                    comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                    con.Open();
    var dr=comObj.ExecuteScalar();
 while(dr.read())
    {
    int userid=convert.toint16(dr[0]);
    string Password=dr[1].tostring();
    // now Manipulate as per as your requirment
    }
                }
            }
        }
</code>```

Title: Method to return username and Id

Body:
Hi guys im trying to get Username And id, right now im just getting the id.

This is the Stored Procedure:

 ALTER PROCEDURE [dbo].[spLogin]
    @username VARCHAR(MAX),
    @password VARCHAR(MAX)
    AS
        SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password

This is my method:

 public class UserBL
    {
        string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        public int CheckUserLogin(UserL User)
        {
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }

This is my User class:

 public class UserL
    {
        public int UserID { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }

And im checking if the user exited by id With Ajax but I need to create sessions, and in order to do that I need

Body:
use executereader because execute scalar return single value.

    public class UserBL
        {
            string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            public int CheckUserLogin(UserL User)
            {
                using (SqlConnection con = new SqlConnection(conexion))
                {
                    SqlCommand comObj = new SqlCommand("spLogin", con);
                    comObj.CommandType = CommandType.StoredProcedure;
                    comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                    comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                    con.Open();
    var dr=comObj.ExecuteScalar();
 while(dr.read())
    {
    int userid=convert.toint16(dr[0]);
    string Password=dr[1].tostring();
    // now Manipulate as per as your requirment
    }
                }
            }
        }


问:
Keycloak angular app file uploading not sending token
This is my angular configuration for appending keycloak token with every HTTP request.

```<code>module.factory('authInterceptor', function($q, Auth) {
    return {
        request: function (config) {
            var deferred = $q.defer();
            if (Auth.authz.token) {
                Auth.authz.updateToken(5).success(function() {
                    config.headers = config.headers || {};
                    config.headers.Authorization = 'Bearer ' + Auth.authz.token;
                    deferred.resolve(config);
                }).error(function() {
                        deferred.reject('Failed to refresh token');
                    });
            }
            return deferred.promise;
        }
    };
});
module.config(["$httpProvider", function ($httpProvider)  {
    $httpProvider.interceptors.push('authInterceptor');
}]);
</code>```

This is the request I sending to the backend. It seems the request not adding keycloak token, so I'm getting 403 forbidden error.

```<code>var formData = new FormData(file);
formData.append('file', file);
return $http({
  method: 'POST',
  url: API_BASE + '/uploadEmployeeDetails/excelUpload',
  headers: {
    'Content-Type': undefined
  },
  data: formData,
  transformRequest: function(data, headersGetterFunction) {
    return data;
  }
});
</code>```

Backend security config

答:
Since you are able to send the token to the back-end as you can see from the network tab of the browser.

The issue is in the api side on handling the csrf token

If the csrf token is enabled by default you should disable it.

Here is the code with your help, to disable it

```<code>http.csrf().disable();
http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
.authorizeRequests().antMatchers("/**")
.hasAnyRole("ORG_ADMIN", "EMPLOYEE", "PARENT", "STUDENT")
.anyRequest().permitAll();
</code>```

Body:
This is my angular configuration for appending keycloak token with every HTTP request.

module.factory('authInterceptor', function($q, Auth) {
    return {
        request: function (config) {
            var deferred = $q.defer();
            if (Auth.authz.token) {
                Auth.authz.updateToken(5).success(function() {
                    config.headers = config.headers || {};
                    config.headers.Authorization = 'Bearer ' + Auth.authz.token;
                    deferred.resolve(config);
                }).error(function() {
                        deferred.reject('Failed to refresh token');
                    });
            }
            return deferred.promise;
        }
    };
});
module.config(["$httpProvider", function ($httpProvider)  {
    $httpProvider.interceptors.push('authInterceptor');
}]);

This is the request I sending to the backend. It seems the request not adding keycloak token, so I'm getting 403 forbidden error.

var formData = new FormData(file);
formData.append('file', file);
return $http({
  method: 'POST',
  url: API_BASE + '/uploadEmployeeDetails/excelUpload',
  headers: {
    'Content-Type': undefined
  },
  data: formData,
  transformRequest: function(data, headersGetterFunction) {
    return data;
  }
});

Backend security config

Body:
Since you are able to send the token to the back-end as you can see from the network tab of the browser.

The issue is in the api side on handling the csrf token

If the csrf token is enabled by default you should disable it.

Here is the code with your help, to disable it

http.csrf().disable();
http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
.authorizeRequests().antMatchers("/**")
.hasAnyRole("ORG_ADMIN", "EMPLOYEE", "PARENT", "STUDENT")
.anyRequest().permitAll();


问:
Count number of value occurrences per column in matrix - R
I have a matrix in R that is structured like so:

ColA     ColB     ColC

5            7           12

9             8              3

15          0             25

I'd like to find, for each column, the number of values greater than 10, such that I would get a vector (or data frame?) showing this result:

ColA    1

ColB    0

ColC    2

答:
We can use

```<code>colSums(m1 >=10)
# ColA ColB ColC
#  1    0    2
</code>```

Or using tidyverse

```<code>library(tidyverse)
m1 %>%
    as.data.frame() %>%
    summarise_all(funs(sum(.>=10)))
#  ColA ColB ColC
#1    1    0    2
</code>```

Body:
We can use

colSums(m1 >=10)
# ColA ColB ColC
#  1    0    2

Or using tidyverse

library(tidyverse)
m1 %>%
    as.data.frame() %>%
    summarise_all(funs(sum(.>=10)))
#  ColA ColB ColC
#1    1    0    2


问:
Use of def, val, and var in scala
```<code>class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)
</code>```

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

```<code>def age = 30
age = 45
</code>```

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

答:
There are three ways of defining things in Scala:

def defines a method

val defines a fixed value (which cannot be modified)

var defines a variable (which can be modified)

Looking at your code:

```<code>def person = new Person("Kumar",12)
</code>```

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

```<code>person
</code>```

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

```<code>person.age = 20
</code>```

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:

```<code>println(person.age)
</code>```

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

```<code>println(person().age)
</code>```

Title: Use of def, val, and var in scala

Body:
class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

def age = 30
age = 45

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

Body:
There are three ways of defining things in Scala:

def defines a method

val defines a fixed value (which cannot be modified)

var defines a variable (which can be modified)

Looking at your code:

def person = new Person("Kumar",12)

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

person

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:

println(person.age)

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

println(person().age)


问:
Python: how do I resolve AttributeError: 'module' object has no attribute 'face_recognition_model_v1'
I have downloaded the file and placed it in the same directory from where I am running my code. But here facerec = dlib.face_recognition_model_v1(face_rec_model_path) I am still getting this Atribute error. i have given the full to where it is but still error.

this is my code, I am not able to identify where the problem is ?

```<code>import sys
import os
import dlib
import glob
from skimage import io

predictor_path = '/home/irum/Desktop/DLIB-recognition/shape_predictor_68_face_landmarks.dat'
face_rec_model_path = '/home/irum/Desktop/DLIB-recognition/dlib_face_recognition_resnet_model_v1.dat'
faces_folder_path = '/home/irum/Desktop/DLIB-recognition/att_faces/ERSHIAN'

# Load all the models we need: a detector to find the faces, a shape predictor
# to find face landmarks so we can precisely localize the face, and finally the

# face recognition model.
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)

win = dlib.image_window()

# Now process all the images
for f in glob.glob(os.path.join(faces_folder_path, "*.png")):
    print("Processing file: {}".format(f))
    img = io.imread(f)

    win.clear_overlay()
    win.set_image(img)

    # Ask the detector to find the bounding boxes of each face. The 1 in the
    # second argument indicates that we should upsample the image 1 time. This
    # will make everything bigger and allow us to detect more faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))

    # Now process each face we found.
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
        # Get the landmarks/parts for the face in box d.
        shape = sp(img, d)
        # Draw the face landmarks on the screen so we can see what face is currently being processed.
        win.clear_overlay()
        win.add_overlay(d)
        win.add_overlay(shape)

        face_descriptor = facerec.compute_face_descriptor(img, shape)
        print(face_descriptor)

        dlib.hit_enter_to_continue()
</code>```

答:
You need to install dlib.
Run
pip install dlib

Body:
I have downloaded the file and placed it in the same directory from where I am running my code. But here facerec = dlib.face_recognition_model_v1(face_rec_model_path) I am still getting this Atribute error. i have given the full to where it is but still error.

this is my code, I am not able to identify where the problem is ?

import sys
import os
import dlib
import glob
from skimage import io

predictor_path = '/home/irum/Desktop/DLIB-recognition/shape_predictor_68_face_landmarks.dat'
face_rec_model_path = '/home/irum/Desktop/DLIB-recognition/dlib_face_recognition_resnet_model_v1.dat'
faces_folder_path = '/home/irum/Desktop/DLIB-recognition/att_faces/ERSHIAN'

# Load all the models we need: a detector to find the faces, a shape predictor
# to find face landmarks so we can precisely localize the face, and finally the

# face recognition model.
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)

win = dlib.image_window()

# Now process all the images
for f in glob.glob(os.path.join(faces_folder_path, "*.png")):
    print("Processing file: {}".format(f))
    img = io.imread(f)

    win.clear_overlay()
    win.set_image(img)

    # Ask the detector to find the bounding boxes of each face. The 1 in the
    # second argument indicates that we should upsample the image 1 time. This
    # will make everything bigger and allow us to detect more faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))

    # Now process each face we found.
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
        # Get the landmarks/parts for the face in box d.
        shape = sp(img, d)
        # Draw the face landmarks on the screen so we can see what face is currently being processed.
        win.clear_overlay()
        win.add_overlay(d)
        win.add_overlay(shape)

        face_descriptor = facerec.compute_face_descriptor(img, shape)
        print(face_descriptor)

        dlib.hit_enter_to_continue()


问:
show ProgressBar above WebView so that it does not hide when scrolling down WebView
I have a ProgressBar as a child of WebView, which works fine.

Problem is When I scroll the WebView up, the progress bar hides.
Here is my activity_main.xml

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ionicframework.VendeeTouch.MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ProgressBar
            android:id="@+id/progressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5dp"
            android:layout_y="26dp"
            android:padding="2dip"></ProgressBar>

        <TextView
            android:id="@+id/tV1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="119dp"
            android:layout_y="286dp"
            android:text="Loading, please wait . . ."
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#000000"></TextView>
    </WebView>

</RelativeLayout>
</code>```

How do I keep it fixed at the top so that when I scroll down it does not hide?

答:
place the ProgressBar outside the WebView

```<code><ProgressBar
    android:id="@+id/progressbar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dip" />
<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/progressbar">
    <TextView
        android:id="@+id/tV1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Loading, please wait . . ."
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#000000" />
</WebView>
</code>```

you can set the height to 0 after loading is finished.
like this

```<code>        ProgressBar p=(ProgressBar)findViewById(R.id.progress);

        p.setLayoutParams(new LinearLayout .LayoutParams(LinearLayout .LayoutParams.MATCH_PARENT,0));
</code>```

Body:
I have a ProgressBar as a child of WebView, which works fine.

Problem is When I scroll the WebView up, the progress bar hides.
Here is my activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ionicframework.VendeeTouch.MainActivity">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ProgressBar
            android:id="@+id/progressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5dp"
            android:layout_y="26dp"
            android:padding="2dip"></ProgressBar>

        <TextView
            android:id="@+id/tV1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="119dp"
            android:layout_y="286dp"
            android:text="Loading, please wait . . ."
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#000000"></TextView>
    </WebView>

</RelativeLayout>

How do I keep it fixed at the top so that when I scroll down it does not hide?

Body:
place the ProgressBar outside the WebView

<ProgressBar
    android:id="@+id/progressbar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dip" />
<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/progressbar">
    <TextView
        android:id="@+id/tV1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Loading, please wait . . ."
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#000000" />
</WebView>

you can set the height to 0 after loading is finished.
like this

        ProgressBar p=(ProgressBar)findViewById(R.id.progress);

        p.setLayoutParams(new LinearLayout .LayoutParams(LinearLayout .LayoutParams.MATCH_PARENT,0));


问:
How to use cURL in magento 1.9 module
I've developed a module, at the moment only some function and get/post from to Database , the front I have it already done.
I want to add a class (cURL) to call 3rd party api, but I don't know how can I to implement that. It should be in controllers(IndexController?) or Model folder as new file? and if I have to add some details in config.xml?</p>

答:
I would suggest you to add ur cURl in helper class and call that helper method from controller.
No need to add any details in config.xml .Simply define your helper class in config.xml and add the cURL data in a helper function</p>

Title: How to use cURL in magento 1.9 module


问:
Django doesn't load static files
I have an Django project but I have problem with the static files. They are not loaded.

In my setting.py I have:

```<code>STATIC_ROOT = 'static'
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/"

STATICFILES_DIRS = (INSTALLED_FOLDER + ('' if DEV_MACHINE else (SALES_COMPANY_CODE_LOWER + '/')) + '/Autralis/libStatic',)
</code>```

I did next to load my styles:

```<code>ln -s /data /users/my_name/Projects/autralis/Autralis/libStatic/data
ln -s /users/my_name/Projects/autralis/Autralis/libStatic  /users/my_name/Projects/autralis/Autralis/static
</code>```

And I get static folder as follows:

The links to styles in the base template are as follows :

<link href="/static/autralis/css/base.css" rel="stylesheet" type="text/css" />

and if I click on the link a get page not found as follows:

Any idea how to solve this?

答:
I will give you an exemple from my Django project. Maybe it could help you ;)

My project tree :

In my settings.py file, I have :

```<code>STATIC_URL = '/static/'
THEME_DIRS = os.path.join(BASE_DIR, "static", "Theme/")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), THEME_DIRS, ]

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
</code>```

And my HTML files get :

```<code>{% load staticfiles %}
{% load static %}

...
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/>
</code>```

with context_processors.py file :

```<code>def GetTheme(request):
    return {'mytheme' : Theme.objects.values_list('favorite_theme').last()[0].encode("ascii")}
</code>```

or more simple :

```<code>{% load staticfiles %}
{% load static %}

    ...
<link rel="stylesheet" type="text/css" href="{% static 'css/Base_Identity.css' %}"/>
</code>```

Title: Django doesn't load static files

Body:
I have an Django project but I have problem with the static files. They are not loaded.

In my setting.py I have:

STATIC_ROOT = 'static'
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/"

STATICFILES_DIRS = (INSTALLED_FOLDER + ('' if DEV_MACHINE else (SALES_COMPANY_CODE_LOWER + '/')) + '/Autralis/libStatic',)

I did next to load my styles:

ln -s /data /users/my_name/Projects/autralis/Autralis/libStatic/data
ln -s /users/my_name/Projects/autralis/Autralis/libStatic  /users/my_name/Projects/autralis/Autralis/static

And I get static folder as follows:

The links to styles in the base template are as follows :

<link href="/static/autralis/css/base.css" rel="stylesheet" type="text/css" />

and if I click on the link a get page not found as follows:

Any idea how to solve this?

Body:
I will give you an exemple from my Django project. Maybe it could help you ;)

My project tree :

In my settings.py file, I have :

STATIC_URL = '/static/'
THEME_DIRS = os.path.join(BASE_DIR, "static", "Theme/")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), THEME_DIRS, ]

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')

And my HTML files get :

{% load staticfiles %}
{% load static %}

...
<link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/>

with context_processors.py file :

def GetTheme(request):
    return {'mytheme' : Theme.objects.values_list('favorite_theme').last()[0].encode("ascii")}

or more simple :

{% load staticfiles %}
{% load static %}

    ...
<link rel="stylesheet" type="text/css" href="{% static 'css/Base_Identity.css' %}"/>


问:
Spring JPA @query image
I need to get image saved in postgresql database using custom query in repository.
Currently i save image to database as byte[] with mime-type, file name and also create 2 thumbnail image in the same row.
For Http GET request i need to display the image, but i am required to create a qustom query so that if i want to get original image i query for that and dont load thumbnails or file name that are stored in the same table row in database.

MyFile entity:

```<code>@Entity
private String name;
private String mimeType;
private byte[] content;
private byte[] thumbnailSm;
private byte[] thumbnailMd;
// getters & setters
</code>```

Repository:

```<code>@Component
public interface MyFileRepository extends JpaRepository<MyFile, Long> {}
</code>```

Currently what i did in controller to get image from db:

```<code>    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public void getFile(@PathVariable Long id, HttpServletResponse response) throws IOException{
    MyFile myFile = myFileRepository.findOne(id);
    response.setContentType(myFile.getMimetype());
    response.getOutputStream().write(myFile.getContent());
    response.getOutputStream().close();
}
</code>```

The problem is that it loads all the content from database (thumbnails, name etc) when i only need original image.

I try to create a custom query in repository and the sql statement that i try to use is:

```<code>@Query(value = "SELECT content FROM file WHERE id=:id")
</code>```

Also tried the statement, don't really know what is the difference:

```<code>@Query(value = "SELECT f.content FROM file f WHERE f.id=:id")
</code>```

I get bytes from database but i can't seem to figure out how to send them from repository interface method to controller so i can display image.
I tried to use something like:

```<code>byte[] findFileById(@Param("id") Long id);
</code>```

and:

```<code>ResponseEntity<byte[]> findFileById(@Param("id") Long id);
</code>```

So my question is, after sql query gets bytes for image from db, how can i create a sql query method to get only image from db without also loading other content (thumbnails, name etc)?
Sorry if my explanation is confusing.

答:
When fetching an entity, all attributes are going to be loaded as well. You can set fetch strategy for column to FetchType.LAZY, in which case the entity attribute is loaded with a secondary select statement upon being accessed for the first time.

Check this The best way to lazy load entity attributes using JPA and Hibernate

Title: Spring JPA @query image

Body:
I need to get image saved in postgresql database using custom query in repository.
Currently i save image to database as byte[] with mime-type, file name and also create 2 thumbnail image in the same row.
For Http GET request i need to display the image, but i am required to create a qustom query so that if i want to get original image i query for that and dont load thumbnails or file name that are stored in the same table row in database.

MyFile entity:

@Entity
private String name;
private String mimeType;
private byte[] content;
private byte[] thumbnailSm;
private byte[] thumbnailMd;
// getters & setters

Repository:

@Component
public interface MyFileRepository extends JpaRepository<MyFile, Long> {}

Currently what i did in controller to get image from db:

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public void getFile(@PathVariable Long id, HttpServletResponse response) throws IOException{
    MyFile myFile = myFileRepository.findOne(id);
    response.setContentType(myFile.getMimetype());
    response.getOutputStream().write(myFile.getContent());
    response.getOutputStream().close();
}

The problem is that it loads all the content from database (thumbnails, name etc) when i only need original image.

I try to create a custom query in repository and the sql statement that i try to use is:

@Query(value = "SELECT content FROM file WHERE id=:id")

Also tried the statement, don't really know what is the difference:

@Query(value = "SELECT f.content FROM file f WHERE f.id=:id")

I get bytes from database but i can't seem to figure out how to send them from repository interface method to controller so i can display image.
I tried to use something like:

byte[] findFileById(@Param("id") Long id);

and:

ResponseEntity<byte[]> findFileById(@Param("id") Long id);

So my question is, after sql query gets bytes for image from db, how can i create a sql query method to get only image from db without also loading other content (thumbnails, name etc)?
Sorry if my explanation is confusing.


问:
access jquery unserialized data using getData in cakephp 3
I'm using cakephp 3.4

I have a form to submit values using ajax.

```<code><?= $this->Form->create(null, ['id' => 'search-form']) ?>
<?= $this->Form->control('keyword') ?>
<?= $this->Form->button(__('Search'), ['id' => 'search-submit']); ?>
<?= $this->Form->end() ?>
</code>```

and sending this data to action using

```<code>$('#search-submit').click(function(event){
    event.preventDefault();
    $.post('/dashboard/custom-search/ajax-search',
    {
        data: $('#search-form').serialize()
    }, function (response)
    {
        $('#search-result').html(response);
    });
    return false;
});
</code>```

In ajaxSearch action when I debug request data

```<code>debug($this->request->getData());
</code>```

It gives

```<code>[
    'data' => '_method=POST&keyword=world'
]
</code>```

But when I try

```<code>debug($this->request->getData('keyword'));
</code>```

It gives

```<code>null
</code>```

How can I get serialized data in an action? or How to unserialize data in action/controller?

答:
What you need to change is the way you are posting your serialized data to:

```<code>$.post('/dashboard/custom-search/ajax-search',
    $('#search-form').serialize(),
    function (response){
        $('#search-result').html(response);
});
</code>```

This way your getData() will return data in expected format.

Full info about passing serialized data via jQuery.post() can be found here: jQuery.post()

Body:
I'm using cakephp 3.4

I have a form to submit values using ajax.

<?= $this->Form->create(null, ['id' => 'search-form']) ?>
<?= $this->Form->control('keyword') ?>
<?= $this->Form->button(__('Search'), ['id' => 'search-submit']); ?>
<?= $this->Form->end() ?>

and sending this data to action using

$('#search-submit').click(function(event){
    event.preventDefault();
    $.post('/dashboard/custom-search/ajax-search',
    {
        data: $('#search-form').serialize()
    }, function (response)
    {
        $('#search-result').html(response);
    });
    return false;
});

In ajaxSearch action when I debug request data

debug($this->request->getData());

It gives

[
    'data' => '_method=POST&keyword=world'
]

But when I try

debug($this->request->getData('keyword'));

It gives

null

How can I get serialized data in an action? or How to unserialize data in action/controller?

Body:
What you need to change is the way you are posting your serialized data to:

$.post('/dashboard/custom-search/ajax-search',
    $('#search-form').serialize(),
    function (response){
        $('#search-result').html(response);
});

This way your getData() will return data in expected format.

Full info about passing serialized data via jQuery.post() can be found here: jQuery.post()


问:
Retrofit Unable to create call adapter
I followed the format from the tutorial in inserting data to database using Retrofit Library. The logcat shows the error Unable to create call adapter for retrofit2.Call<dagger.com.japorms.model.User_Account_Model> for method APIService.registerUser

Here is my APIService Interface:

```<code>    public interface APIService {

    @FormUrlEncoded
    @POST("test_db/register.php")
    Call<User_Account_Model> registerUser(@Field("email") String email, @Field("password") String password);
}
</code>```

Here is the Method:

```<code> public void registerUser(){
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Registering Account");
    progressDialog.setMessage("Please Wait ...");
    progressDialog.setCancelable(false);
    progressDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.73:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    APIService service = retrofit.create(APIService.class);

    User_Account_Model user_account_model = new User_Account_Model();
    user_account_model.email = reg_email_et.getText().toString();
    user_account_model.password = reg_pass_et.getText().toString();

    String conf_pass = reg_conf_pass_et.getText().toString();

    if(user_account_model.password.equals(conf_pass)){

        Call<User_Account_Model> call = service.registerUser(user_account_model.email,user_account_model.password);
        call.enqueue((new Callback<User_Account_Model>() {
            @Override
            public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<User_Account_Model> call, Throwable t) {

            }
        }));
    }
    else
    {
        progressDialog.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle(Html.fromHtml("<font color='#ff0000'>REGISTER FAILED</font>")).setMessage("password and confirm password did not match")
                .setCancelable(false)
                .setNegativeButton("Ok", null).create().show();
    }

}
</code>```

my format is the same as the tutorial except I have 2 parameters. I hope you could help me explain this logcat because I'm having a hard time understanding it since I'm new to this Retrofit library. Thank you so much guys.

答:
Can you paste User_Account_Model.class here

Have you add in app gradle file

```<code>compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
</code>```

Title: Retrofit Unable to create call adapter

Body:
I followed the format from the tutorial in inserting data to database using Retrofit Library. The logcat shows the error Unable to create call adapter for retrofit2.Call<dagger.com.japorms.model.User_Account_Model> for method APIService.registerUser

Here is my APIService Interface:

    public interface APIService {

    @FormUrlEncoded
    @POST("test_db/register.php")
    Call<User_Account_Model> registerUser(@Field("email") String email, @Field("password") String password);
}

Here is the Method:

 public void registerUser(){
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Registering Account");
    progressDialog.setMessage("Please Wait ...");
    progressDialog.setCancelable(false);
    progressDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.73:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    APIService service = retrofit.create(APIService.class);

    User_Account_Model user_account_model = new User_Account_Model();
    user_account_model.email = reg_email_et.getText().toString();
    user_account_model.password = reg_pass_et.getText().toString();

    String conf_pass = reg_conf_pass_et.getText().toString();

    if(user_account_model.password.equals(conf_pass)){

        Call<User_Account_Model> call = service.registerUser(user_account_model.email,user_account_model.password);
        call.enqueue((new Callback<User_Account_Model>() {
            @Override
            public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<User_Account_Model> call, Throwable t) {

            }
        }));
    }
    else
    {
        progressDialog.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle(Html.fromHtml("REGISTER FAILED")).setMessage("password and confirm password did not match")
                .setCancelable(false)
                .setNegativeButton("Ok", null).create().show();
    }

}

my format is the same as the tutorial except I have 2 parameters. I hope you could help me explain this logcat because I'm having a hard time understanding it since I'm new to this Retrofit library. Thank you so much guys.

Body:
Can you paste User_Account_Model.class here

Have you add in app gradle file

compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'


问:
docker-compose unsupported config for services
I am using below version of docker and docker-compose -

```<code>Docker version 17.03.1-ce, build c6d412e

docker-compose version 1.11.2, build dfed245
</code>```

I still face issues with -

```<code>ERROR: The Compose file './docker-compose.yml' is invalid because:
Unsupported config option for services.web: 'version'
</code>```

below is my docker file -

```<code>version: '2'
services:
  web:
    build: .
    ports:
      - "80:80"
      - "443:443"
    links:
      - memache:memcahced
      - solr:solr
      - dev_mysql:dev_mysql
    container_name: xyz
    hostname: XYZ
    image: XYZ/mono
    version: latest
    privileged: true
 ...
 ...
</code>```

Need some assistance.

答: As already some people pointed out, your indentation is broken. You can verify your docker-compose YAML files with docker-compose config. This checks docker-compose.yml. If you want to check a different YAML, you can specify it with -f, e.g. docker-compose -f docker-compose.prod.yml config

Body:
I am using below version of docker and docker-compose -

Docker version 17.03.1-ce, build c6d412e

docker-compose version 1.11.2, build dfed245

I still face issues with -

ERROR: The Compose file './docker-compose.yml' is invalid because:
Unsupported config option for services.web: 'version'

below is my docker file -

version: '2'
services:
  web:
    build: .
    ports:
      - "80:80"
      - "443:443"
    links:
      - memache:memcahced
      - solr:solr
      - dev_mysql:dev_mysql
    container_name: xyz
    hostname: XYZ
    image: XYZ/mono
    version: latest
    privileged: true
 ...
 ...

Need some assistance.


问:
Tkinter Label image setting won´t work
I've been learning how to use Tkinter from scratch and while I try to set a simple Label widget in a frame:

```<code>from Tkinter import *
from ttk import *

root = Tk()
root.title("Practice")

mainW = LabelFrame(root, text = "Main info")
mainW.grid()

image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
image.grid(column = 0, row = 0)

codeEntry = Entry(mainW, text = "User Code")
codeEntry.grid(column = 1, row = 0)

root.mainloop()
</code>```

I'm getting the following error:

```<code>Traceback (most recent call last):
  File "Tutorial.py", line 10, in <module>
    image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
  File "C:\Python27\lib\lib-tk\ttk.py", line 757, in __init__
Widget.__init__(self, master, "ttk::label", kw)
  File "C:\Python27\lib\lib-tk\ttk.py", line 555, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image specification must contain an odd number of elements
</code>```

I've checked the image format, the route, etc. And now I don't really know what can be causing me trouble.

答:
image

  The image to display in the widget. The value should be a
  PhotoImage, BitmapImage, or a compatible object. If specified, this
  takes precedence over the text and bitmap options. (image/Image)

Right now you are just passing a string for image option of label. You need something like,

```<code>photo = PhotoImage(file="image.gif")
label = Label(..., image=photo)
label.photo = photo  #reference keeping is important when working with images
</code>```

Right now, since you are using PNG image, you need to install and use Python Imaging Library (PIL) though. For more info, you can read Photo Image section from effbot.

Title: Tkinter Label image setting won´t work

Body:
I've been learning how to use Tkinter from scratch and while I try to set a simple Label widget in a frame:

from Tkinter import *
from ttk import *

root = Tk()
root.title("Practice")

mainW = LabelFrame(root, text = "Main info")
mainW.grid()

image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
image.grid(column = 0, row = 0)

codeEntry = Entry(mainW, text = "User Code")
codeEntry.grid(column = 1, row = 0)

root.mainloop()

I'm getting the following error:

Traceback (most recent call last):
  File "Tutorial.py", line 10, in <module>
    image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
  File "C:\Python27\lib\lib-tk\ttk.py", line 757, in __init__
Widget.__init__(self, master, "ttk::label", kw)
  File "C:\Python27\lib\lib-tk\ttk.py", line 555, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image specification must contain an odd number of elements

I've checked the image format, the route, etc. And now I don't really know what can be causing me trouble.

Body:
image

  The image to display in the widget. The value should be a
  PhotoImage, BitmapImage, or a compatible object. If specified, this
  takes precedence over the text and bitmap options. (image/Image)

Right now you are just passing a string for image option of label. You need something like,

photo = PhotoImage(file="image.gif")
label = Label(..., image=photo)
label.photo = photo  #reference keeping is important when working with images

Right now, since you are using PNG image, you need to install and use Python Imaging Library (PIL) though. For more info, you can read Photo Image section from effbot.


问:
Height issue with elements in a row using flexbox and scrolling
I have a couple of element which are positioned horizontally, but they are taller than the parent, meeaning they scroll. It looks like this

Although the scroll behaviour is correct, the content of the first block overflows.

The HTML looks like this

```<code><section>
    <div> <!-- very long content --> </div>
    <div>b</div>
    ....
</section>
</code>```

CSS:

```<code>section {
    display: flex;
    border: 2px solid red;
    height: 100px;
    align-items: stretch;
    overflow:auto;
}

div {
    background-color: green;
    margin: 5px;
    flex: 1;
}
</code>```

DEMO

As you can see in the demo, the element with the green background color is not tall enough to fit all the content. How can this be achieved ? It would be nice if all divs have the same height, is that possible?

答:
For all to have the same height, add a wrapper between the section and the div items and let it be the flex container.

Updated fiddle

Stack snippet

section {
  border: 2px solid red;
  height: 100px;
  overflow: auto;
}

section > div {
  display: flex;
}

section > div > div {
  flex: 1;
  margin: 5px;
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div>
    <div>a ge g er g er gerge rgera ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er
      gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgergg</div>
    <div>b</div>
    <div>c</div>
    <div>d</div>
    <div>e</div>
    <div>f</div>
  </div>
</section></code>```

For only the overflowed element to maintain background color on the overflowing part, add an extra inner wrapper to each item and let it inherit the background color.

Updated fiddle

Stack snippet

section {
  display: flex;
  border: 2px solid red;
  height: 100px;
  overflow: auto;
}

section > div {
  flex: 1;
  margin: 5px;
  background-color: green;
}

section > div > div {
  background-color: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div>
    <div>a ge g er g er gerge rgera ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er
      gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgergg</div>
  </div>
  <div>
    <div>b</div>
  </div>
  <div>
    <div>c</div>
  </div>
  <div>
    <div>d</div>
  </div>
  <div>
    <div>e</div>
  </div>
  <div>
    <div>f</div>
  </div>
</section></code>```

Body:
I have a couple of element which are positioned horizontally, but they are taller than the parent, meeaning they scroll. It looks like this

Although the scroll behaviour is correct, the content of the first block overflows.

The HTML looks like this

b

    ....

CSS:

section {
    display: flex;
    border: 2px solid red;
    height: 100px;
    align-items: stretch;
    overflow:auto;
}

div {
    background-color: green;
    margin: 5px;
    flex: 1;
}

DEMO

As you can see in the demo, the element with the green background color is not tall enough to fit all the content. How can this be achieved ? It would be nice if all divs have the same height, is that possible?

Body:
For all to have the same height, add a wrapper between the section and the div items and let it be the flex container.

Updated fiddle

Stack snippet

section {
  border: 2px solid red;
  height: 100px;
  overflow: auto;
}

section > div {
  display: flex;
}

section > div > div {
  flex: 1;
  margin: 5px;
  background-color: green;
}

<section>
  <div>
    <div>a ge g er g er gerge rgera ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er
      gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgergg</div>
    <div>b</div>
    <div>c</div>
    <div>d</div>
    <div>e</div>
    <div>f</div>
  </div>
</section>

For only the overflowed element to maintain background color on the overflowing part, add an extra inner wrapper to each item and let it inherit the background color.

Updated fiddle

Stack snippet

section {
  display: flex;
  border: 2px solid red;
  height: 100px;
  overflow: auto;
}

section > div {
  flex: 1;
  margin: 5px;
  background-color: green;
}

section > div > div {
  background-color: inherit;
}

<section>
  <div>
    <div>a ge g er g er gerge rgera ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er
      gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgerga ge g er g er gerge rgergg</div>
  </div>
  <div>
    <div>b</div>
  </div>
  <div>
    <div>c</div>
  </div>
  <div>
    <div>d</div>
  </div>
  <div>
    <div>e</div>
  </div>
  <div>
    <div>f</div>
  </div>
</section>


问:
Datadog count metric dropping with multiple containers
I am incrementing a Datadog counter in python:

```<code>from datadog import initialize
from datadog import ThreadStats
stats.increment('api.request_count', tags=['environment:' + environment])
</code>```

And have set the metric type to "count" and the unit to "requests per none" in the metadata for the metric.

The code runs in a docker container on a kubernetes node in a Container Engine in Google Cloud... I have docker-dd-agent (https://github.com/DataDog/docker-dd-agent) running on each node.

I can move the container to any node and it logs around 200 requests per minute. But as soon as I scale it up and launch a second container, it only logs around 100 requests per minute. If I scale down to one container again, it spikes to 200 rpm again:

What could be causing the requests to drop or get overwritten from other pods?

答:
In the python script I was initializing with an api key:

```<code>from datadog import api
from datadog import initialize
from datadog import statsd
options = {
    'api_key':'#######'
}

initialize(**options)
</code>```

And sending some events

```<code>api.Event.create(title=title, text=text, tags=tags)
</code>```

When I changed it to initialize like this, it started working with the dd-agent:

```<code>initialize(statsd_use_default_route=True)
</code>```

I didn't need the link command (--link dogstatsd:dogstastd).

With that setup it now works in the staging environment, but not in production. :/

Body:
I am incrementing a Datadog counter in python:

from datadog import initialize
from datadog import ThreadStats
stats.increment('api.request_count', tags=['environment:' + environment])

And have set the metric type to "count" and the unit to "requests per none" in the metadata for the metric.

The code runs in a docker container on a kubernetes node in a Container Engine in Google Cloud... I have docker-dd-agent (https://github.com/DataDog/docker-dd-agent) running on each node.

I can move the container to any node and it logs around 200 requests per minute. But as soon as I scale it up and launch a second container, it only logs around 100 requests per minute. If I scale down to one container again, it spikes to 200 rpm again:

What could be causing the requests to drop or get overwritten from other pods?

Body:
In the python script I was initializing with an api key:

from datadog import api
from datadog import initialize
from datadog import statsd
options = {
    'api_key':'#######'
}

initialize(**options)

And sending some events

api.Event.create(title=title, text=text, tags=tags)

When I changed it to initialize like this, it started working with the dd-agent:

initialize(statsd_use_default_route=True)

I didn't need the link command (--link dogstatsd:dogstastd).

With that setup it now works in the staging environment, but not in production. :/


问:
JSONexception while fetching JSONArray JSONObject
Getting JSON Exception while fetching json response from server.I have tried many solutions given on stackoverflow but thats not working.Below is my code for sending parameters to the sever and fetching json.Please help me guys.Any help will be appreciated.
Thanks

JSON Response from server:

Note:"upload" is an JSONarray .

```<code>  {
        "code": 200,
        "upload": {
        "Booking": {
        "id": "17",
        "contributor_id": "16",
        "table_of_content_id": "1",
        "composition_id": "12",
        "completion": "2017-05-20",
        "approved": null,
        "cdn_id": null,
        "secret_token": null,
        "uploaded_on": null,
        "created": "2017-05-09 14:41:49",
        "modified": "2017-05-09 14:41:49"
        },
        "TableOfContent": {
        "id": "1",
        "name": "গোরা",
        "category_id": "1",
        "language_id": "1",
        "created": "2016-03-09 03:39:01",
        "modified": "2016-03-09 14:39:01"
        }
        }
        }
</code>```

This is how i am trying to do it.

```<code>public void forwardtoOurServer() {
        JSONObject jsonObject=null;
        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            JSONArray obj = json.getJSONArray("upload");
                            Log.d(TAG, "obj Response Check :" + obj);
                            for (int i = 0; i < obj.length(); i++) {

                                JSONObject jsonObject = obj.getJSONObject(i);
                                Log.d(TAG, "jsonObject Response Check :" + jsonObject);
                                JSONObject bookings = obj.getJSONObject(Integer.parseInt("Booking"));

//                                int id = jsonObject.getInt("id");
//
//                                String type = jsonObject.getString("type");

                                // retrieve the values like this so on..

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Booking][id]",bookingId);
                params.put("data[Booking][contributor_id]",contributor_id);
                params.put("data[Booking][table_of_content_id]",tocId);
                params.put("data[Booking][cdn_id]",vs_cdn_id);
                params.put("data[Booking][secret_token]",secret_token);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Booking][uploaded_on]",strDate);
                Log.d(TAG, "Params :" + params);
                return params;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };

        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }
</code>```

Log:

```<code>06-07 12:44:18.865 13701-13903/com.showhow2.www.thetagoreproject D/Null: Params :{data[Booking][cdn_id]=326929293, data[Booking][table_of_content_id]=1, data[Booking][id]=16, data[Booking][secret_token]=s-0DT7x, data[Booking][contributor_id]=16, data[Booking][uploaded_on]=2017-06-07T07:14:18Z}
06-07 12:44:20.629 13701-13701/com.showhow2.www.thetagoreproject D/Null: Audio Upload Response Check :{"code":200,"upload":{"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"\u0997\u09cb\u09b0\u09be","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"\u09ac\u09bf\u09a8\u09df \u0993 \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf \u09b9\u0987\u09a4\u09c7 \u09b0\u09be\u09b8\u09cd\u09a4\u09be\u09df \u09ac\u09be\u09b9\u09bf\u09b0 \u09b9\u0987\u09b2\u09c7 \u09ac\u09bf\u09a8\u09df \u0995\u09b9\u09bf\u09b2, "\u0997\u09cb\u09b0\u09be, \u098f\u0995\u099f\u09c1 \u0986\u09b8\u09cd\u09a4\u09c7 \u0986\u09b8\u09cd\u09a4\u09c7 \u099a\u09b2\u09cb \u09ad\u09be\u0987-- \u09a4\u09cb\u09ae\u09be\u09b0 \u09aa\u09be \u09a6\u09c1\u099f\u09cb \u0986\u09ae\u09be\u09a6\u09c7\u09b0 \u099a\u09c7\u09df\u09c7 \u0985\u09a8\u09c7\u0995 \u09ac\u09dc\u09cb-- \u0993\u09b0 \u099a\u09be\u09b2\u099f\u09be \u098f\u0995\u099f\u09c1 \u0996\u09be\u099f\u09cb \u09a8\u09be \u0995\u09b0\u09b2\u09c7 \u09a4\u09cb\u09ae\u09be\u09b0 \u09b8\u0999\u09cd\u0997\u09c7 \u09af\u09c7\u09a4\u09c7 \u0986\u09ae\u09b0\u09be \u09b9\u09be\u0981\u09aa\u09bf\u09df\u09c7 \u09aa\u09dc\u09bf\u0964"\n \u0997\u09cb\u09b0\u09be \u0995\u09b9\u09bf\u09b2, "\u0986\u09ae\u09bf \u098f\u0995\u09b2\u09be\u0987 \u09af\u09c7\u09a4\u09c7 \u099a\u09be\u0987, \u0986\u09ae\u09be\u09b0 \u0986\u099c \u0985\u09a8\u09c7\u0995 \u0995\u09a5\u09be \u09ad\u09be\u09ac\u09ac\u09be\u09b0 \u0986\u099b\u09c7\u0964"\n \u09ac\u09b2\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09b8\u09cd\u09ac\u09be\u09ad\u09be\u09ac\u09bf\u0995 \u09a6\u09cd\u09b0\u09c1\u09a4\u0997\u09a4\u09bf\u09a4\u09c7 \u09b8\u09c7 \u09ac\u09c7\u0997\u09c7 \u099a\u09b2\u09bf\u09df\u09be \u0997\u09c7\u09b2\u0964\n \u09ac\u09bf\u09a8\u09df\u09c7\u09b0 \u09ae\u09a8\u09c7 \u0986\u0998\u09be\u09a4 \u09b2\u09be\u0997\u09bf\u09b2\u0964 \u09b8\u09c7 \u0986\u099c \u0997\u09cb\u09b0\u09be\u09b0 \u09ac\u09bf\u09b0\u09c1\u09a6\u09cd\u09a7\u09c7 \u09ac\u09bf\u09a6\u09cd\u09b0\u09cb\u09b9 \u0995\u09b0\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09a8\u09bf\u09df\u09ae \u09ad\u0999\u09cd\u0997 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7\u0964 \u09b8\u09c7 \u09b8\u09ae\u09cd\u09ac\u09a8\u09cd\u09a7\u09c7 \u0997\u09cb\u09b0\u09be\u09b0 \u0995\u09be\u099b\u09c7 \u09a4\u09bf\u09b0\u09b8\u09cd\u0995\u09be\u09b0 \u09ad\u09cb\u0997 \u0995\u09b0\u09bf\u09b2\u09c7 \u09b8\u09c7 \u0996\u09c1\u09b6\u09bf \u09b9\u0987\u09a4\u0964 \u098f\u0995\u099f\u09be \u099d\u09dc \u09b9\u0987\u09df\u09be \u0997\u09c7\u09b2\u09c7\u0987 \u09a4\u09be\u09b9\u09be\u09a6\u09c7\u09b0 \u099a\u09bf\u09b0\u09a6\u09bf\u09a8\u09c7\u09b0 \u09ac\u09a8\u09cd\u09a7\u09c1\u09a4\u09cd\u09ac\u09c7\u09b0 \u0986\u0995\u09be\u09b6 \u09b9\u0987\u09a4\u09c7 \u0997\u09c1\u09ae\u099f \u0995\u09be\u099f\u09bf\u09df\u09be \u09af\u09be\u0987\u09a4 \u098f\u09ac\u0982 \u09b8\u09c7 \u09b9\u09be\u0981\u09aa \u099b\u09be\u09dc\u09bf\u09df\u09be \u09ac\u09be\u0981\u099a\u09bf\u09a4\u0964\n \u09a4\u09be\u09b9\u09be \u099b\u09be\u09dc\u09be \u0986\u09b0-\u098f\u0995\u099f\u09be \u0995\u09a5\u09be \u09a4\u09be\u09b9\u09be\u0995\u09c7 \u09aa\u09c0\u09dc\u09be \u09a6\u09bf\u09a4\u09c7\u099b\u09bf\u09b2\u0964 \u0986\u099c \u09b9\u09a0\u09be\u09ce \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf\u09a4\u09c7 \u09aa\u09cd\u09b0\u09a5\u09ae \u0986\u09b8\u09bf\u09df\u09be\u0987 \u09ac\u09bf\u09a8\u09df\u0995\u09c7 \u09b8\u09c7\u0996\u09be\u09a8\u09c7 \u09ac\u09a8\u09cd\u09a7\u09c1\u09ad\u09be\u09ac\u09c7 \u09ac\u09b8\u09bf\u09df\u09be \u09a5\u09be\u0995\u09bf\u09a4\u09c7 \u09a6\u09c7\u0996\u09bf\u09df\u09be \u09a8\u09bf\u09b6\u09cd\u099a\u09df\u0987 \u09ae\u09a8\u09c7 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7 \u09ac\u09bf\u09a8\u09df \u098f \u09ac\u09be\u
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err: org.json.JSONException: Value {"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"গোরা","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"বিনয় ও গোরা পরেশের বাড়ি হইতে রাস্তায় বাহির হইলে বিনয় কহিল, "গোরা, একটু আস্তে আস্তে চলো ভাই-- তোমার পা দুটো আমাদের চেয়ে অনেক বড়ো-- ওর চালটা একটু খাটো না করলে তোমার সঙ্গে যেতে আমরা হাঁপিয়ে পড়ি।"\n গোরা কহিল, "আমি একলাই যেতে চাই, আমার আজ অনেক কথা ভাববার আছে।"\n বলিয়া তাহার স্বাভাবিক দ্রুতগতিতে সে বেগে চলিয়া গেল।\n বিনয়ের মনে আঘাত লাগিল। সে আজ গোরার বিরুদ্ধে বিদ্রোহ করিয়া তাহার নিয়ম ভঙ্গ করিয়াছে। সে সম্বন্ধে গোরার কাছে তিরস্কার ভোগ করিলে সে খুশি হইত। একটা ঝড় হইয়া গেলেই তাহাদের চিরদিনের বন্ধুত্বের আকাশ হইতে গুমট কাটিয়া যাইত এবং সে হাঁপ ছাড়িয়া বাঁচিত।\n তাহা ছাড়া আর-একটা কথা তাহাকে পীড়া দিতেছিল। আজ হঠাৎ গোরা পরেশের বাড়িতে প্রথম আসিয়াই বিনয়কে সেখানে বন্ধুভাবে বসিয়া থাকিতে দেখিয়া নিশ্চয়ই মনে করিয়াছে বিনয় এ বাড়িতে সর্বদাই যাতায়াত করে। অবশ্য, যাতায়াত করিলে যে কোনো অপরাধ আছে তাহা নয়; গোরা যাহাই বলুক পরেশবাবুর সুশিক্ষিত পরিবারের সঙ্গে অন্তরঙ্গভাবে পরিচিত হইবার সুযোগ পাওয়া বিনয় একটা বিশেষ লাভ বলিয়া গণ্য করিতেছে; ইঁহাদের সঙ্গে মেশামেশি করাতে গোরা যদি কোনো দোষ দেখে তবে সেটা তাহার নিতান্ত গোঁড়ামি; কিন্তু পূর্বের কথাবার্তায় গোরা নাকি জানিয়াছে যে বিনয় পরেশবাবুর বাড়িতে যাওয়া-আসা করে না, আজ সহসা তাহার মনে হইতে পারে যে সে কথাটা সত্য নয়। বিশেষত বরদাসুন্দরী তাহাকে বিশেষ করিয়া ঘরে ডাকিয়া লইয়া গেলেন, সেখানে তাঁহার মেয়েদের সঙ্গে তাহার আলাপ হইতে লাগিল-- গোরার তীক্ষ্ণ লক্ষ হইতে ইহা এড়াইয়া যায় নাই। মেয়েদের সঙ্গে এইরূপ মেলামেশায় ও বরদাসুন্দরীর আত্মীয়তায় মনে মনে বিনয় ভার�
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:704)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:694)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Looper.loop(Looper.java:148)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Now you are using JSONArray obj = json.getJSONArray("upload");  but "upload" is jsonObject.

In your java code use JSONObject bookings = obj.getJSONObject("upload").getJSONObject("Booking");

Body:
Getting JSON Exception while fetching json response from server.I have tried many solutions given on stackoverflow but thats not working.Below is my code for sending parameters to the sever and fetching json.Please help me guys.Any help will be appreciated.
Thanks

JSON Response from server:

Note:"upload" is an JSONarray .

  {
        "code": 200,
        "upload": {
        "Booking": {
        "id": "17",
        "contributor_id": "16",
        "table_of_content_id": "1",
        "composition_id": "12",
        "completion": "2017-05-20",
        "approved": null,
        "cdn_id": null,
        "secret_token": null,
        "uploaded_on": null,
        "created": "2017-05-09 14:41:49",
        "modified": "2017-05-09 14:41:49"
        },
        "TableOfContent": {
        "id": "1",
        "name": "গোরা",
        "category_id": "1",
        "language_id": "1",
        "created": "2016-03-09 03:39:01",
        "modified": "2016-03-09 14:39:01"
        }
        }
        }

This is how i am trying to do it.

public void forwardtoOurServer() {
        JSONObject jsonObject=null;
        String tag_string_req = "req_login";
        StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Audio Upload Response Check :" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            JSONArray obj = json.getJSONArray("upload");
                            Log.d(TAG, "obj Response Check :" + obj);
                            for (int i = 0; i < obj.length(); i++) {

                                JSONObject jsonObject = obj.getJSONObject(i);
                                Log.d(TAG, "jsonObject Response Check :" + jsonObject);
                                JSONObject bookings = obj.getJSONObject(Integer.parseInt("Booking"));

//                                int id = jsonObject.getInt("id");
//
//                                String type = jsonObject.getString("type");

                                // retrieve the values like this so on..

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error Response Check :" + error);

                    }
                }) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("data[Booking][id]",bookingId);
                params.put("data[Booking][contributor_id]",contributor_id);
                params.put("data[Booking][table_of_content_id]",tocId);
                params.put("data[Booking][cdn_id]",vs_cdn_id);
                params.put("data[Booking][secret_token]",secret_token);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date now = new Date();
                String strDate = sdf.format(now);
                params.put("data[Booking][uploaded_on]",strDate);
                Log.d(TAG, "Params :" + params);
                return params;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("UUID", device_uuid);
                headers.put("APPID", "2A192A0C22");
                headers.put("USERID", "1");
                headers.put("PLATFORM", "Andriod");
                headers.put("APP_REQUEST", "1");
                headers.put("PLATFORMVERSION",androidOS);
                return headers;
            }

        };

        AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);

    }

Log:

06-07 12:44:18.865 13701-13903/com.showhow2.www.thetagoreproject D/Null: Params :{data[Booking][cdn_id]=326929293, data[Booking][table_of_content_id]=1, data[Booking][id]=16, data[Booking][secret_token]=s-0DT7x, data[Booking][contributor_id]=16, data[Booking][uploaded_on]=2017-06-07T07:14:18Z}
06-07 12:44:20.629 13701-13701/com.showhow2.www.thetagoreproject D/Null: Audio Upload Response Check :{"code":200,"upload":{"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"\u0997\u09cb\u09b0\u09be","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"\u09ac\u09bf\u09a8\u09df \u0993 \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf \u09b9\u0987\u09a4\u09c7 \u09b0\u09be\u09b8\u09cd\u09a4\u09be\u09df \u09ac\u09be\u09b9\u09bf\u09b0 \u09b9\u0987\u09b2\u09c7 \u09ac\u09bf\u09a8\u09df \u0995\u09b9\u09bf\u09b2, "\u0997\u09cb\u09b0\u09be, \u098f\u0995\u099f\u09c1 \u0986\u09b8\u09cd\u09a4\u09c7 \u0986\u09b8\u09cd\u09a4\u09c7 \u099a\u09b2\u09cb \u09ad\u09be\u0987-- \u09a4\u09cb\u09ae\u09be\u09b0 \u09aa\u09be \u09a6\u09c1\u099f\u09cb \u0986\u09ae\u09be\u09a6\u09c7\u09b0 \u099a\u09c7\u09df\u09c7 \u0985\u09a8\u09c7\u0995 \u09ac\u09dc\u09cb-- \u0993\u09b0 \u099a\u09be\u09b2\u099f\u09be \u098f\u0995\u099f\u09c1 \u0996\u09be\u099f\u09cb \u09a8\u09be \u0995\u09b0\u09b2\u09c7 \u09a4\u09cb\u09ae\u09be\u09b0 \u09b8\u0999\u09cd\u0997\u09c7 \u09af\u09c7\u09a4\u09c7 \u0986\u09ae\u09b0\u09be \u09b9\u09be\u0981\u09aa\u09bf\u09df\u09c7 \u09aa\u09dc\u09bf\u0964"\n \u0997\u09cb\u09b0\u09be \u0995\u09b9\u09bf\u09b2, "\u0986\u09ae\u09bf \u098f\u0995\u09b2\u09be\u0987 \u09af\u09c7\u09a4\u09c7 \u099a\u09be\u0987, \u0986\u09ae\u09be\u09b0 \u0986\u099c \u0985\u09a8\u09c7\u0995 \u0995\u09a5\u09be \u09ad\u09be\u09ac\u09ac\u09be\u09b0 \u0986\u099b\u09c7\u0964"\n \u09ac\u09b2\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09b8\u09cd\u09ac\u09be\u09ad\u09be\u09ac\u09bf\u0995 \u09a6\u09cd\u09b0\u09c1\u09a4\u0997\u09a4\u09bf\u09a4\u09c7 \u09b8\u09c7 \u09ac\u09c7\u0997\u09c7 \u099a\u09b2\u09bf\u09df\u09be \u0997\u09c7\u09b2\u0964\n \u09ac\u09bf\u09a8\u09df\u09c7\u09b0 \u09ae\u09a8\u09c7 \u0986\u0998\u09be\u09a4 \u09b2\u09be\u0997\u09bf\u09b2\u0964 \u09b8\u09c7 \u0986\u099c \u0997\u09cb\u09b0\u09be\u09b0 \u09ac\u09bf\u09b0\u09c1\u09a6\u09cd\u09a7\u09c7 \u09ac\u09bf\u09a6\u09cd\u09b0\u09cb\u09b9 \u0995\u09b0\u09bf\u09df\u09be \u09a4\u09be\u09b9\u09be\u09b0 \u09a8\u09bf\u09df\u09ae \u09ad\u0999\u09cd\u0997 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7\u0964 \u09b8\u09c7 \u09b8\u09ae\u09cd\u09ac\u09a8\u09cd\u09a7\u09c7 \u0997\u09cb\u09b0\u09be\u09b0 \u0995\u09be\u099b\u09c7 \u09a4\u09bf\u09b0\u09b8\u09cd\u0995\u09be\u09b0 \u09ad\u09cb\u0997 \u0995\u09b0\u09bf\u09b2\u09c7 \u09b8\u09c7 \u0996\u09c1\u09b6\u09bf \u09b9\u0987\u09a4\u0964 \u098f\u0995\u099f\u09be \u099d\u09dc \u09b9\u0987\u09df\u09be \u0997\u09c7\u09b2\u09c7\u0987 \u09a4\u09be\u09b9\u09be\u09a6\u09c7\u09b0 \u099a\u09bf\u09b0\u09a6\u09bf\u09a8\u09c7\u09b0 \u09ac\u09a8\u09cd\u09a7\u09c1\u09a4\u09cd\u09ac\u09c7\u09b0 \u0986\u0995\u09be\u09b6 \u09b9\u0987\u09a4\u09c7 \u0997\u09c1\u09ae\u099f \u0995\u09be\u099f\u09bf\u09df\u09be \u09af\u09be\u0987\u09a4 \u098f\u09ac\u0982 \u09b8\u09c7 \u09b9\u09be\u0981\u09aa \u099b\u09be\u09dc\u09bf\u09df\u09be \u09ac\u09be\u0981\u099a\u09bf\u09a4\u0964\n \u09a4\u09be\u09b9\u09be \u099b\u09be\u09dc\u09be \u0986\u09b0-\u098f\u0995\u099f\u09be \u0995\u09a5\u09be \u09a4\u09be\u09b9\u09be\u0995\u09c7 \u09aa\u09c0\u09dc\u09be \u09a6\u09bf\u09a4\u09c7\u099b\u09bf\u09b2\u0964 \u0986\u099c \u09b9\u09a0\u09be\u09ce \u0997\u09cb\u09b0\u09be \u09aa\u09b0\u09c7\u09b6\u09c7\u09b0 \u09ac\u09be\u09dc\u09bf\u09a4\u09c7 \u09aa\u09cd\u09b0\u09a5\u09ae \u0986\u09b8\u09bf\u09df\u09be\u0987 \u09ac\u09bf\u09a8\u09df\u0995\u09c7 \u09b8\u09c7\u0996\u09be\u09a8\u09c7 \u09ac\u09a8\u09cd\u09a7\u09c1\u09ad\u09be\u09ac\u09c7 \u09ac\u09b8\u09bf\u09df\u09be \u09a5\u09be\u0995\u09bf\u09a4\u09c7 \u09a6\u09c7\u0996\u09bf\u09df\u09be \u09a8\u09bf\u09b6\u09cd\u099a\u09df\u0987 \u09ae\u09a8\u09c7 \u0995\u09b0\u09bf\u09df\u09be\u099b\u09c7 \u09ac\u09bf\u09a8\u09df \u098f \u09ac\u09be\u
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err: org.json.JSONException: Value {"Booking":{"id":"17","contributor_id":"16","table_of_content_id":"1","composition_id":"12","completion":"2017-05-20","approved":null,"cdn_id":null,"secret_token":null,"uploaded_on":null,"created":"2017-05-09 14:41:49","modified":"2017-05-09 14:41:49"},"TableOfContent":{"id":"1","name":"গোরা","category_id":"1","language_id":"1","created":"2016-03-09 03:39:01","modified":"2016-03-09 14:39:01"},"Composition":{"id":"12","content":"বিনয় ও গোরা পরেশের বাড়ি হইতে রাস্তায় বাহির হইলে বিনয় কহিল, "গোরা, একটু আস্তে আস্তে চলো ভাই-- তোমার পা দুটো আমাদের চেয়ে অনেক বড়ো-- ওর চালটা একটু খাটো না করলে তোমার সঙ্গে যেতে আমরা হাঁপিয়ে পড়ি।"\n গোরা কহিল, "আমি একলাই যেতে চাই, আমার আজ অনেক কথা ভাববার আছে।"\n বলিয়া তাহার স্বাভাবিক দ্রুতগতিতে সে বেগে চলিয়া গেল।\n বিনয়ের মনে আঘাত লাগিল। সে আজ গোরার বিরুদ্ধে বিদ্রোহ করিয়া তাহার নিয়ম ভঙ্গ করিয়াছে। সে সম্বন্ধে গোরার কাছে তিরস্কার ভোগ করিলে সে খুশি হইত। একটা ঝড় হইয়া গেলেই তাহাদের চিরদিনের বন্ধুত্বের আকাশ হইতে গুমট কাটিয়া যাইত এবং সে হাঁপ ছাড়িয়া বাঁচিত।\n তাহা ছাড়া আর-একটা কথা তাহাকে পীড়া দিতেছিল। আজ হঠাৎ গোরা পরেশের বাড়িতে প্রথম আসিয়াই বিনয়কে সেখানে বন্ধুভাবে বসিয়া থাকিতে দেখিয়া নিশ্চয়ই মনে করিয়াছে বিনয় এ বাড়িতে সর্বদাই যাতায়াত করে। অবশ্য, যাতায়াত করিলে যে কোনো অপরাধ আছে তাহা নয়; গোরা যাহাই বলুক পরেশবাবুর সুশিক্ষিত পরিবারের সঙ্গে অন্তরঙ্গভাবে পরিচিত হইবার সুযোগ পাওয়া বিনয় একটা বিশেষ লাভ বলিয়া গণ্য করিতেছে; ইঁহাদের সঙ্গে মেশামেশি করাতে গোরা যদি কোনো দোষ দেখে তবে সেটা তাহার নিতান্ত গোঁড়ামি; কিন্তু পূর্বের কথাবার্তায় গোরা নাকি জানিয়াছে যে বিনয় পরেশবাবুর বাড়িতে যাওয়া-আসা করে না, আজ সহসা তাহার মনে হইতে পারে যে সে কথাটা সত্য নয়। বিশেষত বরদাসুন্দরী তাহাকে বিশেষ করিয়া ঘরে ডাকিয়া লইয়া গেলেন, সেখানে তাঁহার মেয়েদের সঙ্গে তাহার আলাপ হইতে লাগিল-- গোরার তীক্ষ্ণ লক্ষ হইতে ইহা এড়াইয়া যায় নাই। মেয়েদের সঙ্গে এইরূপ মেলামেশায় ও বরদাসুন্দরীর আত্মীয়তায় মনে মনে বিনয় ভার�
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:704)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.showhow2.www.thetagoreproject.RecordComposition$16.onResponse(RecordComposition.java:694)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.os.Looper.loop(Looper.java:148)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
06-07 12:44:20.663 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-07 12:44:20.664 13701-13701/com.showhow2.www.thetagoreproject W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


问:
Does trend suggest server-side web programming model (e.g. ASP.NET) being replaced by JavaScript/Ajax?
ASP.NET server controls has a few categories, for example, normal ones e.g. TextBox, Button which can be done in HTML/JS; Validation controls: can be done in JS; Login controls: I have seen them implemented in JS. Data bound controls: not sure, but maybe JS can work directly with databases, implementing controls like photo slider.

So in the time span of next 5-10 years, will server-side web programming model fall out of mainstream and be replaced by JS/Ajax that interacts directly with databases?

答:
So in the time span of next 5-10 years, will server-side web programming model fall out of mainstream and be replaced by JS/Ajax that interacts directly with databases?

What's going on is the same thing we always do in computer technology (née in nature), try and find an equilibrium. As bandwidth increases and javascript [process time decreases & feature set increases in ECMAscript spec] then more effects will be pushed to the client, but as @BrianBall points out, you have to have somewhere to keep the data, or it was for naught.

There was a time when we relied on the client to do all the work because network latency was crippling, and we called those fat clients. There was a time when we didn't trust the client to keep any data because we couldn't trust the client to be able to process anything, and we call that thin-client.

We are rapidly approaching an equilibrium again where we rely on the server to do the heavy lifting on somethings, to manage the data, to maintain security, and to stream video or send emails. Everything else is migrating for the most part to the client. I don't see us moving back to a really fat-client anytime in the next ten years, altho I do see the browser becoming more central to our app usage. A truly standard platform on which to build any app.

ContentLicense: CC BY-SA 2.5


问:
ggplot: Error: Aesthetics must be either length 1 or the same as the data (10): x, y, group
I have a small dataset and I want to plot it with a line graph:

```<code> > Gain
     quantile Positives Total_Examples Positive_Prevalence     Lift Cumsum_Positives
 1:     (0, ]         1              1                   1 1.428571        0.1428571
 2: (1.9,2.8]         1              1                   1 1.428571        0.2857143
 3: (2.8,3.7]         1              1                   1 1.428571        0.4285714
 4: (3.7,4.6]         1              1                   1 1.428571        0.5714286
 5: (4.6,5.5]         1              1                   1 1.428571        0.7142857
 6: (5.5,6.4]         1              1                   1 1.428571        0.8571429
 7: (6.4,7.3]         1              1                   1 1.428571        1.0000000
 8: (7.3,8.2]         0              1                   0 0.000000        1.0000000
 9: (8.2,9.1]         0              1                   0 0.000000        1.0000000
10:  (9.1,10]         0              1                   0 0.000000        1.0000000
</code>```

My code is the following:

```<code>    ggplot(Gain ) +
  geom_area(aes(x = quantile, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))
</code>```

However, I get an error message :

```<code>  Error: Aesthetics must be either length 1 or the same as the data (10): x, y, group
</code>```

I have read posts relating to this sort of error and usually the error implies that the variables called within the aesthetics are not present in the original dataframe.  But this is not the case here.

I also tried this code, but it returns the same error message as well:

```<code>Gain$index <- row.names(Gain)

ggplot(Gain ) +
  geom_area(aes(x = index, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))
</code>```

Your advice will be appreciated.

答:
If your aim is to draw a line from (x = 0, y = 0) to (x = 0.9, y = 1), you could also replace geom_line with geom_abline:

```<code>geom_abline(slope = 1/9,
            intercept = -0.109,
            color = "blue",
            size = 2,
            alpha = 0.5) +
</code>```

Body:
I have a small dataset and I want to plot it with a line graph:

 > Gain
     quantile Positives Total_Examples Positive_Prevalence     Lift Cumsum_Positives
 1:     (0, ]         1              1                   1 1.428571        0.1428571
 2: (1.9,2.8]         1              1                   1 1.428571        0.2857143
 3: (2.8,3.7]         1              1                   1 1.428571        0.4285714
 4: (3.7,4.6]         1              1                   1 1.428571        0.5714286
 5: (4.6,5.5]         1              1                   1 1.428571        0.7142857
 6: (5.5,6.4]         1              1                   1 1.428571        0.8571429
 7: (6.4,7.3]         1              1                   1 1.428571        1.0000000
 8: (7.3,8.2]         0              1                   0 0.000000        1.0000000
 9: (8.2,9.1]         0              1                   0 0.000000        1.0000000
10:  (9.1,10]         0              1                   0 0.000000        1.0000000

My code is the following:

    ggplot(Gain ) +
  geom_area(aes(x = quantile, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))

However, I get an error message :

  Error: Aesthetics must be either length 1 or the same as the data (10): x, y, group

I have read posts relating to this sort of error and usually the error implies that the variables called within the aesthetics are not present in the original dataframe.  But this is not the case here.

I also tried this code, but it returns the same error message as well:

Gain$index <- row.names(Gain)

ggplot(Gain ) +
  geom_area(aes(x = index, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))

Your advice will be appreciated.

Body:
If your aim is to draw a line from (x = 0, y = 0) to (x = 0.9, y = 1), you could also replace geom_line with geom_abline:

geom_abline(slope = 1/9,
            intercept = -0.109,
            color = "blue",
            size = 2,
            alpha = 0.5) +


问:
AzCopy - Wildcards In Middle Of Pattern?
Scenario:
-Backups located in Azure storage
-Folder containing >100,000 folders
-Inside of each folder is a file in the following format: MM-DD-YYYY_randomnumber.wav.gz

We need to pull all files from two months (unknown number, likely 30,000-40,000).

Looks like AzCopy is the utility we need to accomplish this.

The following command is how I'd imagine it would work, but am unable to get it to do so:

```<code>AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11-*-2016_*.wav.gz /S
</code>```

The following grabs the parent folder (it's named the same as the files within them, just without the .wav.gz extension), which wouldn't be ideal, but would be workable. However, this would grab files from multiple years:

```<code>AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11 /S
</code>```

I've read the documentation, and it mentions wildcards can be used in some circumstances but not others, but I'm not entirely sure what it's meaning.

Thanks!

答:
No, it's infeasible. Per the document of AzCopy regarding /Pattern option:

If the specified source is a blob container or virtual directory, then wildcards are not applied. If option /S is specified, then AzCopy interprets the specified file pattern as a blob prefix. If option /S is not specified, then AzCopy matches the file pattern against exact blob names.

Body:
Scenario:
-Backups located in Azure storage
-Folder containing >100,000 folders
-Inside of each folder is a file in the following format: MM-DD-YYYY_randomnumber.wav.gz

We need to pull all files from two months (unknown number, likely 30,000-40,000).

Looks like AzCopy is the utility we need to accomplish this.

The following command is how I'd imagine it would work, but am unable to get it to do so:

AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11-*-2016_*.wav.gz /S

The following grabs the parent folder (it's named the same as the files within them, just without the .wav.gz extension), which wouldn't be ideal, but would be workable. However, this would grab files from multiple years:

AzCopy /Source:https://path.to.files/path/to/files /Dest:C:\test /SourceKey:key /Pattern:11 /S

I've read the documentation, and it mentions wildcards can be used in some circumstances but not others, but I'm not entirely sure what it's meaning.

Thanks!


问:
MongoDB search by nested dynamic sub field
Trying to find a way to reach to sub sub field which dynamic sub field in between. Not sure how to reach there. Looking for something like $ used for arrays.

My data structure looks like

```<code>  {
    _id: ObjectId("59355deee13f1a1260f17421"),
    product: {
      shirt: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17422"),
    product: {
      top: {
        color: "red"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17423"),
    product: {
      shoes: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17424"),
    product: {
      belt: {
        color: "brown7"
      }
    }
  },
</code>```

Looking for equivalent of

```<code>db.things.find({product.$.color: "black"})
</code>```

答:
This should work

```<code>db.getCollection('things').find({$where: function() {
for (var field in this.product) {
    if (this.product[field].color == "black") return true;
}
return false;
</code>```

}})

ContentLicense: CC BY-SA 4.0

Body:
Trying to find a way to reach to sub sub field which dynamic sub field in between. Not sure how to reach there. Looking for something like $ used for arrays.

My data structure looks like

  {
    _id: ObjectId("59355deee13f1a1260f17421"),
    product: {
      shirt: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17422"),
    product: {
      top: {
        color: "red"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17423"),
    product: {
      shoes: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17424"),
    product: {
      belt: {
        color: "brown7"
      }
    }
  },

Looking for equivalent of

db.things.find({product.$.color: "black"})

Body:
This should work

db.getCollection('things').find({$where: function() {
for (var field in this.product) {
    if (this.product[field].color == "black") return true;
}
return false;

}})


问:
Query to find the FIRST AND SECOND largest value from a group
i have a query like this:

```<code>SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
</code>```

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

答:
This is a bit old-school but TOP and a subquery will work if you use ORDER BY. Try this:

```<code>SELECT TOP 2
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 (SELECT MAX(st1.some_value) FROM some_table AS st1
  WHERE DATEPART(month,some_date) = DATEPART(month,st1.some_date)) AS max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
ORDER BY DATEPART(month,some_date) DESC
</code>```

That will give you the two rows with the "highest" month values and the added subselect should give you the max from each grouping.

Body:
i have a query like this:

SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

Body:
This is a bit old-school but TOP and a subquery will work if you use ORDER BY. Try this:

SELECT TOP 2
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 (SELECT MAX(st1.some_value) FROM some_table AS st1
  WHERE DATEPART(month,some_date) = DATEPART(month,st1.some_date)) AS max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
ORDER BY DATEPART(month,some_date) DESC

That will give you the two rows with the "highest" month values and the added subselect should give you the max from each grouping.