问:
Getting checked checkbox from database
I have checkboxes displayed in a loop with id's defined as check1, check2, check3 and so on

```<code><input class="single-checkbox" type="checkbox" name="check" id="check<?php
echo $i; ?>">
</code>```

Now I have two variables $chk1 and $chk2 both have values "check1" and "check2"
Is there anyway I could use an 'if' condition with OR gate within

```<code><input class="single-checkbox"...>
</code>```

to compare id with variable and return checked checkboxes 1 and 2.

答:
```<code><input class="single-checkbox" type="checkbox" name="check<?php echo $i; ?> " id="check<?php echo $i; ?>" value="<?php echo $i; ?>">
</code>```

What I have realised is that you need to different names for all your checkboxes.Moreover you have not defined value for checkboxes.So now you will get different value for different checked boxes with different values.

Response to OPs comment:
In order to get the checkboxes pre checked of unchecked you will need to get it from your backend or your database which will be the values true or false corresponding to each index of your loop and put that in your checkbox checked attribute as follow:

```<code><input checked="ValueFromDataBase" >
</code>```

The checkbox will be checked or unchecked based on the value from your database.

Title: Getting checked checkbox from database

Body:
I have checkboxes displayed in a loop with id's defined as check1, check2, check3 and so on

<input class="single-checkbox" type="checkbox" name="check" id="check<?php
echo $i; ?>">

Now I have two variables $chk1 and $chk2 both have values "check1" and "check2"
Is there anyway I could use an 'if' condition with OR gate within

<input class="single-checkbox"...>

to compare id with variable and return checked checkboxes 1 and 2.

Body:
<input class="single-checkbox" type="checkbox" name="check<?php echo $i; ?> " id="check<?php echo $i; ?>" value="<?php echo $i; ?>">

What I have realised is that you need to different names for all your checkboxes.Moreover you have not defined value for checkboxes.So now you will get different value for different checked boxes with different values.

Response to OPs comment:
In order to get the checkboxes pre checked of unchecked you will need to get it from your backend or your database which will be the values true or false corresponding to each index of your loop and put that in your checkbox checked attribute as follow:

<input checked="ValueFromDataBase" >

The checkbox will be checked or unchecked based on the value from your database.


来源: stackexchange

问:
vb.net LINQ LEFT JOIN
I want query LINQ to LEFT JOIN TWO TABLES get results like SQL exactly
(show results like the picture even the row empty yellow line)

My code:

```<code>Dim qJoint = From tSum In lstSUM Group Join tbnk In lstBank On tbnk.ID_BANK Equals tSum.ID_BANK _
   Into tResult = Group From tbnk In tResult.DefaultIfEmpty Select tbnk.ID_BANK, tbnk.ABRIGER, tbnk.NomBank_AR, tSum.Montant_Facture
</code>```

答:
Little Problem Try Code:</p>

```<code>Dim result=  from v in VW_sum_bybank
            join b in tbl_bank on v.id_bank equals b.id_bank into jj from kk in  jj.DefaultIfEmpty()
          select
                  V_id_bank=v.id_banl,
                  Code_bank=v.Code_bank,
                   NOMBANK=v.NOMBANK,
                  ABRG=v.ABRG,
                  b_id_bank=kk.ID_bank,
                  sommeFAC=kk.sommeFAC
</code>```

ContentLicense: CC BY-SA 3.0

Title: vb.net LINQ LEFT JOIN

Body:
I want query LINQ to LEFT JOIN TWO TABLES get results like SQL exactly
(show results like the picture even the row empty yellow line)

My code:

Dim qJoint = From tSum In lstSUM Group Join tbnk In lstBank On tbnk.ID_BANK Equals tSum.ID_BANK _
   Into tResult = Group From tbnk In tResult.DefaultIfEmpty Select tbnk.ID_BANK, tbnk.ABRIGER, tbnk.NomBank_AR, tSum.Montant_Facture

Body:
Little Problem Try Code:

Dim result=  from v in VW_sum_bybank
            join b in tbl_bank on v.id_bank equals b.id_bank into jj from kk in  jj.DefaultIfEmpty()
          select
                  V_id_bank=v.id_banl,
                  Code_bank=v.Code_bank,
                   NOMBANK=v.NOMBANK,
                  ABRG=v.ABRG,
                  b_id_bank=kk.ID_bank,
                  sommeFAC=kk.sommeFAC


问:
Return value of series where position is determined by minimum value of an array
Using the example data table below as a guide

Image of table

I need to return the value in the first column that corresponds to the minimum value in the column where the that column header is equal to a referenced value.  I have been trying to use the following array equation, but I only get the minimum value and can't figure out how to reference the other column.

{=MIN(IF((B1:D1=*the reference value in this case "xy"*),B2:D8))}

The result I am looking for is "T3"

答:
=LOOKUP(1,0/FREQUENCY(-98^99,INDEX(B2:D8,0,MATCH(G2,B1:D1,0))),A2:A8)

where it is assumed that no value within the range B2:D8 is smaller than -98^99.

Regards


问:
Yii2 -Make dropdown row in navbar disable/readOnly based on user type
Is there someone who can help me?
I make a dropdown on of my layout tab menu.
this my dropdown.

```<code>[
      'label' => '(' . Yii::$app->user->identity->username . ')',
      'items' => [
          ['label' => 'Change Password', 'url' => ['/site/changepassword']],
          ['label' => 'User Setting', 'url' => ['/user']],
          ['label' => 'test', 'url' => ['/leave-record/leave']],
          '<li class="dropdown-header"></li>',
          ['label' => 'Logout', 'url' => ['/site/logout'],
                                'linkOptions' => ['data-method' => 'post']],
      ],
    ],
</code>```

I've 3 user type in user model.
1. Master Admin
2. Normal Admin
3. Normal User

if Master Admin login, he can access all rows in dropdown. Then if normal admin login row "User Setting" become disable.

答:
for an item you can use the  visible attribute  assign  a proper condition

eg:

```<code>[
      ['label' => 'Change Password', 'url' => ['/site/changepassword']],
      [
         'label' => 'User Setting',
          'url' => ['/user'],
          'visible' => Yii::$app->User->can('masterAdmin'),
      ],
 ],
</code>```

for two user type you could use a $check

```<code>$check = ((Yii::$app->User->can('masterAdmin') || Yii::$app->User->can('admin')) ? TRUE : FALSE;
</code>```

.

```<code> ...
 'label' => 'User Setting',
  'url' => ['/user'],
 'visible' =>$check,
</code>```

Body:
Is there someone who can help me?
I make a dropdown on of my layout tab menu.
this my dropdown.

[
      'label' => '(' . Yii::$app->user->identity->username . ')',
      'items' => [
          ['label' => 'Change Password', 'url' => ['/site/changepassword']],
          ['label' => 'User Setting', 'url' => ['/user']],
          ['label' => 'test', 'url' => ['/leave-record/leave']],
          '

',
          ['label' => 'Logout', 'url' => ['/site/logout'],
                                'linkOptions' => ['data-method' => 'post']],
      ],
    ],

I've 3 user type in user model.
1. Master Admin
2. Normal Admin
3. Normal User

if Master Admin login, he can access all rows in dropdown. Then if normal admin login row "User Setting" become disable.

Body:
for an item you can use the  visible attribute  assign  a proper condition

eg:

[
      ['label' => 'Change Password', 'url' => ['/site/changepassword']],
      [
         'label' => 'User Setting',
          'url' => ['/user'],
          'visible' => Yii::$app->User->can('masterAdmin'),
      ],
 ],

for two user type you could use a $check

$check = ((Yii::$app->User->can('masterAdmin') || Yii::$app->User->can('admin')) ? TRUE : FALSE;

.

 ...
 'label' => 'User Setting',
  'url' => ['/user'],
 'visible' =>$check,


问:
MKMapView in loadView method
I have a silly question to ask and the question is that i have been working with MapKit Framework and found that whenever i am setting the frames and mapType of the object of MKMapView in the init method i get a blank view but when i set the frame and mapType in the loadView method i can view the map interface.

Why is this so? i am using sdk 3.1

Please help

here's my code

```
- (void)loadView {
    [super loadView];
    mymapView = [[MKMapView alloc]initWithFrame:self.view.bounds];

    mymapView.mapType = MKMapTypeStandard;

    mymapView.showsUserLocation = YES;

    [self.view addSubview:mymapView];
}

```

答:
use debbuging pointer for checking init method calls or not.I think init method does not call

but viewDidLoad always call thats why this happens.

you can also use according to you that means show map in init by simply calling init in viewDidLoad.

ContentLicense: CC BY-SA 2.5

Title: MKMapView in loadView method

Body:
I have a silly question to ask and the question is that i have been working with MapKit Framework and found that whenever i am setting the frames and mapType of the object of MKMapView in the init method i get a blank view but when i set the frame and mapType in the loadView method i can view the map interface.

Why is this so? i am using sdk 3.1

Please help

here's my code

- (void)loadView {
    [super loadView];
    mymapView = [[MKMapView alloc]initWithFrame:self.view.bounds];

    mymapView.mapType = MKMapTypeStandard;

    mymapView.showsUserLocation = YES;

    [self.view addSubview:mymapView];
}


问:
jQuery UI : Increase the padding on resizeable()
I want to know that is it possible to increase and decrease padding on resize instead of increase and decreasing the height.

```<code>$( function() {
    $( "#resizable" ).resizable({
        handles: 'n,s'
    });
 });
</code>```

Fiddle example

Update :

I actually want to know that if I resize the div I want to dynamically increase the padding on resize instead of height
Updated Fiddle

Try to resize the div from north and south position

答:
Added a fiddle with some calculated changes.

```<code>$( function() {
  $( "#resizable" ).resizable({
    resize: function( event, ui ) {
      var originalHeight = ui.originalSize.height;
      var newHeight = ui.size.height;
      var pad = 5;
      if (originalHeight < newHeight) {
        pad = newHeight - originalHeight;
      }
      $(this).css('padding', pad);
    }
  });
});
</code>```

https://jsfiddle.net/aavrug/6rh7emog/1/

Body:
I want to know that is it possible to increase and decrease padding on resize instead of increase and decreasing the height.

$( function() {
    $( "#resizable" ).resizable({
        handles: 'n,s'
    });
 });

Fiddle example

Update :

I actually want to know that if I resize the div I want to dynamically increase the padding on resize instead of height
Updated Fiddle

Try to resize the div from north and south position

Body:
Added a fiddle with some calculated changes.

$( function() {
  $( "#resizable" ).resizable({
    resize: function( event, ui ) {
      var originalHeight = ui.originalSize.height;
      var newHeight = ui.size.height;
      var pad = 5;
      if (originalHeight < newHeight) {
        pad = newHeight - originalHeight;
      }
      $(this).css('padding', pad);
    }
  });
});

https://jsfiddle.net/aavrug/6rh7emog/1/


问:
Spring Boot API with Multiple Controllers?
I am starting to learn Spring Boot. I am struggling to find an example with multiple RestControllers, which indicates to me that I may be doing something wrong. I am trying a very simple example: The goal is to make calls like the following:

```<code>localhost:8080/
localhost:8080/employees/bob
localhost:8080/departments
</code>```

I can only get localhost:8080/ to display. The other calls return response: This application has no explicit mapping for /error, so you are seeing this as a fallback.

```<code>com.demo.departments
Department.java
DepartmentController.java

com.demo.employees
Employee.java
EmployeeController.java

com.demo
BootDemoApplication.java
</code>```

Code:

```<code>package com.demo.departments
@RestController
@RequestMapping("/departments")
public class DepartmentController {

@RequestMapping("")
public String get(){
    return "test..";

}

@RequestMapping("/list")
public List<Department> getDepartments(){
    return null;

}

}
--------------------------------------------------------------------
package com.demo.employees
@RestController
@RequestMapping("/employees")
public class EmployeeController {

Employee e =new Employee();

@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public Employee getEmployeeInJSON(@PathVariable String name) {

 e.setName(name);
 e.setEmail("employee1@genuitec.com");

 return e;

}
}
-----------------------------------------------------------------------

package com.demo
@RestController
@SpringBootApplication

public class BootDemoApplication {

public static void main(String[] args) {
    SpringApplication.run(BootDemoApplication.class, args);
}

@RequestMapping("/")
String home(){
    return "<html> This is the home page for Boot Demo.</html>";
}
</code>```

答:
ComponentScan annotation works in most cases.

See below example, you could apply similar.

    package com.demo;

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@ComponentScan(basePackages = {"com.demo"})
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}
}
</code>```

Body:
I am starting to learn Spring Boot. I am struggling to find an example with multiple RestControllers, which indicates to me that I may be doing something wrong. I am trying a very simple example: The goal is to make calls like the following:

localhost:8080/
localhost:8080/employees/bob
localhost:8080/departments

I can only get localhost:8080/ to display. The other calls return response: This application has no explicit mapping for /error, so you are seeing this as a fallback.

com.demo.departments
Department.java
DepartmentController.java

com.demo.employees
Employee.java
EmployeeController.java

com.demo
BootDemoApplication.java

Code:

package com.demo.departments
@RestController
@RequestMapping("/departments")
public class DepartmentController {

@RequestMapping("")
public String get(){
    return "test..";

}

@RequestMapping("/list")
public List<Department> getDepartments(){
    return null;

}

}
--------------------------------------------------------------------
package com.demo.employees
@RestController
@RequestMapping("/employees")
public class EmployeeController {

Employee e =new Employee();

@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public Employee getEmployeeInJSON(@PathVariable String name) {

 e.setName(name);
 e.setEmail("employee1@genuitec.com");

 return e;

}
}
-----------------------------------------------------------------------

package com.demo
@RestController
@SpringBootApplication

public class BootDemoApplication {

public static void main(String[] args) {
    SpringApplication.run(BootDemoApplication.class, args);
}

@RequestMapping("/")
String home(){
    return " This is the home page for Boot Demo.";
}

Body:
ComponentScan annotation works in most cases.

See below example, you could apply similar.

    package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@ComponentScan(basePackages = {"com.demo"})
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}
}


问:
JDialog windowClosed event called when owner JFrame close
I have the test code below.
After opening the dialog when I close the it the windowClosed method is called, but it's called again when I close the JFrame and the dialog was just closed, why?  I am not closing the dialog in this case.
So I see:

```<code>closed
closed
</code>```

How can I prevent it?

I don't want to set EXIT_ON_CLOSE on JFrame (this will not call the windowClosed again) because this terminate the application and in the real case I can't do this.

Thanks for the help

```<code>public final class Test4 {

    public static void main(String[] args) {

        Runnable runnable = new Runnable(){

            @Override
            public void run() {

                final JFrame frame = new JFrame("test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setSize(300, 300);
                JButton btn = new JButton("test");
                frame.add(btn);
                frame.setVisible(true);
                btn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {

                        openDialog(frame);
                    }
                });
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    private static void openDialog(Frame owner) {

        JDialog testDialog = new JDialog(owner);
        testDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        testDialog.setSize(100,100);
        testDialog.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {

                System.out.println("closed");
            }
        });
        testDialog.setVisible(true);
    }
}
</code>```

答: From comments and tests probably it was a bug resolved in java 8 because with java 8 It works fine.</p>

Body:
I have the test code below.
After opening the dialog when I close the it the windowClosed method is called, but it's called again when I close the JFrame and the dialog was just closed, why?  I am not closing the dialog in this case.
So I see:

closed
closed

How can I prevent it?

I don't want to set EXIT_ON_CLOSE on JFrame (this will not call the windowClosed again) because this terminate the application and in the real case I can't do this.

Thanks for the help

public final class Test4 {

    public static void main(String[] args) {

        Runnable runnable = new Runnable(){

            @Override
            public void run() {

                final JFrame frame = new JFrame("test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setSize(300, 300);
                JButton btn = new JButton("test");
                frame.add(btn);
                frame.setVisible(true);
                btn.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {

                        openDialog(frame);
                    }
                });
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    private static void openDialog(Frame owner) {

        JDialog testDialog = new JDialog(owner);
        testDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        testDialog.setSize(100,100);
        testDialog.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {

                System.out.println("closed");
            }
        });
        testDialog.setVisible(true);
    }
}


问:
Generate a class from xsd file in net core
I need to generate a class from an xsd in net core.
In dotnet standard I used commandline xsd filename.xsd /c.
But how to I create this class in net core.
Anyone knows how to do this?

When I add a class generated with xsd.exe I get several errors.

Example

```<code>    Error   CS0234  The type or namespace name 'SerializableAttributeAttribute' does not exist in the namespace 'System' (are you missing an assembly reference?)

Error   CS0234  The type or namespace name 'DesignerCategoryAttribute' does not exist in the namespace 'System.ComponentModel' (are you missing an assembly reference?)

Error   CS0234  The type or namespace name 'XmlTypeAttributeAttribute' does not exist in the namespace 'System.Xml.Serialization' (are you missing an assembly reference?)

Error   CS0246  The type or namespace name 'AnonymousType' could not be found (are you missing a using directive or an assembly reference?)
</code>```

Attributes from a class in autogen file

```<code>[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
</code>```

答:
I have now solved this issue with adding nugets to my project.

System.Xml.XmlSerializer

Solution: Removes the serializations attribute issues except the DesignerCategoryAttribute

Newtonsoft.json

Solution: Removes the DesignerCategoryAttribute

Now it is possible to compile the xsd.exe generated class and use it in net core

Body:
I need to generate a class from an xsd in net core.
In dotnet standard I used commandline xsd filename.xsd /c.
But how to I create this class in net core.
Anyone knows how to do this?

When I add a class generated with xsd.exe I get several errors.

Example

    Error   CS0234  The type or namespace name 'SerializableAttributeAttribute' does not exist in the namespace 'System' (are you missing an assembly reference?)

Error   CS0234  The type or namespace name 'DesignerCategoryAttribute' does not exist in the namespace 'System.ComponentModel' (are you missing an assembly reference?)

Error   CS0234  The type or namespace name 'XmlTypeAttributeAttribute' does not exist in the namespace 'System.Xml.Serialization' (are you missing an assembly reference?)

Error   CS0246  The type or namespace name 'AnonymousType' could not be found (are you missing a using directive or an assembly reference?)

Attributes from a class in autogen file

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]


问:
PHP: Manipulating existing array
I have an existing array $cars[]. Here's how I created the array $cars[]

```<code>$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );
</code>```

As you can see, the indices of the array $cars[] is not in order. What I need to do is insert an array element in the array $cars[] when needed, to make it in order. I need to make the array $cars[] like this:

```<code>$cars = array("1" => "Toyota",
              "2"=> "NULL",
              "3"=> "NULL",
              "4"=> "NULL",
              "5" => "BMW",
              "6"=> "NULL",
              "7" => "Volvo",
              "8"=> "NULL",
               .
               .
               .
              "31"=> "NULL",
              "32"=> "Porsche"
               .
               .
               .
              "48"=> "NULL"  );
</code>```

A total of 48 cars. Thank you guys!

答:
Try this-

```<code>function addKeyArray(&$array)
{
    end($array);
    $max = key($array); //Get the final key as max or you can directly pass value like $max = 48;
    for($i = 0; $i < $max; $i++)
    {
        if(!isset($array[$i]))
        {
            $array[$i] = 'NULL';
        }
    }
}

addKeyArray($cars);
ksort($cars);
echo "```"; print_r($cars);
```

Explaination:

addKeyArray() will loop and check if any key miss then it will set key and after that ksort() will sort array based on key.

Title: PHP: Manipulating existing array

Body:
I have an existing array $cars[]. Here's how I created the array $cars[]

$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );

As you can see, the indices of the array $cars[] is not in order. What I need to do is insert an array element in the array $cars[] when needed, to make it in order. I need to make the array $cars[] like this:

$cars = array("1" => "Toyota",
              "2"=> "NULL",
              "3"=> "NULL",
              "4"=> "NULL",
              "5" => "BMW",
              "6"=> "NULL",
              "7" => "Volvo",
              "8"=> "NULL",
               .
               .
               .
              "31"=> "NULL",
              "32"=> "Porsche"
               .
               .
               .
              "48"=> "NULL"  );

A total of 48 cars. Thank you guys!

Body:
Try this-

function addKeyArray(&$array)
{
    end($array);
    $max = key($array); //Get the final key as max or you can directly pass value like $max = 48;
    for($i = 0; $i < $max; $i++)
    {
        if(!isset($array[$i]))
        {
            $array[$i] = 'NULL';
        }
    }
}

addKeyArray($cars);
ksort($cars);
echo "<pre>"; print_r($cars);

Explaination:

addKeyArray() will loop and check if any key miss then it will set key and after that ksort() will sort array based on key.


问:
Python - Using pandas to format excel cell
I have a pandas dataframe, which is something like shown below.

I would like to format the column "Pass/Fail" as if Fail --> red background, else green background, like:

I have tried to use Pandas to do the formatting, but it fails to add color to the excel. Following is the code:

```<code>writer = pandas.ExcelWriter(destination,engine = 'xlsxwriter')
color = Answer.style.applymap(lambda x: 'color: red' if x == "Fail" else 'color: green',subset= pandas.IndexSlice[:,['Pass/Fail']])
color.to_excel(writer,'sheet1')
</code>```

I tried StyleFrame which failed to install. Seems that StyleFrame does not comply with my python version 3.6.

How can I format the excel as I want?

答:
Disclaimer: I wrote the following library

I'd like to suggest using StyleFrame:

```<code>import pandas as pd
from StyleFrame import StyleFrame, Styler

df = pd.DataFrame({'Pass/Fail':['Pass','Fail','Fail'],
                   'expect':[1,2,3]})

sf = StyleFrame(df)

sf.apply_style_by_indexes(sf[sf['Pass/Fail'] == 'Pass'], cols_to_style='Pass/Fail',
                          styler_obj=Styler(bg_color='green'))
sf.apply_style_by_indexes(sf[sf['Pass/Fail'] == 'Fail'], cols_to_style='Pass/Fail',
                          styler_obj=Styler(bg_color='red'))

sf.to_excel('test.xlsx').save()
</code>```

Since it bridges the gap between pandas and openpyxl, the styling is done on the dataframe level instead of the worksheet level (so for example you don't need to know the relevant cell range is B2:B4 or mess with indexes.

The code above outputs the following:

EDIT: Just saw you mentioned you've tried to install but got an error. Can you edit your question and include the error?

Body:
I have a pandas dataframe, which is something like shown below.

I would like to format the column "Pass/Fail" as if Fail --> red background, else green background, like:

I have tried to use Pandas to do the formatting, but it fails to add color to the excel. Following is the code:

writer = pandas.ExcelWriter(destination,engine = 'xlsxwriter')
color = Answer.style.applymap(lambda x: 'color: red' if x == "Fail" else 'color: green',subset= pandas.IndexSlice[:,['Pass/Fail']])
color.to_excel(writer,'sheet1')

I tried StyleFrame which failed to install. Seems that StyleFrame does not comply with my python version 3.6.

How can I format the excel as I want?

Body:
Disclaimer: I wrote the following library

I'd like to suggest using StyleFrame:

import pandas as pd
from StyleFrame import StyleFrame, Styler

df = pd.DataFrame({'Pass/Fail':['Pass','Fail','Fail'],
                   'expect':[1,2,3]})

sf = StyleFrame(df)

sf.apply_style_by_indexes(sf[sf['Pass/Fail'] == 'Pass'], cols_to_style='Pass/Fail',
                          styler_obj=Styler(bg_color='green'))
sf.apply_style_by_indexes(sf[sf['Pass/Fail'] == 'Fail'], cols_to_style='Pass/Fail',
                          styler_obj=Styler(bg_color='red'))

sf.to_excel('test.xlsx').save()

Since it bridges the gap between pandas and openpyxl, the styling is done on the dataframe level instead of the worksheet level (so for example you don't need to know the relevant cell range is B2:B4 or mess with indexes.

The code above outputs the following:

EDIT: Just saw you mentioned you've tried to install but got an error. Can you edit your question and include the error?


问:
how to call web service(.wsdl) using asp.net
I got .wsdl file from my client. by using this webservice i need validate customer information. So how to achieve this one .if customer is there or not
xml :

```<code> <xs:element name="FetchClubMembershipRequest">
        <xs:annotation>
          <xs:documentation>Request to fetch customers' membership information.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_ID" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_Code" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Last_Name" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="First_Name" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
</code>```

this is from wsdl.file

答:
Visual Studio comes with builtin support for creating web service proxy objects from a WSDL specification. Take a look at the documentation for a command-line tool that comes with Visual Studio. Most other .NET IDEs allow you to create the web service proxies 'invisibly' as well - but you'll most likely have to host the WSDL descriptor on a web site.

If you use the command line tool, you'll easily see the code generated. And if you use Visual Studio to generate the proxy instead, you can view the methods and properties of the web service proxy in the class/object browser.

Body:
I got .wsdl file from my client. by using this webservice i need validate customer information. So how to achieve this one .if customer is there or not
xml :

 <xs:element name="FetchClubMembershipRequest">
        <xs:annotation>
          <xs:documentation>Request to fetch customers' membership information.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_ID" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_Code" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Last_Name" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="First_Name" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

this is from wsdl.file


问:
How to run recorder.java with fxml JavaFX?
I want to record voice using UI fxml. But I dont know how to run this java file on UI fxml I have create.

JavaRecorder.java

```<code>package application;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class JavaRecorder {

     static final long RECORD_TIME = 30000;  // 0.5 minute

        // path of the wav file
        File wavFile = new File("C:/Users/Asus/Music/RecordAudio.wav");

        // format of audio file
        AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

        // the line from which audio data is captured
        TargetDataLine line;

        /**
         * Defines an audio format
         */
        AudioFormat getAudioFormat() {
            float sampleRate = 16000;
            int sampleSizeInBits = 8;
            int channels = 2;
            boolean signed = true;
            boolean bigEndian = true;
            AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
                                                 channels, signed, bigEndian);
            return format;
        }

        /**
         * Captures the sound and record into a WAV file
         */
        void start() {
            try {
                AudioFormat format = getAudioFormat();
                DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

                // checks if system supports the data line
                if (!AudioSystem.isLineSupported(info)) {
                    System.out.println("Line not supported");
                    System.exit(0);
                }
                line = (TargetDataLine) AudioSystem.getLine(info);
                line.open(format);
                line.start();   // start capturing

                System.out.println("Start capturing...");

                AudioInputStream ais = new AudioInputStream(line);

                System.out.println("Start recording...");

                // start recording
                AudioSystem.write(ais, fileType, wavFile);

            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }

        /**
         * Closes the target data line to finish capturing and recording
         */
        void finish() {
            line.stop();
            line.close();
            System.out.println("Finished");
        }

        /**
         * Entry to run the program
         */
        public static void main(String[] args) {
            final JavaRecorder recorder = new JavaRecorder();

            // creates a new thread that waits for a specified
            // of time before stopping
            Thread stopper = new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(RECORD_TIME);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    recorder.finish();
                }
            });

            stopper.start();

            // start recording
            recorder.start();
        }
    }
</code>```

Below is coding for UI fxml..

Main.java

```<code>package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.fxml.FXMLLoader;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("First.fxml"));
            Scene scene = new Scene(root,717,700);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

I want to record by clicking "Record" button that I have created in AyatP1.fxml..

AyatP1Controller.java

```<code>package application;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

public class AyatP1Controller implements Initializable {

    @FXML
    private AnchorPane rootPane;

    @Override
    public void initialize(URL url, ResourceBundle rb){
         mediaPlayer.setOnEndOfMedia(()->button.setVisible(true));
    }
    @FXML
    private void loadPrev(ActionEvent event)throws IOException {
        AnchorPane pane = (AnchorPane)FXMLLoader.load(getClass().getResource("MenuAyat.fxml"));
        rootPane.getChildren().setAll(pane);
    }
    @FXML
    private void loadNext(ActionEvent event)throws IOException {
        AnchorPane pane = (AnchorPane)FXMLLoader.load(getClass().getResource("AyatP2.fxml"));
        rootPane.getChildren().setAll(pane);
    }
    @FXML private Button button;
    @FXML private Button rekod;
    @FXML private MediaPlayer mediaPlayer;

    @FXML
    public void Playbtn(ActionEvent event){
        button.setVisible(false);
        mediaPlayer.seek(Duration.ZERO);
        mediaPlayer.play();
    }
    @FXML
    public void Playrecord(ActionEvent event){
        rekod.setVisible(false);
    }
}
</code>```

AyatP1.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.media.Media?>
<?import javafx.scene.media.MediaPlayer?>
<?import javafx.scene.media.MediaView?>

<AnchorPane fx:id="rootPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="598.0" prefWidth="717.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.AyatP1Controller">
   <children>
      <ImageView fitHeight="598.0" fitWidth="761.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../../../Pictures/gambar/classroom.jpg" />
         </image>
      </ImageView>
      <ImageView fitHeight="260.0" fitWidth="385.0" layoutX="55.0" layoutY="94.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../../../Pictures/gambar/Slide1.jpg" />
         </image>
      </ImageView>
      <Button layoutX="411.0" layoutY="525.0" mnemonicParsing="false" onAction="#loadPrev">
         <graphic>
            <ImageView fitHeight="48.0" fitWidth="48.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../../../../../Pictures/gambar/left_circle.png" />
               </image>
            </ImageView>
         </graphic>
      </Button>
      <Button layoutX="482.0" layoutY="525.0" mnemonicParsing="false" onAction="#loadNext">
         <graphic>
            <ImageView fitHeight="48.0" fitWidth="48.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../../../../../Pictures/gambar/right_circle.png" />
               </image>
            </ImageView>
         </graphic>
      </Button>
      <Button fx:id="button" layoutX="125.0" layoutY="439.0" mnemonicParsing="false" onAction="#Playbtn" text="Start" />
      <Button fx:id="rekod" layoutX="222.0" layoutY="439.0" mnemonicParsing="false" onAction="#Playrecord" text="Record" />
      <Button layoutX="324.0" layoutY="439.0" mnemonicParsing="false" text="Stop" />
       <MediaView>
                  <mediaPlayer>
                      <MediaPlayer fx:id="mediaPlayer" autoPlay="false">
                          <media>
                              <Media source="file:///C:/Users/Asus/Music/gitarresms.mp3" />
                          </media>
                      </MediaPlayer>
                  </mediaPlayer>
      </MediaView>
   </children>
</AnchorPane>
</code>```

答:
You might want to try out

```<code>AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("/First.fxml"));
</code>```

Change the "First.fxml" to "/First.fxml", and then run the main(String[] args) method from the Main class.

Body:
I want to record voice using UI fxml. But I dont know how to run this java file on UI fxml I have create.

JavaRecorder.java

package application;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class JavaRecorder {

     static final long RECORD_TIME = 30000;  // 0.5 minute

        // path of the wav file
        File wavFile = new File("C:/Users/Asus/Music/RecordAudio.wav");

        // format of audio file
        AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

        // the line from which audio data is captured
        TargetDataLine line;

        /**
         * Defines an audio format
         */
        AudioFormat getAudioFormat() {
            float sampleRate = 16000;
            int sampleSizeInBits = 8;
            int channels = 2;
            boolean signed = true;
            boolean bigEndian = true;
            AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
                                                 channels, signed, bigEndian);
            return format;
        }

        /**
         * Captures the sound and record into a WAV file
         */
        void start() {
            try {
                AudioFormat format = getAudioFormat();
                DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

                // checks if system supports the data line
                if (!AudioSystem.isLineSupported(info)) {
                    System.out.println("Line not supported");
                    System.exit(0);
                }
                line = (TargetDataLine) AudioSystem.getLine(info);
                line.open(format);
                line.start();   // start capturing

                System.out.println("Start capturing...");

                AudioInputStream ais = new AudioInputStream(line);

                System.out.println("Start recording...");

                // start recording
                AudioSystem.write(ais, fileType, wavFile);

            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }

        /**
         * Closes the target data line to finish capturing and recording
         */
        void finish() {
            line.stop();
            line.close();
            System.out.println("Finished");
        }

        /**
         * Entry to run the program
         */
        public static void main(String[] args) {
            final JavaRecorder recorder = new JavaRecorder();

            // creates a new thread that waits for a specified
            // of time before stopping
            Thread stopper = new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(RECORD_TIME);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    recorder.finish();
                }
            });

            stopper.start();

            // start recording
            recorder.start();
        }
    }

Below is coding for UI fxml..

Main.java

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.fxml.FXMLLoader;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("First.fxml"));
            Scene scene = new Scene(root,717,700);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}

I want to record by clicking "Record" button that I have created in AyatP1.fxml..

AyatP1Controller.java

package application;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

public class AyatP1Controller implements Initializable {

    @FXML
    private AnchorPane rootPane;

    @Override
    public void initialize(URL url, ResourceBundle rb){
         mediaPlayer.setOnEndOfMedia(()->button.setVisible(true));
    }
    @FXML
    private void loadPrev(ActionEvent event)throws IOException {
        AnchorPane pane = (AnchorPane)FXMLLoader.load(getClass().getResource("MenuAyat.fxml"));
        rootPane.getChildren().setAll(pane);
    }
    @FXML
    private void loadNext(ActionEvent event)throws IOException {
        AnchorPane pane = (AnchorPane)FXMLLoader.load(getClass().getResource("AyatP2.fxml"));
        rootPane.getChildren().setAll(pane);
    }
    @FXML private Button button;
    @FXML private Button rekod;
    @FXML private MediaPlayer mediaPlayer;

    @FXML
    public void Playbtn(ActionEvent event){
        button.setVisible(false);
        mediaPlayer.seek(Duration.ZERO);
        mediaPlayer.play();
    }
    @FXML
    public void Playrecord(ActionEvent event){
        rekod.setVisible(false);
    }
}

AyatP1.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.media.Media?>
<?import javafx.scene.media.MediaPlayer?>
<?import javafx.scene.media.MediaView?>

<AnchorPane fx:id="rootPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="598.0" prefWidth="717.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.AyatP1Controller">
   <children>
      <ImageView fitHeight="598.0" fitWidth="761.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../../../Pictures/gambar/classroom.jpg" />
         </image>
      </ImageView>
      <ImageView fitHeight="260.0" fitWidth="385.0" layoutX="55.0" layoutY="94.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../../../Pictures/gambar/Slide1.jpg" />
         </image>
      </ImageView>
      <Button layoutX="411.0" layoutY="525.0" mnemonicParsing="false" onAction="#loadPrev">
         <graphic>
            <ImageView fitHeight="48.0" fitWidth="48.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../../../../../Pictures/gambar/left_circle.png" />
               </image>
            </ImageView>
         </graphic>
      </Button>
      <Button layoutX="482.0" layoutY="525.0" mnemonicParsing="false" onAction="#loadNext">
         <graphic>
            <ImageView fitHeight="48.0" fitWidth="48.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@../../../../../Pictures/gambar/right_circle.png" />
               </image>
            </ImageView>
         </graphic>
      </Button>
      <Button fx:id="button" layoutX="125.0" layoutY="439.0" mnemonicParsing="false" onAction="#Playbtn" text="Start" />
      <Button fx:id="rekod" layoutX="222.0" layoutY="439.0" mnemonicParsing="false" onAction="#Playrecord" text="Record" />
      <Button layoutX="324.0" layoutY="439.0" mnemonicParsing="false" text="Stop" />
       <MediaView>
                  <mediaPlayer>
                      <MediaPlayer fx:id="mediaPlayer" autoPlay="false">
                          <media>
                              <Media source="file:///C:/Users/Asus/Music/gitarresms.mp3" />
                          </media>
                      </MediaPlayer>
                  </mediaPlayer>
      </MediaView>
   </children>
</AnchorPane>

Body:
You might want to try out

AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("/First.fxml"));

Change the "First.fxml" to "/First.fxml", and then run the main(String[] args) method from the Main class.


问:
replace values of keys in json1 from Json2
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

```<code> one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.
</code>```

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the

```<code> second JSON --> for ex: {"blog_heading":"def"}
</code>```

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

```<code>  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.
</code>```

So i am trying as below,

```<code>$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);
</code>```

id5 data is : $id5

```<code>  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================
</code>```

Log of $id :

```<code>stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )
</code>```

Please suggest me how can i achieve this... Anything i am doing wrong here

答:
If you have only one element in array,Do like this

```<code>$a = json_decode('{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}',true);
$b = json_decode('{"blog_heading":"def"}',true);
$a['blog_heading'] = $b['blog_heading'];
print_r($a);
</code>```

If you have multiple element like this :

```<code>$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"blog_heading":"def"},{"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
    $c[$i]['blog_heading'] = $d[$i]['blog_heading'];
    $return[] = $c[$i];
}
print_r($return);
</code>```

If you want to replace value by specific id

```<code>$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":7,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();

for ($i=0; $i < count($c); $i++) {
    if($d[$i]['id'] == $c[$i]['id']) {
        $c[$i]['blog_heading'] = $d[$i]['blog_heading'];
    }
    $return[] = $c[$i];
}
print_r($return);
</code>```

Checking dynamic key value pair :

```<code>$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":6,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);

$return = array();
for ($i=0; $i < count($c); $i++) {
    $result = array_intersect_key($c[$i], $d[$i]);
    foreach ($result as $key => $value) {
        $c[$i][$key] = $d[$i][$key];
    }
    $return[] = $c[$i];
}
print_r($return);
</code>```

Check demo here

Body:
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

 one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the

 second JSON --> for ex: {"blog_heading":"def"}

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.

So i am trying as below,

$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);

id5 data is : $id5

  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================

Log of $id :

stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )

Please suggest me how can i achieve this... Anything i am doing wrong here

Body:
If you have only one element in array,Do like this

$a = json_decode('{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}',true);
$b = json_decode('{"blog_heading":"def"}',true);
$a['blog_heading'] = $b['blog_heading'];
print_r($a);

If you have multiple element like this :

$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"blog_heading":"def"},{"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
    $c[$i]['blog_heading'] = $d[$i]['blog_heading'];
    $return[] = $c[$i];
}
print_r($return);

If you want to replace value by specific id

$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":7,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();

for ($i=0; $i < count($c); $i++) {
    if($d[$i]['id'] == $c[$i]['id']) {
        $c[$i]['blog_heading'] = $d[$i]['blog_heading'];
    }
    $return[] = $c[$i];
}
print_r($return);

Checking dynamic key value pair :

$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":6,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);

$return = array();
for ($i=0; $i < count($c); $i++) {
    $result = array_intersect_key($c[$i], $d[$i]);
    foreach ($result as $key => $value) {
        $c[$i][$key] = $d[$i][$key];
    }
    $return[] = $c[$i];
}
print_r($return);

Check demo here


问:
What is the difference between smoke testing and sanity testing?
What is the difference between smoke testing and sanity testing? When do will perform smoke testing and when do will perform sanity testing?</p>

答:
Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.

Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.

In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.


问:
How to save image in Microsoft SQL Database on Azure from Android app?
I'm trying to find an easiest way to store and image from Android app in SQL Database on Azure. I created Azure Mobile App and I have sample project with TodoList table on my database. The client (Android app) project can save new text item to this database. How can I save image?</p>

答:
Per my experience, to store image from Android App to SQL Azure is that encode an image using Base64 to a byte array as an entity attribute to save it as a blob column via the backend of Azure Mobile App using NodeJS/C# on SQL Azure.

However, to save images to SQL Azure or other RDBMS is not a good idea. The correct & best way is that using Azure Blob Storage to store images or other files. There is a good blog which introduces how to store image from Android on Azure Mobile, I think it's very helpful that you can refer to.


问:
How do you create a mongodb replica set or shard that is externally available in kubernetes?
I have followed tutorials and set up working mongodb replica sets however when it comes to exposing them as a service I am stuck with using a LoadBalancer which directs to any pod. In most cases this ends up being a secondary database and not terrible helpful. I have also managed to get separate mongodb replicas set up and then tried to connect to those externally however connections fail because internal replicaset ips are all through local google cloud dns.

What I am hoping for is something like this.

Then (potentially) there is a single connection uri that could connect you to your mongodb replicaset without needing individual mongodb connection details.

I'm not sure if this is possible but any help is greatly appreciated!

答: The loadbalancer type service will route traffic to any one pod matches its selector, which is not how mongodb replica set works. The connection string should contain all instances in the set. You probably need to expose each replica instance with type=loadbalancer. Then you may connect via "mongodb://mongo-0_IP,mongo-1_IP,mongo-2_IP:27017/dbname_?"


问:
Value was evaluated just now with console.log on JavaScript object
When I print object in HTML using for each loop I'm getting only half contents of the object but when I print using console.log and press that little triangle I'm getting full object and i is shown near that object when I hover that it says value was evaluated just now as shown in below image,

When I print same object in HTML it looks like this,

```<code>7.33--Some Name
7.08--Some Name
7.83--Some Name
</code>```

Actually, object contains a total of 5 elements as shown in the above image,
Code for printing object HTML,

```<code>for (var key in obj){
    $("p").append(key+"--"+obj[key][0]+"<br>");
}
</code>```

答:
Examining objects via console.log happens in an asynchronous manner.

The reference to the object is passed synchronously to console but it doesn't display the properties till its expanded . If the object has been modified before examining it in the console, the data shown will have the updated values. Chrome console shows a little i in a box which which says value below was evaluated just now

In order to print the object completely in console, you can stringify and log it like

```<code>console.log(JSON.stringify(obj));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I print object in HTML using for each loop I'm getting only half contents of the object but when I print using console.log and press that little triangle I'm getting full object and i is shown near that object when I hover that it says value was evaluated just now as shown in below image,

When I print same object in HTML it looks like this,

7.33--Some Name
7.08--Some Name
7.83--Some Name

Actually, object contains a total of 5 elements as shown in the above image,
Code for printing object HTML,

for (var key in obj){
    $("p").append(key+"--"+obj[key][0]+"
");
}

Body:
Examining objects via console.log happens in an asynchronous manner.

The reference to the object is passed synchronously to console but it doesn't display the properties till its expanded . If the object has been modified before examining it in the console, the data shown will have the updated values. Chrome console shows a little i in a box which which says value below was evaluated just now

In order to print the object completely in console, you can stringify and log it like

console.log(JSON.stringify(obj));


问:
Different behavior when using vsnprintf on msvc and gcc
I have the following code to append a buffer using vsnprintf().

```<code>#include <stdio.h>
#include <stdarg.h>

using namespace std;

void MyPrintFunc(char *buffer, size_t sizeOfBuffer, const char* format, ...)
{
   va_list arg;
   va_start(arg, format);

   vsnprintf(buffer, sizeOfBuffer, format, arg);

   va_end(arg);
}

int main()
{
   char buffer[1000] = { 0 };
   const char* abc = "abc";
   const char* def = "def";

   MyPrintFunc(buffer, 1000, "%s", abc);
   MyPrintFunc(buffer, 1000, "%s%s", buffer, def);
   printf("%s\n", buffer);
   return 0;
}
</code>```

It gave different output on both Windows and Linux.
On Windows (using msvc-14.0 compiler), it give desired output of abcdef.

But on Linux (using gcc-5.4), it only print output of def.

How can I get the correct output?

答:
Thanks everyone for the input.

My solution to this is to create a copy of the buffer if user of the MyPrintFunc() used it to append buffer:

```<code>void MyPrintFunc(char *buffer, size_t sizeOfBuffer, const char* format, ...)
{
   va_list arg;
   va_list arg_copy;

   va_start(arg, format);
   va_copy(arg_copy, arg);

   if (buffer == va_arg(arg, char*))
   {
      char temp[strlen(buffer)];
      strcpy(temp, buffer);
      MyPrintFunc(buffer, sizeOfBuffer, format, temp, va_arg(arg,char*));
   }
   else
   {
      vsnprintf(buffer, sizeOfBuffer, format, arg_copy);
   }

   va_end(arg);
   va_end(arg_copy);
}
</code>```

Body:
I have the following code to append a buffer using vsnprintf().

#include <stdio.h>
#include <stdarg.h>

using namespace std;

void MyPrintFunc(char *buffer, size_t sizeOfBuffer, const char* format, ...)
{
   va_list arg;
   va_start(arg, format);

   vsnprintf(buffer, sizeOfBuffer, format, arg);

   va_end(arg);
}

int main()
{
   char buffer[1000] = { 0 };
   const char* abc = "abc";
   const char* def = "def";

   MyPrintFunc(buffer, 1000, "%s", abc);
   MyPrintFunc(buffer, 1000, "%s%s", buffer, def);
   printf("%s\n", buffer);
   return 0;
}

It gave different output on both Windows and Linux.
On Windows (using msvc-14.0 compiler), it give desired output of abcdef.

But on Linux (using gcc-5.4), it only print output of def.

How can I get the correct output?

Body:
Thanks everyone for the input.

My solution to this is to create a copy of the buffer if user of the MyPrintFunc() used it to append buffer:

void MyPrintFunc(char *buffer, size_t sizeOfBuffer, const char* format, ...)
{
   va_list arg;
   va_list arg_copy;

   va_start(arg, format);
   va_copy(arg_copy, arg);

   if (buffer == va_arg(arg, char*))
   {
      char temp[strlen(buffer)];
      strcpy(temp, buffer);
      MyPrintFunc(buffer, sizeOfBuffer, format, temp, va_arg(arg,char*));
   }
   else
   {
      vsnprintf(buffer, sizeOfBuffer, format, arg_copy);
   }

   va_end(arg);
   va_end(arg_copy);
}


答:
To insert new data into an existing array use -

```<code>array_push($cars, $new_value);
</code>```

Then sort your array by using ksort

```<code>ksort($cars);
</code>```

This will give you the array as you are expecting

Title: PHP: Manipulating existing array

Body:
To insert new data into an existing array use -

array_push($cars, $new_value);

Then sort your array by using ksort

ksort($cars);

This will give you the array as you are expecting


问:
Posting Array in Javascript
First, I want to thank stack overflow before posting this. Here's the scenario. I want to Post Array [["a","b"],["c","d"]] in javascript. And Return data as the same [["a","b"],["c","d"]]. But I got these value - "[[\"a\",\"b\"],[\"c\",\"d\"]]"

Thanks in advance.

var arraylist = [["a","b"],["c","d"]];

```<code>$.ajax({
async: true,
type: "POST",
url: "/TestReciever.cshtml",
data: JSON.stringify(arraylist),
success: function (data) {
    alert(data);
    }
});
</code>```

My TestReciever.cshtml code is :

```<code>string input;
using (var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
var j = Json.Encode(input);
Response.Write(j);
</code>```

答:
In your code

```<code>string input;
using (var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
// Your are encoding the JSON data to STRING
   var j = Json.Encode(input);  // Its like doing JSON.stringify in JS
   Response.Write(j);
</code>```

This line var j = Json.Encode(input); is converting your JSON to an string. what its doing in your code is that as your JSON consist of double quotes in its structure. so, its basically escapes them. like  from [["a","b"],["c","d"]] to "[[\"a\",\"b\"],[\"c\",\"d\"]]";

In javascript you need to do JSON.parse(YOUR_RESPONSE) to read the data as a array.

```<code>$.ajax({
async: true,
type: "POST",
url: "/TestReciever.cshtml",
data: JSON.stringify(arraylist),
success: function (data) {
       var your_array = JSON.parse(data); //This will parse your string to ARRAY
       /* NOW USE YOUR ARRAY HERE AS A NORMAL ARRAY*/
    }
});
</code>```

For more information on JSON.parse

The JSON.parse() method parses a JSON string, constructing the
  JavaScript value or object described by the string. An optional
  reviver function can be provided to perform a transformation on the
  resulting object before it is returned.

If your are confused if array can be a JSON here is an great answer.

Title: Posting Array in Javascript

Body:
First, I want to thank stack overflow before posting this. Here's the scenario. I want to Post Array [["a","b"],["c","d"]] in javascript. And Return data as the same [["a","b"],["c","d"]]. But I got these value - "[[\"a\",\"b\"],[\"c\",\"d\"]]"

Thanks in advance.

var arraylist = [["a","b"],["c","d"]];

$.ajax({
async: true,
type: "POST",
url: "/TestReciever.cshtml",
data: JSON.stringify(arraylist),
success: function (data) {
    alert(data);
    }
});

My TestReciever.cshtml code is :

string input;
using (var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
var j = Json.Encode(input);
Response.Write(j);

Body:
In your code

string input;
using (var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
// Your are encoding the JSON data to STRING
   var j = Json.Encode(input);  // Its like doing JSON.stringify in JS
   Response.Write(j);

This line var j = Json.Encode(input); is converting your JSON to an string. what its doing in your code is that as your JSON consist of double quotes in its structure. so, its basically escapes them. like  from [["a","b"],["c","d"]] to "[[\"a\",\"b\"],[\"c\",\"d\"]]";

In javascript you need to do JSON.parse(YOUR_RESPONSE) to read the data as a array.

$.ajax({
async: true,
type: "POST",
url: "/TestReciever.cshtml",
data: JSON.stringify(arraylist),
success: function (data) {
       var your_array = JSON.parse(data); //This will parse your string to ARRAY
       /* NOW USE YOUR ARRAY HERE AS A NORMAL ARRAY*/
    }
});

For more information on JSON.parse

The JSON.parse() method parses a JSON string, constructing the
  JavaScript value or object described by the string. An optional
  reviver function can be provided to perform a transformation on the
  resulting object before it is returned.

If your are confused if array can be a JSON here is an great answer.


问:
Application freezes for some time
In my app I have a login view. When I enter login details and click login button, the app freezes for some time and then continues. I know it's freezing because it is communicating with remote server but how can I prevent the freeze thing and show a nice looking status animation instead?</p>

答:
As you are communication with server it will takes some time, so meanwhile you can add some animation on alertview.

But by calling simply alertview it will not work.

So you have to proceed in the following steps:

1) On Submit Button Click first add Custom Indication View

2) Start Animation View

3) Call NSThread for server communication like

[NSThread detachNewThreadSelector:@selector(yourActionName) toTarget:self withObject:nil];

4) Remove Animation View

For more information go through this article:
http://iphonedevcentral.blogspot.com/2010/08/safe-threaded-design-and-inter-thread.html

Title: Application freezes for some time


问:
WordPress - Run function on form submit
I am trying to do the following for users on my site.

Give the user a chance to resend their activation email if they try to login, but have not yet activated.

Check that the email they enter is in the list of current users who have not yet activated

I am trying to do this via a shortcode, so the code for the page itself is contained in the following function. I have not yet written the function to check the user against the current list of users (but have that code elsewhere, and don't necessarily need that code.
I know I need an action on the form, but this is where I come up blank, and can't seem to find answers that make sense to me.

```<code>function resend_activation_email_form() {
echo 'Activation Email Form<br>';
echo '<form><input type="email"><br>';
echo '<button type="submit">Resend Activation Email</button></form>';
}
add_shortcode('resend_activation','resend_activation_email_form');
</code>```

答:
add action to your form and then add condition to your shortcode

```<code>add_shortcode('resend_activation','resend_activation_email_form');
$post_arr = array();
if(isset($_POST['reSendMail']))
{
$post_arr = $_POST;
}
do_shortcode('[resend_activation passdata='.$post_arr.']');
</code>```

modified function

```<code>function resend_activation_email_form($attr) {
var_dump($attr);
    if(isset($attr['passdata']) && !empty($attr))
    {
        var_dump($attr);
    }
    else
    {
    echo 'Activation Email Form<br>';
    echo '<form action=""><input type="email"><br>';
    echo '<button name="reSendMail" type="submit">Resend Activation Email</button></form>';
    }
}
</code>```

Title: WordPress - Run function on form submit

Body:
I am trying to do the following for users on my site.

Give the user a chance to resend their activation email if they try to login, but have not yet activated.

Check that the email they enter is in the list of current users who have not yet activated

I am trying to do this via a shortcode, so the code for the page itself is contained in the following function. I have not yet written the function to check the user against the current list of users (but have that code elsewhere, and don't necessarily need that code.
I know I need an action on the form, but this is where I come up blank, and can't seem to find answers that make sense to me.

function resend_activation_email_form() {
echo 'Activation Email Form
';
echo '<form><input type="email">
';
echo '<button type="submit">Resend Activation Email</button></form>';
}
add_shortcode('resend_activation','resend_activation_email_form');

Body:
add action to your form and then add condition to your shortcode

add_shortcode('resend_activation','resend_activation_email_form');
$post_arr = array();
if(isset($_POST['reSendMail']))
{
$post_arr = $_POST;
}
do_shortcode('[resend_activation passdata='.$post_arr.']');

modified function

function resend_activation_email_form($attr) {
var_dump($attr);
    if(isset($attr['passdata']) && !empty($attr))
    {
        var_dump($attr);
    }
    else
    {
    echo 'Activation Email Form<br>';
    echo '<form action=""><input type="email"><br>';
    echo '<button name="reSendMail" type="submit">Resend Activation Email</button></form>';
    }
}


问:
Grpc cannot resolve symbol GreeterGrpc
I am following the link https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples/helloworld here to try to get grpc working.

this is the final folder structure.

And my HelloWorldServer.java is the same as https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java, except the package name.

but Intellij tells that it cannot resolve symbol GreeterGrpc.

Could someone help me out of here please?

答:
Notice that GreeterGrpc.java is under generated-sources,
but IntelliJ doesn't know it's a source file.

I see that target/generated-sources/protobuf/java is marked as generated sources root, but target/generated-sources/protobuf/grpc-java is not.
Normally IntelliJ picks this up from the configuration in pom.xml.
Maybe you don't have something correctly configured there.
You could try to reimport the Maven module by right-click on pom.xml,
and select Maven and then Reimport.
The icon of grpc-java should change to blue with a gear,
like java at the same directory level.

If that doesn't work,
then you could mark grpc-java as a generated source root manually:
right-click on it, select Mark Directory as and then Generated Sources Root.

Title: Grpc cannot resolve symbol GreeterGrpc


问:
Android AlertDialog Not Displaying Entire XML
Bit of an odd problem, I have a layout that opens as an AlertDialog in my Android app but for some reason only the second of two LinearLayouts in the xml file is displayed. I didn't realize it was possible for a layout to have its views partially ignored. Oddly enough, the layout is drawn correctly if I use a PopupWindow instead of an AlertDialog, so I think theres some difference between the two causing the issue.

The XML layout in question is below. At its root, its a LinearLayout with two children, with respective weights 0.10 and 0.90. When drawn, the layout with weight 0.90 fills the entire parent and the layout with weight 0.10 is nowhere to be found. Changing these weight values does nothing to remedy this.

What is the fix?

menu_popup_set_chords.xml

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">

<!-- This is the missing Layout on draw -->
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:orientation="vertical"
    android:layout_weight="0.10"
    android:background="#000000">
</LinearLayout>

<!-- This layout fills the entire dialog window instead of 90% of it -->
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#212121"
    android:layout_weight="0.90">

    <LinearLayout
        android:layout_weight="1.40"
        android:layout_width="0dp"
        android:layout_height="match_parent">

        <!-- Custom view for Canvas -->
        <com.example.foo.CustomChordCanvas
            android:id="@+id/chordCanvas"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/neck_hud_background_alpha85"/>

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:padding="8dp"
        android:layout_weight="3.60"
        android:layout_width="0dp"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="3.10">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_userChords"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5">

            <LinearLayout
                android:id="@+id/fl_actionButtons"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_weight="0.5"
                    android:layout_width="0dp"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.AppCompatImageButton
                        android:id="@+id/addMarker"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:padding="16dp"
                        android:clickable="true"
                        android:src="@drawable/ic_add_circle_black_24dp"
                        android:background="@android:color/transparent"
                        android:tint="#C4252C"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_weight="0.5"
                    android:layout_width="0dp"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.AppCompatImageButton
                        android:id="@+id/removeMarker"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:background="@android:color/transparent"
                        android:padding="16dp"
                        android:src="@drawable/ic_remove_circle_black_24dp"
                        android:tint="#C4252C"/>

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

For comprehensiveness, heres the code that builds and shows the AlertDialog in question:

FragmentChordMenu.java

```<code>public class FragmentChordMenu extends Fragment implements CustomChordAdapter.onItemClickListener {
public static int chordCanvasWidth, chordCanvasHeight;

private static RecyclerView mCustomChordList;
private static CustomChordAdapter mRecyclerViewAdapter;
private static Context mContext;

private FloatingActionButton mFAB;
private View mPopupView;
private AlertDialog mDialogChordMenu;
private CustomChordCanvas chordCanvas;
private ImageButton btnAddMarker, btnRemoveMarker;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mRecyclerViewAdapter = new CustomChordAdapter(this);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    mContext = getActivity();   //stores application context for later use in fragment without risk
                                                        //of detachment

    View v = inflater.inflate(R.layout.menu_fragment_chord, container, false);
    LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mPopupView = layoutInflater.inflate(R.layout.menu_popup_set_chords, null);

    mDialogChordMenu = new AlertDialog.Builder(getActivity()).setView(mPopupView).create();

    chordCanvas = (CustomChordCanvas) mPopupView.findViewById(R.id.chordCanvas);

    ...

    //This method fetches view parameters for one of the Dialog child layout
    //A ViewTreeObserver is used to allow view parameters to be accessed BEFORE view is drawn on screen
    ViewTreeObserver viewTreeObserver = chordCanvas.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                chordCanvas.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                chordCanvasWidth = chordCanvas.getMeasuredWidth();
                chordCanvasHeight = chordCanvas.getMeasuredHeight();
                CustomChordCanvas.setViewParams(chordCanvasWidth, chordCanvasHeight);
            }
        });
    }

    mFAB = (FloatingActionButton) v.findViewById(R.id.addChord);
    mFAB.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mDialogChordMenu.show();
            mCustomChordList = (RecyclerView) mPopupView.findViewById(R.id.rv_userChords);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            mCustomChordList.setLayoutManager(layoutManager);
            mCustomChordList.setAdapter(mRecyclerViewAdapter);
        }
    });

    return v;
}
...}
</code>```

答: Set some default height to custom layout of dialog.</p>

Body:
Bit of an odd problem, I have a layout that opens as an AlertDialog in my Android app but for some reason only the second of two LinearLayouts in the xml file is displayed. I didn't realize it was possible for a layout to have its views partially ignored. Oddly enough, the layout is drawn correctly if I use a PopupWindow instead of an AlertDialog, so I think theres some difference between the two causing the issue.

The XML layout in question is below. At its root, its a LinearLayout with two children, with respective weights 0.10 and 0.90. When drawn, the layout with weight 0.90 fills the entire parent and the layout with weight 0.10 is nowhere to be found. Changing these weight values does nothing to remedy this.

What is the fix?

menu_popup_set_chords.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:orientation="vertical"
    android:layout_weight="0.10"
    android:background="#000000">
</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#212121"
    android:layout_weight="0.90">

    <LinearLayout
        android:layout_weight="1.40"
        android:layout_width="0dp"
        android:layout_height="match_parent">

        <com.example.foo.CustomChordCanvas
            android:id="@+id/chordCanvas"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/neck_hud_background_alpha85"/>

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:padding="8dp"
        android:layout_weight="3.60"
        android:layout_width="0dp"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="3.10">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_userChords"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5">

            <LinearLayout
                android:id="@+id/fl_actionButtons"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_weight="0.5"
                    android:layout_width="0dp"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.AppCompatImageButton
                        android:id="@+id/addMarker"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:padding="16dp"
                        android:clickable="true"
                        android:src="@drawable/ic_add_circle_black_24dp"
                        android:background="@android:color/transparent"
                        android:tint="#C4252C"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_weight="0.5"
                    android:layout_width="0dp"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.AppCompatImageButton
                        android:id="@+id/removeMarker"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:background="@android:color/transparent"
                        android:padding="16dp"
                        android:src="@drawable/ic_remove_circle_black_24dp"
                        android:tint="#C4252C"/>

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

For comprehensiveness, heres the code that builds and shows the AlertDialog in question:

FragmentChordMenu.java

public class FragmentChordMenu extends Fragment implements CustomChordAdapter.onItemClickListener {
public static int chordCanvasWidth, chordCanvasHeight;

private static RecyclerView mCustomChordList;
private static CustomChordAdapter mRecyclerViewAdapter;
private static Context mContext;

private FloatingActionButton mFAB;
private View mPopupView;
private AlertDialog mDialogChordMenu;
private CustomChordCanvas chordCanvas;
private ImageButton btnAddMarker, btnRemoveMarker;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mRecyclerViewAdapter = new CustomChordAdapter(this);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    mContext = getActivity();   //stores application context for later use in fragment without risk
                                                        //of detachment

    View v = inflater.inflate(R.layout.menu_fragment_chord, container, false);
    LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mPopupView = layoutInflater.inflate(R.layout.menu_popup_set_chords, null);

    mDialogChordMenu = new AlertDialog.Builder(getActivity()).setView(mPopupView).create();

    chordCanvas = (CustomChordCanvas) mPopupView.findViewById(R.id.chordCanvas);

    ...

    //This method fetches view parameters for one of the Dialog child layout
    //A ViewTreeObserver is used to allow view parameters to be accessed BEFORE view is drawn on screen
    ViewTreeObserver viewTreeObserver = chordCanvas.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                chordCanvas.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                chordCanvasWidth = chordCanvas.getMeasuredWidth();
                chordCanvasHeight = chordCanvas.getMeasuredHeight();
                CustomChordCanvas.setViewParams(chordCanvasWidth, chordCanvasHeight);
            }
        });
    }

    mFAB = (FloatingActionButton) v.findViewById(R.id.addChord);
    mFAB.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mDialogChordMenu.show();
            mCustomChordList = (RecyclerView) mPopupView.findViewById(R.id.rv_userChords);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            mCustomChordList.setLayoutManager(layoutManager);
            mCustomChordList.setAdapter(mRecyclerViewAdapter);
        }
    });

    return v;
}
...}


问:
Are animations with ng-style possible? (AngularJS)
I have a div set to a dynamic height called option.height using AngularJS's ng-style attribute.

```<code><div class="rec" ng-style="{ 'height': option.height, 'background-color': option.color}"></div>
</code>```

When the page is loaded, the height may be set to anything from 0px to 300px, depending on earlier user input. While this works, I want the div height to animate from 0px to whatever value option.height is using CSS animations, instead of just starting at the correct height. Is this possible? How should I approach this?

答:
You can use CSS keyframes with the from property.

This will animate it to the specified height from 0px.

Something like:

```<code>@keyframes AnimHeight{
  from{
    height:0px;
  }
}
</code>```

Example:

.res {
  animation: AnimHeight 0.5s ease;
}

@-webkit-keyframes AnimHeight {
  from {
    height: 0px;
  }
}

@-moz-keyframes AnimHeight {
  from {
    height: 0px;
  }
}

@-o-keyframes AnimHeight {
  from {
    height: 0px;
  }
}

@keyframes AnimHeight {
  from {
    height: 0px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="res" style="height:100px;background:red;width:100%;">
</div></code>```

EDIT : Added all the vendor specifics for keyframes.

Body:
I have a div set to a dynamic height called option.height using AngularJS's ng-style attribute.

When the page is loaded, the height may be set to anything from 0px to 300px, depending on earlier user input. While this works, I want the div height to animate from 0px to whatever value option.height is using CSS animations, instead of just starting at the correct height. Is this possible? How should I approach this?

Body:
You can use CSS keyframes with the from property.

This will animate it to the specified height from 0px.

Something like:

@keyframes AnimHeight{
  from{
    height:0px;
  }
}

Example:

.res {
  animation: AnimHeight 0.5s ease;
}

@-webkit-keyframes AnimHeight {
  from {
    height: 0px;
  }
}

@-moz-keyframes AnimHeight {
  from {
    height: 0px;
  }
}

@-o-keyframes AnimHeight {
  from {
    height: 0px;
  }
}

@keyframes AnimHeight {
  from {
    height: 0px;
  }
}

<div class="res" style="height:100px;background:red;width:100%;">
</div>

EDIT : Added all the vendor specifics for keyframes.


问:
How to kill background process from system function call
How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

```<code>const char app[] = "fooprocess &";
system(app);
</code>```

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.

答:
I have tried your problem using this:

```<code>ps -axc|grep -i myApp|awk '{print $1}' | tr -d '\n' | xargs -0 kill
</code>```

you can place that in system() like so:

```<code>system("ps -axc|grep -i myApp|awk '{print $1}' | tr -d '\n' | xargs -0 kill");
</code>```

That will work.

Body:
How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

const char app[] = "fooprocess &";
system(app);

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.

Body:
I have tried your problem using this:

ps -axc|grep -i myApp|awk '{print $1}' | tr -d '\n' | xargs -0 kill

you can place that in system() like so:

system("ps -axc|grep -i myApp|awk '{print $1}' | tr -d '\n' | xargs -0 kill");

That will work.


答: It looks like your problem is in the cs-code, not the javascript. The line var j = Json.Encode(input); will json-encode the already json-encoded string coming from your site. If you simply return your input, you should get the correct json back.

Title: Posting Array in Javascript