问:
Determine if request is PartialView or AJAX request in ASP.NET MVC 3
I have to give access rigths to the users of a website.
I am doing the filtering here:

```<code>protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
</code>```

The problem is that I cannot distinguish full View request such as 'Index' from PartialViewRequests or AJAX calls requests.

Therefore the page 'Index' has access but the 'PartialViewGridViewForIndex' does not have access.

The property ControllerContext.IsChildAction does not help either.

答:
You can extend HttpRequestExtensions in asp.net Core 2 as below

```<code>public static class HttpRequestExtensions
{
    private const string RequestedWithHeader = "X-Requested-With";
    private const string XmlHttpRequest = "XMLHttpRequest";

    public static bool IsAjaxRequest(this HttpRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        if (request.Headers != null)
        {
            return request.Headers[RequestedWithHeader] == XmlHttpRequest;
        }

        return false;
    }
}
</code>```

And use it as

```<code> if (!Request.IsAjaxRequest())
 {
    //----
  }
  else
  {
      // -------
  }
</code>```

Body:
I have to give access rigths to the users of a website.
I am doing the filtering here:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
}

The problem is that I cannot distinguish full View request such as 'Index' from PartialViewRequests or AJAX calls requests.

Therefore the page 'Index' has access but the 'PartialViewGridViewForIndex' does not have access.

The property ControllerContext.IsChildAction does not help either.

Body:
You can extend HttpRequestExtensions in asp.net Core 2 as below

public static class HttpRequestExtensions
{
    private const string RequestedWithHeader = "X-Requested-With";
    private const string XmlHttpRequest = "XMLHttpRequest";

    public static bool IsAjaxRequest(this HttpRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        if (request.Headers != null)
        {
            return request.Headers[RequestedWithHeader] == XmlHttpRequest;
        }

        return false;
    }
}

And use it as

 if (!Request.IsAjaxRequest())
 {
    //----
  }
  else
  {
      // -------
  }


来源: stackexchange

问:
How do I get the value of expression string in sqlite within query?
I want math expression string('(0.98/0.62)') in a column to be evaluated within query.

I expect "select '(0.98/0.62)'" to return 0.98/0.62=1.58... not '(0.98/0.62)'.

答:
SQLite is designed as an embedded database, so it does not have any built-in mechanism to execute dynamic SQL.

It would be possible to register a user-defined function that executes an SQL expression.

ContentLicense: CC BY-SA 3.0


问:
get value from key in sessionStorage javascript
Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

```<code>  if(sessionStorage.getItem("item") == "5");
</code>```

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?

答:
I dont know if I understood you correctly, but I assume you have item in your session storage, e.g.:

sessionStorage.setItem("item", 12345)

Then, you want to check if there is a number 5 in it. You can do it by typing

sessionStorage.getItem("item").indexOf(5) > -1

Body:
Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

  if(sessionStorage.getItem("item") == "5");

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?


问:
Editing table data in Angular 4
I am simply trying to display, add, delete & update the employee table in Angular. Here is the image of the table:

As of now I have disabled each field of the table. Whenever i click on 'Edit' button i want the field of the corresponding row to be enabled so i can edit right on!

Here are my files:

employee-data.component.ts

```<code>import { Component } from '@angular/core';
import { Employee } from './employee';
import { NgForm } from '@angular/forms';
import { promise } from 'selenium-webdriver';

@Component({
selector: 'employee-data',
templateUrl: './employee-data.component.html',
})

export class EmployeeDataComponent {

id: number;
name: string;
address: string;
gender: string;
company: string;

//emp: Employee[] = [];

employees: Employee[] = [
    {
        id: 1,
        name: 'Ram',
        address: 'Kupondole',
        gender: 'Male',
        company: 'XYZ Techno Sales'
    },
    {
        id: 2,
        name: 'Shyam',
        address: 'Baneshwor',
        gender: 'Male',
        company: 'ABC Enterprises'
    },
    {
        id: 3,
        name: 'Prashansha',
        address: 'Tripureshwor',
        gender: 'Female',
        company: 'MNO Inc'
    },
    {
        id: 4,
        name: 'Rita',
        address: 'Ghatthaghar',
        gender: 'Female',
        company: 'Subisu'
    }
];

addRow() {
    //prompt("Checking the control!");
    this.employees.push({
        id: this.id,
        name: this.name,
        address: this.address,
        gender: this.gender,
        company: this.company
    });
}

deleteEmployee(index) {

    this.employees.splice(index, 1);
}

editEmployee(index) {

    //code for editing

}
</code>```

}

employee-data.component.html

```<code><table border="1">
<thead>
    <tr>
        <td>Id</td>
        <td>Name</td>
        <td>Address</td>
        <td>Gender</td>
        <td>Company</td>
        <td>Action</td>
    </tr>
</thead>

<tbody>
    <tr *ngFor="let employee of employees; let i= index;">
        <td>
            <input type="number" min="1" [(ngModel)]="employee.id" disabled>
        </td>
        <td>
            <input type="text" [(ngModel)]="employee.name" disabled>
        </td>
        <td>
            <input type="text" [(ngModel)]="employee.address" disabled>
        </td>
        <td>
            <input type="text" [(ngModel)]="employee.gender" disabled>
        </td>
        <td>
            <input type="text" [(ngModel)]="employee.company" disabled>
        </td>
        <td>
            <div>
                <button (click)="editEmployee(i)">Edit</button>
                <button (click)="deleteEmployee(i)">Delete</button>
            </div>
        </td>
    </tr>
</tbody>
</table>
<hr>
<br>
<h1>Add an Employee</h1>

<form>
<div>
    <label>Id</label>
    <div>
        <input type="number" class="" name="id"
        [(ngModel)]="id" required />
    </div>
</div>

<div>
    <label>Name</label>
    <div>
        <input type="text" class="" name="name"
        [(ngModel)]="name" required />
    </div>
</div>
<div>
    <label>Address</label>
    <div>
        <input type="text" class="" name="address"
        [(ngModel)]="address" required />
    </div>
</div>
<div>
    <label>Gender</label>
    <div>
        <input type="text" class="" name="gender"
        [(ngModel)]="gender" required />
    </div>
</div>
<div>
    <label>Company</label>
    <div>
        <input type="text" class="" name="company"
        [(ngModel)]="company" required />
    </div>
</div>
<div>
    <div>
        <input type="submit" value="Submit" class=""
           (click)="addRow()" />
    </div>
</div>
</form>
</code>```

How can i edit the row? And I am using Angular 4

答:
You can use a property like isEditable with employee and use it to disable or enable editing something like

```<code><input type="text" [(ngModel)]="employee.name"  [disabled]="!employee.isEditable">
</code>```

Then enable on edit button click

```<code><button (click)="employee.isEditable=!employee.isEditable" *ngIf="!employee.isEditable">Edit</button>
</code>```

Check this demo

Title: Editing table data in Angular 4

Body:
I am simply trying to display, add, delete & update the employee table in Angular. Here is the image of the table:

As of now I have disabled each field of the table. Whenever i click on 'Edit' button i want the field of the corresponding row to be enabled so i can edit right on!

Here are my files:

employee-data.component.ts

import { Component } from '@angular/core';
import { Employee } from './employee';
import { NgForm } from '@angular/forms';
import { promise } from 'selenium-webdriver';

@Component({
selector: 'employee-data',
templateUrl: './employee-data.component.html',
})

export class EmployeeDataComponent {

id: number;
name: string;
address: string;
gender: string;
company: string;

//emp: Employee[] = [];

employees: Employee[] = [
    {
        id: 1,
        name: 'Ram',
        address: 'Kupondole',
        gender: 'Male',
        company: 'XYZ Techno Sales'
    },
    {
        id: 2,
        name: 'Shyam',
        address: 'Baneshwor',
        gender: 'Male',
        company: 'ABC Enterprises'
    },
    {
        id: 3,
        name: 'Prashansha',
        address: 'Tripureshwor',
        gender: 'Female',
        company: 'MNO Inc'
    },
    {
        id: 4,
        name: 'Rita',
        address: 'Ghatthaghar',
        gender: 'Female',
        company: 'Subisu'
    }
];

addRow() {
    //prompt("Checking the control!");
    this.employees.push({
        id: this.id,
        name: this.name,
        address: this.address,
        gender: this.gender,
        company: this.company
    });
}

deleteEmployee(index) {

    this.employees.splice(index, 1);
}

editEmployee(index) {

    //code for editing

}

}

employee-data.component.html

        Id
        Name
        Address
        Gender
        Company
        Action

            <input type="number" min="1" [(ngModel)]="employee.id" disabled>

            <input type="text" [(ngModel)]="employee.name" disabled>

            <input type="text" [(ngModel)]="employee.address" disabled>

            <input type="text" [(ngModel)]="employee.gender" disabled>

            <input type="text" [(ngModel)]="employee.company" disabled>

                <button (click)="editEmployee(i)">Edit</button>
                <button (click)="deleteEmployee(i)">Delete</button>

Add an Employee

<form>

    Id

        <input type="number" class="" name="id"
        [(ngModel)]="id" required />

    Name

        <input type="text" class="" name="name"
        [(ngModel)]="name" required />

    Address

        <input type="text" class="" name="address"
        [(ngModel)]="address" required />

    Gender

        <input type="text" class="" name="gender"
        [(ngModel)]="gender" required />

    Company

        <input type="text" class="" name="company"
        [(ngModel)]="company" required />

        <input type="submit" value="Submit" class=""
           (click)="addRow()" />

</form>

How can i edit the row? And I am using Angular 4

Body:
You can use a property like isEditable with employee and use it to disable or enable editing something like

<input type="text" [(ngModel)]="employee.name"  [disabled]="!employee.isEditable">

Then enable on edit button click

<button (click)="employee.isEditable=!employee.isEditable" *ngIf="!employee.isEditable">Edit</button>

Check this demo

ContentLicense: CC BY-SA 4.0


问:
Python error: global variable in class undefined
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.</p>

```<code>class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result
</code>```

答:
You probably only need instance variables:

```<code>class Message():
    def __init__(self):
        self.insertStatement= ''
        self.insertCounter = 0

    def Save(self, msg)
        if msg.topic.startswith("topic1/"):
            self.insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
        elif msg.topic.startswith("topic2/"):
            self.insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
        elif msg.topic.startswith("topic3/")
            self.insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
        elif msg.topic.startswith("messages"):
            self.insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
        else:
            return
        self.insertcounter += 1
        if self.insertCounter > 1000:
            # do the SQL thing
</code>```

As a programmer you should try very, very, very hard to not use global variables.

Body:
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.

class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result

Body:
You probably only need instance variables:

class Message():
    def __init__(self):
        self.insertStatement= ''
        self.insertCounter = 0

    def Save(self, msg)
        if msg.topic.startswith("topic1/"):
            self.insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
        elif msg.topic.startswith("topic2/"):
            self.insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
        elif msg.topic.startswith("topic3/")
            self.insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
        elif msg.topic.startswith("messages"):
            self.insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
        else:
            return
        self.insertcounter += 1
        if self.insertCounter > 1000:
            # do the SQL thing

As a programmer you should try very, very, very hard to not use global variables.


问:
Query to get username from child table with specific condition
I have a table Admin and a child table AdminOfArea. I want to get the user name from Table2 where username only have one Region not multiple which is Liverpool. in this case only A and B are according to this scenario.

Table 1 looks like

```<code>|Username |  UserType  |
|  abc    |  Admin     |
|   A     |  Admin     |
|  xyz    |  Admin     |
|   B     |  Admin     |
</code>```

Table 2 looks like

```<code>|UserName  Region    |
| abc     Wales      |
| abc     Liverpool  |
| abc     Westsussex |
| A       Liverpool  |
| xyz     Wales      |
| xyz     Liverpool  |
| xyz     Westsussex |
| B       Liverpool  |
</code>```

答:
Here is one method that should work in any database:</p>

```<code>select t1.*, t2.region
from table1 t1 join
     (select t2.username, max(region) as region
      from table2 t2
      group by t2.username
      having count(*) = 1
     ) t2
     on t1.username = t2.username;
</code>```

Body:
I have a table Admin and a child table AdminOfArea. I want to get the user name from Table2 where username only have one Region not multiple which is Liverpool. in this case only A and B are according to this scenario.

Table 1 looks like

|Username |  UserType  |
|  abc    |  Admin     |
|   A     |  Admin     |
|  xyz    |  Admin     |
|   B     |  Admin     |

Table 2 looks like

|UserName  Region    |
| abc     Wales      |
| abc     Liverpool  |
| abc     Westsussex |
| A       Liverpool  |
| xyz     Wales      |
| xyz     Liverpool  |
| xyz     Westsussex |
| B       Liverpool  |

Body:
Here is one method that should work in any database:

select t1.*, t2.region
from table1 t1 join
     (select t2.username, max(region) as region
      from table2 t2
      group by t2.username
      having count(*) = 1
     ) t2
     on t1.username = t2.username;


问:
Resizing Flash in IE8 is buggy
Problem

When resizing a Flash object in IE, it's resize handler incorrectly thinks that only the stage width has been updated.

Steps for reproducing the bug

You roll over and click a Flash
button

The button makes an
ExternalInterface call to JS. JS
resizes Flash among other things.

In
all non-IE browsers, Flash is
notified of the dimension change and
executes its resize handler flawlessly.
In IE8,
the resize handler is called but is
only its stage width has been updated. It still believes its height is the same.

To finally get IE8's Flash to acknowledge its true height, roll your mouse out of the SWF.

Actionscript

```<code>package {
 import flash.external.*;
 public class Player {
  public function Player(container:Stage) {
   this.container.addEventListener(Event.RESIZE, this.onResize);
  }
  public function expand():void {
   ExternalInterface.call('expand');
  }
  public function onResize():void {
   // float chrome buttons to the right
   // float chrome to the bottom
  }
 }
}
</code>```

Javascript

```<code>// Using Prototype framework
function expand() {
 $('flash').setStyle({
   width: '500px',
   height: '400px'
 });
 // do other stuff in JS too
}
</code>```

The listener gets triggered fine in all browsers except Internet Explorer. There's no problem with the Javascript - I see the Flash getting resized. But the Actionscript listener doesn't get fired until I my mouse moves out of the SWF. What do I need to know about IE's rendering engine to fix this?

Before

After - IE's Flash is notified of the width change, but still thinks it's height is the same.

Move mouse out of SWF - you must roll your mouse out of the SWF for Flash to acknowledge its true height in IE8

答: I solved this by setting Flash's height a 2nd time. Even though it's set to the same height, it tricks IE to redraw the page. </p>

ContentLicense: CC BY-SA 2.5

Title: Resizing Flash in IE8 is buggy

Body:
Problem

When resizing a Flash object in IE, it's resize handler incorrectly thinks that only the stage width has been updated.

Steps for reproducing the bug

You roll over and click a Flash
button

The button makes an
ExternalInterface call to JS. JS
resizes Flash among other things.

In
all non-IE browsers, Flash is
notified of the dimension change and
executes its resize handler flawlessly.
In IE8,
the resize handler is called but is
only its stage width has been updated. It still believes its height is the same.

To finally get IE8's Flash to acknowledge its true height, roll your mouse out of the SWF.

Actionscript

package {
 import flash.external.*;
 public class Player {
  public function Player(container:Stage) {
   this.container.addEventListener(Event.RESIZE, this.onResize);
  }
  public function expand():void {
   ExternalInterface.call('expand');
  }
  public function onResize():void {
   // float chrome buttons to the right
   // float chrome to the bottom
  }
 }
}

Javascript

// Using Prototype framework
function expand() {
 $('flash').setStyle({
   width: '500px',
   height: '400px'
 });
 // do other stuff in JS too
}

The listener gets triggered fine in all browsers except Internet Explorer. There's no problem with the Javascript - I see the Flash getting resized. But the Actionscript listener doesn't get fired until I my mouse moves out of the SWF. What do I need to know about IE's rendering engine to fix this?

Before

After - IE's Flash is notified of the width change, but still thinks it's height is the same.

Move mouse out of SWF - you must roll your mouse out of the SWF for Flash to acknowledge its true height in IE8


问:
How do I parse an HTML response to JSON by using X-Path?
I am getting a HTML response from HTTPGET method. How do I parse that html response to JSON?

Which API do I use to parse it?

I also want to know what is the main use of x-path.
HTML Response:

```<code><!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />
</code>```

答:
You can use jsoup as a tool to convert your HTML to JSON.</p>

```<code>final String HTML = "<!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />";
Document document = Jsoup.parse(HTML);
Element element = document.select("ANY HTML TAG").first();
String arrayName = element.select("TAG2").first().text();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
Elements ie = element.getElementsByClass("ie");
Elements ei9 = element.getElementsByClass("ei9");
JSONObject jobj = new JSONObject();
for (int i = 0, l = ie.size(); i < l; i++) {
    String key = ie.get(i).text();
    String value = ei9.get(i).text();
    jobj.put(key, value);
}
jsonArr.put(jobj);
jsonObj.put(arrayName, jsonArr);
System.out.println(jsonObj.toString());
</code>```

Body:
I am getting a HTML response from HTTPGET method. How do I parse that html response to JSON?

Which API do I use to parse it?

I also want to know what is the main use of x-path.
HTML Response:

<!DOCTYPE html> <[if IE 8]>  <![endif]> <[if IE 9]>  <![endif]> <if IE]>  <![endif] <[if gt IE 9]>  <![endif]  <link rel="dns-prefetch" href="i1.sdlcdn.com"; />

Body:
You can use jsoup as a tool to convert your HTML to JSON.

final String HTML = "<!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />";
Document document = Jsoup.parse(HTML);
Element element = document.select("ANY HTML TAG").first();
String arrayName = element.select("TAG2").first().text();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
Elements ie = element.getElementsByClass("ie");
Elements ei9 = element.getElementsByClass("ei9");
JSONObject jobj = new JSONObject();
for (int i = 0, l = ie.size(); i < l; i++) {
    String key = ie.get(i).text();
    String value = ei9.get(i).text();
    jobj.put(key, value);
}
jsonArr.put(jobj);
jsonObj.put(arrayName, jsonArr);
System.out.println(jsonObj.toString());


问:
Win32_NetworkAdapter.Index and Win32_IP4RouteTable.InterfaceIndex do not match
I am writing a script that would update DNS servers list on Windows 7 machines for the interfaces that pass traffic for default routes.

I have selected the route table entries with

```<code>$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable |
    Where-Object {$_.Destination -eq "0.0.0.0"}
</code>```

and assuming the list of interfaces obtained with Win32_NetworkAdapterConfiguration is in the $interfaces variable defined as

```<code>$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration
</code>```

I expected to join the two lists on condition $route.InterfaceIndex -eq $interface.Index. However I noticed that the indices do not match.

The route table has the following interface definitions:

```<code>C:\Users\user01>route print if 11
===========================================================================
Interface list
  ....
 13...08 00 27 8d 7e 19 ......Intel(R) PRO/1000 MT #2
 11...08 00 27 a4 16 ad ......Intel(R) PRO/1000 MT
 12...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
  ...
</code>```

However the $interface list has

```<code>ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT
Index            : 7

ServiceName      : tunnel
Description      : Tunnel adapter Microsoft Teredo
Index            : 11

ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT #2
Index            : 13
</code>```

That is in both lists Intel(R) PRO/1000 MT #2 has index 13, however Intel(R) PRO/1000 MT is 11 in one list and 7 in the other list. What could be the reason for this "seven-eleven" discrepancy?

From the description of the InterfaceIndex property I would expect that the indices should match.

InterfaceIndex

IP address of the next hop of this route. The value in this property is the same as the value in the InterfaceIndex property in
  the instances of Win32_NetworkAdapter and
  Win32_NetworkAdapterConfiguration that represent the network interface
  of the next hop of the route.

答:
The following code snippet shows a possible approach to to join the two lists using -in comparison operator.

```<code>$filterDest = "Destination = '0.0.0.0'"
$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable -Filter $filterDest
$filterIPA  = "IPEnabled = True"
$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter $filterIPA

'### interfaces ###'
$interfaces |
    Where-Object {$_.InterfaceIndex -in $defaultgw_routes.Interfaceindex } |
       Select-Object [a-z]* -ExcludeProperty PSComputerName, Scope, Path, Options,
           ClassPath, Properties, SystemProperties, Qualifiers, Site, Container
'### routes ###'
$defaultgw_routes |
    Where-Object {$_.InterfaceIndex -in $interfaces.Interfaceindex } |
       Select-Object [a-z]* -ExcludeProperty PSComputerName, Scope, Path, Options,
           ClassPath, Properties, SystemProperties, Qualifiers, Site, Container
</code>```

Please note that

pipe to Where-Object is replaced with appropriate -Filter parameter to specify a Where clause to use as a filter. Uses the syntax of the WMI Query Language (WQL), and

pipe to Select-Object is added merely to avoid recurring output of well-known properties.

Body:
I am writing a script that would update DNS servers list on Windows 7 machines for the interfaces that pass traffic for default routes.

I have selected the route table entries with

$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable |
    Where-Object {$_.Destination -eq "0.0.0.0"}

and assuming the list of interfaces obtained with Win32_NetworkAdapterConfiguration is in the $interfaces variable defined as

$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration

I expected to join the two lists on condition $route.InterfaceIndex -eq $interface.Index. However I noticed that the indices do not match.

The route table has the following interface definitions:

C:\Users\user01>route print if 11
===========================================================================
Interface list
  ....
 13...08 00 27 8d 7e 19 ......Intel(R) PRO/1000 MT #2
 11...08 00 27 a4 16 ad ......Intel(R) PRO/1000 MT
 12...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
  ...

However the $interface list has

ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT
Index            : 7

ServiceName      : tunnel
Description      : Tunnel adapter Microsoft Teredo
Index            : 11

ServiceName      : E1G60
Description      : Intel(R) PRO/1000 MT #2
Index            : 13

That is in both lists Intel(R) PRO/1000 MT #2 has index 13, however Intel(R) PRO/1000 MT is 11 in one list and 7 in the other list. What could be the reason for this "seven-eleven" discrepancy?

From the description of the InterfaceIndex property I would expect that the indices should match.

InterfaceIndex

IP address of the next hop of this route. The value in this property is the same as the value in the InterfaceIndex property in
  the instances of Win32_NetworkAdapter and
  Win32_NetworkAdapterConfiguration that represent the network interface
  of the next hop of the route.

Body:
The following code snippet shows a possible approach to to join the two lists using -in comparison operator.

$filterDest = "Destination = '0.0.0.0'"
$defaultgw_routes = Get-WMIObject Win32_IP4RouteTable -Filter $filterDest
$filterIPA  = "IPEnabled = True"
$interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter $filterIPA

'### interfaces ###'
$interfaces |
    Where-Object {$_.InterfaceIndex -in $defaultgw_routes.Interfaceindex } |
       Select-Object [a-z]* -ExcludeProperty PSComputerName, Scope, Path, Options,
           ClassPath, Properties, SystemProperties, Qualifiers, Site, Container
'### routes ###'
$defaultgw_routes |
    Where-Object {$_.InterfaceIndex -in $interfaces.Interfaceindex } |
       Select-Object [a-z]* -ExcludeProperty PSComputerName, Scope, Path, Options,
           ClassPath, Properties, SystemProperties, Qualifiers, Site, Container

Please note that

pipe to Where-Object is replaced with appropriate -Filter parameter to specify a Where clause to use as a filter. Uses the syntax of the WMI Query Language (WQL), and

pipe to Select-Object is added merely to avoid recurring output of well-known properties.


问:
"No resource found that matches the given name: attr 'android:keyboardNavigationCluster'"
I found some answer for this question, that I should change compileSdkVersion 26 buildToolVersion "26.0.1"

This worked but I don't want to change my compileSdkVersion, because that causes many problems in my app like notification not working and my install app receiver is not working too.

Before updating Android Studio it was working fine, but now it gives me error.

```<code> buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}
repositories {
mavenCentral()
}
repositories {
jcenter() // includes the MoPub SDK and AVID library
maven { url "https://s3.amazonaws.com/moat-sdk-builds" }

}

android {
compileSdkVersion 25
buildToolsVersion "23.0.3"
defaultConfig {
    applicationId "com.frizza"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 29
    versionName "3.8"
}

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        proguardFile 'proguard-crashlytics.pro'
        proguardFile 'proguard-square-retrofit.pro'
        proguardFile 'proguard-square-picasso.pro'
        proguardFile 'proguard-square-okhttp.pro'
        proguardFile 'proguard-support-v7-appcompat.pro'
        proguardFile 'proguard-google-play-services.pro'
    }

}
android {
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude '.readme'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':SlidingMenu')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.picasso:picasso:2.5.2'

//    compile 'com.google.android.gms:play-services:8.4.0'
//    compile 'com.google.android.gms:play-services-gcm:7.5.0'
//    compile "com.google.android.gms:play-services-gcm:11.0.2"
compile 'com.google.android.gms:play-services-analytics:11.0.2'
compile 'com.google.android.gms:play-services-location:11.0.2'

compile "com.google.firebase:firebase-messaging:11.0.2"

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

compile files('libs/assl_sdk_rmn.jar')

//// For interstitials
//    compile('com.mopub:mopub-sdk-interstitial:4.16.1@aar') {
//        transitive = true
//    }
compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true;
}

}

apply plugin: 'com.google.gms.google-services'
</code>```

答:
It's look like setKeyboardNavigationCluster was added in API 26 for View, or support library v26.0.1.

For both cases you need to update compileSdkVersion to API 26.

Body:
I found some answer for this question, that I should change compileSdkVersion 26 buildToolVersion "26.0.1"

This worked but I don't want to change my compileSdkVersion, because that causes many problems in my app like notification not working and my install app receiver is not working too.

Before updating Android Studio it was working fine, but now it gives me error.

 buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}
repositories {
mavenCentral()
}
repositories {
jcenter() // includes the MoPub SDK and AVID library
maven { url "https://s3.amazonaws.com/moat-sdk-builds" }

}

android {
compileSdkVersion 25
buildToolsVersion "23.0.3"
defaultConfig {
    applicationId "com.frizza"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 29
    versionName "3.8"
}

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        proguardFile 'proguard-crashlytics.pro'
        proguardFile 'proguard-square-retrofit.pro'
        proguardFile 'proguard-square-picasso.pro'
        proguardFile 'proguard-square-okhttp.pro'
        proguardFile 'proguard-support-v7-appcompat.pro'
        proguardFile 'proguard-google-play-services.pro'
    }

}
android {
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude '.readme'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':SlidingMenu')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.picasso:picasso:2.5.2'

//    compile 'com.google.android.gms:play-services:8.4.0'
//    compile 'com.google.android.gms:play-services-gcm:7.5.0'
//    compile "com.google.android.gms:play-services-gcm:11.0.2"
compile 'com.google.android.gms:play-services-analytics:11.0.2'
compile 'com.google.android.gms:play-services-location:11.0.2'

compile "com.google.firebase:firebase-messaging:11.0.2"

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

compile files('libs/assl_sdk_rmn.jar')

//// For interstitials
//    compile('com.mopub:mopub-sdk-interstitial:4.16.1@aar') {
//        transitive = true
//    }
compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true;
}

}

apply plugin: 'com.google.gms.google-services'


问:
How can i customise an EditText Box to just allow currency?
i'm new to development and i'm just starting my journey into the daunting world of validation. So far i've had it easy and been able to restricted the inputtype just with these two lines: android:inputType="phone" android:digits="1234567890."

Now i want to try and stop my user from entering digits past two decimal places. I think i either need to be working with an InputFilter or using onTextChange to check for use of the decimal and digits thereafter( alas i don't have a clue how i would go about doing that either). I've got no experience with either of these and i'm having a hard time finding examples online that i can understand, If someone could tell me where to start that would be really appreciated, i think i'm on the right track but im not even sure how i'd go about checking characters let alone restricting them. Any answers welcome, thank you.

答:
Create a class that implements TextWatcher

```
class CurrencyFormatterTextWatcher implements TextWatcher {

   @Override
   public synchronized void afterTextChanged(Editable text) {
        // [...] do your formatting here; beware that each
        // change to the text value will fire another textchanged event
   }
}
```

then register it as a listener for textchanged events fired by your targeted EditText:

```
currencyFormatter = new CurrencyFormatterTextWatcher();
currencyEditText.addTextChangedListener(currencyFormatter);
```

Body:
Create a class that implements TextWatcher

class CurrencyFormatterTextWatcher implements TextWatcher {

   @Override
   public synchronized void afterTextChanged(Editable text) {
        // [...] do your formatting here; beware that each
        // change to the text value will fire another textchanged event
   }
}

then register it as a listener for textchanged events fired by your targeted EditText:

currencyFormatter = new CurrencyFormatterTextWatcher();
currencyEditText.addTextChangedListener(currencyFormatter);


问:
Is there any way to edit Information_schema in mysql
I know information schema is read only but I ran into a problem.
I've imported mysql database. Information_schema db also got copied. Its 'views' table has a definer set. I wish to change this as this is causing problems to access some tables.

It gives me access denied to root which has all the permissions and I also tried running mysql with --skip-grant-tables option but with no help.

Is there any way I can change the definer?

Note: its Innodb

答:
I have solution to the original problem I faced of not accessing the tables:
1) Create user that was not created.
2) There was actually a view which had a definer set. I dropped the view and recreated with the definer as my own user.</p>


问:
React - importing stateless component causing error
I'm trying to import a stateless component into my app and am getting the following error:

App.jsx:13 Uncaught Error: Cannot find module "./components/test"

and

Module not found: Error: Can't resolve './components/test'

Here is my code:

App.jsx

```<code>import React, {Component} from 'react';
import Username from './components/test';

class App extends Component {
  render() {
    return (
      <h1>Hello React :)</h1>
    );
  }
}
export default App;
</code>```

test.jsx

```<code>import React from 'react';

const Username = function(props) {
  return (
    <p>The logged in user is: </p>
  )
}
export default Username;
</code>```

can't understand why it's giving this error?

答:
If you want to be able to import jsx files without specifying an extension you need to modify your webpack config slightly.

You need to add .jsx to the resolve.extensions array (it defaults to [".js", ".json"] so you should set it to [".js", ".json", ".jsx"] and make sure that resolve.enforceExtension is set to false (which is the default.)

Body:
I'm trying to import a stateless component into my app and am getting the following error:

App.jsx:13 Uncaught Error: Cannot find module "./components/test"

and

Module not found: Error: Can't resolve './components/test'

Here is my code:

App.jsx

import React, {Component} from 'react';
import Username from './components/test';

class App extends Component {
  render() {
    return (

Hello React :)

    );
  }
}
export default App;

test.jsx

import React from 'react';

const Username = function(props) {
  return (

The logged in user is:

  )
}
export default Username;

can't understand why it's giving this error?


问:
How can I check that an element is visible with Puppeteer and pure JavaScript?
I wish to check that a DOM element is visible with Puppeteer and pure JavaScript (not jQuery), how can I do this? By visible I mean that the element is displayed through CSS, and not hidden (f.ex. by display: none).

For example, I can determine whether my element #menu is not hidden via CSS rule display: none, in the following way:

```<code>const isNotHidden = await page.$eval('#menu', (elem) => {
  return elem.style.display !== 'none'
})
</code>```

How can I determine in general though if the element is hidden or not, and not just through display: none?

答:
One is by checking its display style value.
Second is by checking its height, for exp if the element is a child of an element which is display: none, the offsetHeight will be 0 and thus you know the element is not visible despite its display value. opacity: 0 is not considered as hidden element so we will not checking it.

```<code>const isNotHidden = await page.$eval('#menu', (elem) => {
    return window.getComputedStyle(elem).getPropertyValue('display') !== 'none' && elem.offsetHeight
});
</code>```

You can check elem.offsetWidth as well and is not bad before any calculation, check if element exist or not.

Body:
I wish to check that a DOM element is visible with Puppeteer and pure JavaScript (not jQuery), how can I do this? By visible I mean that the element is displayed through CSS, and not hidden (f.ex. by display: none).

For example, I can determine whether my element #menu is not hidden via CSS rule display: none, in the following way:

const isNotHidden = await page.$eval('#menu', (elem) => {
  return elem.style.display !== 'none'
})

How can I determine in general though if the element is hidden or not, and not just through display: none?

Body:
One is by checking its display style value.
Second is by checking its height, for exp if the element is a child of an element which is display: none, the offsetHeight will be 0 and thus you know the element is not visible despite its display value. opacity: 0 is not considered as hidden element so we will not checking it.

const isNotHidden = await page.$eval('#menu', (elem) => {
    return window.getComputedStyle(elem).getPropertyValue('display') !== 'none' && elem.offsetHeight
});

You can check elem.offsetWidth as well and is not bad before any calculation, check if element exist or not.


问:
Issue with shuffling image to a hdf5 file
I want to shuffle my image before putting it into the hdf5 file, but got an error in the computation. As a recent learner, I can't figure this out even afer reading the hdf5 documentation. Kindly guide me.

```<code>from random import shuffle
import glob
shuffle_data = True  # shuffle the addresses before saving

hdf5_path = 'Cat vs Dog/dataset.hdf5'  # address to where you want to save the hdf5 file
cat_dog_train_path = 'Cat vs Dog/train/*.jpg'

# read addresses and labels from the 'train' folder
addrs = glob.glob(cat_dog_train_path)
labels = [0 if 'cat' in addr else 1 for addr in addrs]  # 0 = Cat, 1 = Dog

# to shuffle data
if shuffle_data:
    c = list(zip(addrs, labels))
    shuffle(c)
    addrs, labels = zip(*c)
</code>```

Error:

```<code>> ValueError                                Traceback (most recent call
> last) <ipython-input-19-4408536403db> in <module>()
>       2     c = list(zip(address, labels))
>       3     shuffle(c)
> ----> 4     addrs, labels = zip(*c)
>
> ValueError: not enough values to unpack (expected 2, got 0)
</code>```

Reference: http://machinelearninguru.com/deep_learning/data_preparation/hdf5/hdf5.html#list

答:
The website gives Python 2 code. I am seeing your tag, are you using Python 3? You can convert it using

2to3 -n filename.py```

Body:
I want to shuffle my image before putting it into the hdf5 file, but got an error in the computation. As a recent learner, I can't figure this out even afer reading the hdf5 documentation. Kindly guide me.

from random import shuffle
import glob
shuffle_data = True  # shuffle the addresses before saving

hdf5_path = 'Cat vs Dog/dataset.hdf5'  # address to where you want to save the hdf5 file
cat_dog_train_path = 'Cat vs Dog/train/*.jpg'

# read addresses and labels from the 'train' folder
addrs = glob.glob(cat_dog_train_path)
labels = [0 if 'cat' in addr else 1 for addr in addrs]  # 0 = Cat, 1 = Dog

# to shuffle data
if shuffle_data:
    c = list(zip(addrs, labels))
    shuffle(c)
    addrs, labels = zip(*c)

Error:

> ValueError                                Traceback (most recent call
> last) <ipython-input-19-4408536403db> in <module>()
>       2     c = list(zip(address, labels))
>       3     shuffle(c)
> ----> 4     addrs, labels = zip(*c)
>
> ValueError: not enough values to unpack (expected 2, got 0)

Reference: http://machinelearninguru.com/deep_learning/data_preparation/hdf5/hdf5.html#list


问:
Do internal artifacts belong in a repository?
Our team is struggling with issues around the idea of a library repository. I have used Maven, and I am familiar with Ivy.  We have little doubt that for third-party jars, a common repository that is integrated into the build system has tremendous advantage.

The struggle is around how to handle artifacts that are strictly internal.  We have many artifacts that use a handful of different build tools, including Maven, but essentially they are all part of one one product (one team responsible for all of it).  Unfortunately, we are not currently producing a single artifact per project, but we're headed in that direction.  Developers do and will check out all the projects.

We see two options:

1) Treat all artifacts even internal ones as any third-party jar.  Each jar gets built and published to the repository, and other artifact projects refer to the repository for all projects.

2) Each project refers to other "sibling" projects directly.  There is a "master project" that triggers the builds for all other projects with an appropriate dependency order.  In the IDE (eclipse), each projects refers to it's dependent project (source) directly. The build tools look into the sibling project referencing a .jar.

It's very clear that the open-source world is moving towards the repository model.  But it seems to us that their needs may be different.  Most such projects are very independent and we strongly suspect users are seldom making changes across projects.  There are frequent upgrades that are now easier for clients to track and be aware of.

However, it does add a burden in that you have to separately publish changes.  In our case, we just want to commit to source control (something we do 20-50 times a day).

I'm aware that Maven might solve all these problems, but the team is NOT going to convert everything to Maven.  Other than maven, what do you recommend (and why)?

答:
It's not necessary to choose only one of your options.  I successfully use both in combination.  If a project consists of multiple modules, they are all built together, and then delivered to the repository.  However, the upload only happens for "official" or "release" builds.  The ongoing development builds are done at the developers' machines.  You don't have to use Maven for this.  Ivy would work or even a manual process.  The "artifact repository" could be one of the excellent products available or just a filesystem mount point.

It's all about figuring out the appropriate component boundaries.

When you say "developers do and will check out all projects", that's fine.  You never know when you might want to make a change; there's no harm in having a working copy ready.  But do you really want to make every developer to build every artifact locally, even if they do not need to change it?  Really, is every developer changing every single artifact?

Or maybe you just don't have a very big product, or a very big team.  There's nothing wrong with developing in a single project with many sub-projects (which may themselves have sub-modules).  Everybody works on everything together.  A single "build all" from the top does the job.  Simple, works, fast (enough).  So what would you use a shared repository for in this case?  Probably nothing.

Maybe you need to wait until your project/team is bigger before you see any benefit from splitting things up.

But I guarantee you this: you have some fundamental components, which are depended on (directly or indirectly) by many projects but do not themselves depend on any internal artifacts.  Ideally, these components wouldn't change very much in a typical development cycle.  My advice to you is twofold:

set up an internal repository since you already agree that you will benefit from doing so, if only for third-party jars.

consider separating the most fundamental project into a separate build, and delivering its artifact(s) to the repository, then having the rest of the system reference it as if it were a third-party artifact.

If a split like this works, you'll find that you're rebuilding that fundamental piece only when needed, and the build cycle for the rest of the project (for your developers) is faster by a corresponding amount: win-win.  Also, you'll be able to use a different delivery schedule (if desired) for the fundamental component(s), making the changes to it more deliberate and controlled (which is as it should be for such a component).  This helps facilitate growth.


问:
Can I define a common interface for two classes with same property name?
Let's say I have following class hierarchy:

```<code>class A { }
class B : A { }
class C : A { }
</code>```

And I have two container classes:

```<code>class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }
</code>```

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

```<code>void ProcessValue(IEnumerable<A> as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}
</code>```

答:
If you want a single non-generic IContainer that you can treat both collections as identically, then there's not really a very clean option, because the type is different. Variance hates type difference. You could use generics, sure, but that would help you because you'd need to check each closed generic type separately, just like you'd currently need to check for B and C separately.

The closest you could get easily on a non-generic API would be returning Array or IList (non-generic) in IContainer, which is horrible and doesn't move you forward much.

Alternatively, if you only need to enumerate the items, you can use the variance features of generics to get the items as the base type:

```<code>class BContainer : IContainer
{
    public B[] value { get; set; }
    IEnumerable<A> IContainer.Value => value;
}
class CContainer : IContainer
{
    public C[] value { get; set; }
    IEnumerable<A> IContainer.Value => value;
}

interface IContainer
{
    IEnumerable<A> Value { get; }
}
</code>```

Both BContainer and CContainer can be treated as an IContainer, and given an IContainer you can iterate the items as As.

Body:
Let's say I have following class hierarchy:

class A { }
class B : A { }
class C : A { }

And I have two container classes:

class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

void ProcessValue(IEnumerable as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}

Body:
If you want a single non-generic IContainer that you can treat both collections as identically, then there's not really a very clean option, because the type is different. Variance hates type difference. You could use generics, sure, but that would help you because you'd need to check each closed generic type separately, just like you'd currently need to check for B and C separately.

The closest you could get easily on a non-generic API would be returning Array or IList (non-generic) in IContainer, which is horrible and doesn't move you forward much.

Alternatively, if you only need to enumerate the items, you can use the variance features of generics to get the items as the base type:

class BContainer : IContainer
{
    public B[] value { get; set; }
    IEnumerable<A> IContainer.Value => value;
}
class CContainer : IContainer
{
    public C[] value { get; set; }
    IEnumerable<A> IContainer.Value => value;
}

interface IContainer
{
    IEnumerable<A> Value { get; }
}

Both BContainer and CContainer can be treated as an IContainer, and given an IContainer you can iterate the items as As.


问:
Running Concourse CI on Kubernetes
Is there any ways to deploy Concourse (both worker and web parts) via Kubernetes? I faced an issue with docker push:

```<code>cb1e3aeea39c: Waiting
5dd685fa9d71: Waiting
8a88c6d1419d: Mounted from wodby/php
b37b676c40b5: Mounted from wodby/php
af413e3ea009: Mounted from wodby/php
d142daee8ef2: Mounted from wodby/php
5dd685fa9d71: Mounted from wodby/php
94a8fa70651c: Mounted from wodby/php
cb1e3aeea39c: Mounted from wodby/php
e6ceb8011e49: Mounted from wodby/php
4e86b94d038f: Mounted from wodby/php
dca58c4a8ccb: Mounted from wodby/php
998dedad47e8: Mounted from wodby/php
2bd72896c2d4: Mounted from wodby/php
aa71ffb881e9: Mounted from wodby/php
7cbcbac42c44: Mounted from wodby/php
received unexpected HTTP status: 504 Gateway Time-out
</code>```

So I wonder is it bug or limitation?

Related Github issues:

https://github.com/concourse/concourse/issues/936

https://github.com/concourse/docker-image-resource/issues/102

答:
Copying coffeepac's answer (Helm) to this question here as it is probably the most canonical response particularly for somebody who can't get it working otherwise, and it is super light-weight:

If you are running helm in your cluster, there is a chart for
  deploying concourse to kubernetes:
  github.com/kubernetes/charts/tree/master/stable/concourse

This chart is in the stable repository. Potentially volatile charts are in incubator.

Title: Running Concourse CI on Kubernetes

Body:
Is there any ways to deploy Concourse (both worker and web parts) via Kubernetes? I faced an issue with docker push:

cb1e3aeea39c: Waiting
5dd685fa9d71: Waiting
8a88c6d1419d: Mounted from wodby/php
b37b676c40b5: Mounted from wodby/php
af413e3ea009: Mounted from wodby/php
d142daee8ef2: Mounted from wodby/php
5dd685fa9d71: Mounted from wodby/php
94a8fa70651c: Mounted from wodby/php
cb1e3aeea39c: Mounted from wodby/php
e6ceb8011e49: Mounted from wodby/php
4e86b94d038f: Mounted from wodby/php
dca58c4a8ccb: Mounted from wodby/php
998dedad47e8: Mounted from wodby/php
2bd72896c2d4: Mounted from wodby/php
aa71ffb881e9: Mounted from wodby/php
7cbcbac42c44: Mounted from wodby/php
received unexpected HTTP status: 504 Gateway Time-out

So I wonder is it bug or limitation?

Related Github issues:

https://github.com/concourse/concourse/issues/936

https://github.com/concourse/docker-image-resource/issues/102


问:
Javascript table's pagination

I'm trying to put pagination function into my table and taking this post "Simple pagination in javascript" for reference.

https://codepen.io/duongvu/pen/eewdPG?editors=1111

It's supposed to input the data from my array into the table's class. However it doesn't work in my case.

It freezes and can not proceed when clicking on <next>

答:
```<code>function changePage(page) {
  var btn_next = document.getElementById("btn_next");
  var btn_prev = document.getElementById("btn_prev");
  var col = document.getElementsByClassName("no");
  var colName = document.getElementsByClassName("name");
  var colDetails = document.getElementsByClassName("info");
  var page_span = document.getElementById("page");

  if (page < 1) page = 1;
  if (page > numPages()) page = numPages();

  for (var i = (page - 1) * records_per_page; i < (page * records_per_page); i++) {
    col[i % records_per_page].innerText = content[i] ? content[i].number : '';
    colName[i % records_per_page].innerText = content[i] ? content[i].name : '';
    colDetails[i % records_per_page].innerText = content[i] ? content[i].detail : '';
  }
}
</code>```

You are printing only numbers thats why it was not printing any other result. And as you have only 4 rows, so you need to use col[i % records_per_page] to print inside the table data on page changes.

Here is updated codepen.

Title: Javascript table's pagination

Body:
function changePage(page) {
  var btn_next = document.getElementById("btn_next");
  var btn_prev = document.getElementById("btn_prev");
  var col = document.getElementsByClassName("no");
  var colName = document.getElementsByClassName("name");
  var colDetails = document.getElementsByClassName("info");
  var page_span = document.getElementById("page");

  if (page < 1) page = 1;
  if (page > numPages()) page = numPages();

  for (var i = (page - 1) * records_per_page; i < (page * records_per_page); i++) {
    col[i % records_per_page].innerText = content[i] ? content[i].number : '';
    colName[i % records_per_page].innerText = content[i] ? content[i].name : '';
    colDetails[i % records_per_page].innerText = content[i] ? content[i].detail : '';
  }
}

You are printing only numbers thats why it was not printing any other result. And as you have only 4 rows, so you need to use col[i % records_per_page] to print inside the table data on page changes.

Here is updated codepen.


问:
Concurrency protection is not working
I go bananas here. With my attempts to implement concurrency protection.

So I figured out there are 2 ways to do it.
Optimistic - basically we add a version field to the record and each save will increase it. So if my current version field is different that one on the disc it means something got modified and I give an error.

And the pessimistic approach that means we just lock a record and it will be not possible to edit.

I implemented both ways plus concurrency package for Django and nothing works I teas on SQLLite and on Postgres with Heroku.

Below is my view method it has both approaches

for pessimistic, I lock with transaction atomic using  select_for_update
and for optimistic I use concurrency django package that increases my version field on each edit and do a simple comparison with on_disc value

What I do wrong? Please help?

```<code>@login_required
    def lease_edit(request,pk,uri):
        logger = logging.getLogger(__name__)
        title = 'Edit Lease'
        uri = _get_redirect_url(request, uri)

        with transaction.atomic():

            post = get_object_or_404(Lease.objects.select_for_update(), pk=pk)

            if request.method == "POST":
                form = LeaseForm(request.POST, instance=post)
                if form.is_valid():
                    lease = form.save(commit=False)
                    on_disc= Lease.objects.get(pk=post.id)
                    if on_disc.version > post.version:
                        messages.add_message(request, messages.ERROR, str(lease.id) + "-Error object was modified by another user. Please reopen object.")
                        return redirect(uri)

                    lease.save()
                    messages.add_message(request, messages.SUCCESS, str(lease.id) + "--SUCCESS Object saved successfully")
                    return redirect(uri)
            else:
                form = LeaseForm(instance=post)
            #lease = post.lease
            return render(request, 'object_edit.html', {'form': form, 'title':title, 'extend': EXTEND})
</code>```

To test I just open 2 browsers with the same record and try to edit both in parallel (I use same user)

答:
The problem is with how websites work. Currently your locking works like this:

GET request loads data

you lock the row, load, send to browser, unlock

you edit data on the browser

POST data to server

you lock the row, update, unlock

There is nothing here that keeps the row locked. Multiple instances can send data to the server since the row is unlocked after each request. This is the way web systems usually work, each request is separate and locking has to be done differently.

As for the row versioning, if I understand the code correctly you don't send the current row number to the browser but you read it while updating. This again means that you get the correct number. You should send the current number to the browser and on POST compare that number to the current number in the database. This way if something changes it detects it.

I may be wrong about this part since I'm not familiar with Django but this is my understanding of the functionality of the code. I would assume form might have the current row version but it's not compared to anything, only the current number in database and one after update (which also might change the number possibly).

Title: Concurrency protection is not working

Body:
I go bananas here. With my attempts to implement concurrency protection.

So I figured out there are 2 ways to do it.
Optimistic - basically we add a version field to the record and each save will increase it. So if my current version field is different that one on the disc it means something got modified and I give an error.

And the pessimistic approach that means we just lock a record and it will be not possible to edit.

I implemented both ways plus concurrency package for Django and nothing works I teas on SQLLite and on Postgres with Heroku.

Below is my view method it has both approaches

for pessimistic, I lock with transaction atomic using  select_for_update
and for optimistic I use concurrency django package that increases my version field on each edit and do a simple comparison with on_disc value

What I do wrong? Please help?

@login_required
    def lease_edit(request,pk,uri):
        logger = logging.getLogger(__name__)
        title = 'Edit Lease'
        uri = _get_redirect_url(request, uri)

        with transaction.atomic():

            post = get_object_or_404(Lease.objects.select_for_update(), pk=pk)

            if request.method == "POST":
                form = LeaseForm(request.POST, instance=post)
                if form.is_valid():
                    lease = form.save(commit=False)
                    on_disc= Lease.objects.get(pk=post.id)
                    if on_disc.version > post.version:
                        messages.add_message(request, messages.ERROR, str(lease.id) + "-Error object was modified by another user. Please reopen object.")
                        return redirect(uri)

                    lease.save()
                    messages.add_message(request, messages.SUCCESS, str(lease.id) + "--SUCCESS Object saved successfully")
                    return redirect(uri)
            else:
                form = LeaseForm(instance=post)
            #lease = post.lease
            return render(request, 'object_edit.html', {'form': form, 'title':title, 'extend': EXTEND})

To test I just open 2 browsers with the same record and try to edit both in parallel (I use same user)


问:
RXJava 2 Flowable`s mergeWith not merging
I have this method on my Room`s dao

```<code>@Query("SELECT * FROM Expense WHERE date >= :initDate AND date <= :endDate AND chargeableUuid = :chargeableUuid ORDER BY date")
fun currentMonth(initDate: Long, endDate: Long, chargeableUuid: String): Flowable<List<Expense>>
</code>```

and I am using it this way:

```<code>dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
            .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
            .subscribe { Log.i("test", "size ${it.size}" }
</code>```

If I execute each call separately both return one element each (different elements), but when I execute them together the log outputs that just one element is in the returned list.

How can I merge the emitions from two Flowables into one?

答:
When you use the merge (or mergeWith) operator as you can see in the diagram, you will have an Observable that emits all the items emitted from all the Observable (or Flowable you are merging).

So, actually your subscriber will receive two List. If you want just one Flowable that emit one single item (a list) containing all the items contained in all the lists, you can use the toList operator:

doing

```<code>dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
            .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
    .toList()
</code>```

you'll create a Flowable that emits a list of list, List<List< Expense>> that will contains your two lists. So you can map it in a single list:

```<code>dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
   .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
    .toList()
    .map(lists -> {
     List<Expense> l = new ArrayList<>();
     for (List<Expense> list : lists) {
          l.addAll(list);
     }
     return l;
})
</code>```

If you subscribe now, you will get a single list containing two Expense objects.

Body:
I have this method on my Room`s dao

@Query("SELECT * FROM Expense WHERE date >= :initDate AND date <= :endDate AND chargeableUuid = :chargeableUuid ORDER BY date")
fun currentMonth(initDate: Long, endDate: Long, chargeableUuid: String): Flowable<List<Expense>>

and I am using it this way:

dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
            .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
            .subscribe { Log.i("test", "size ${it.size}" }

If I execute each call separately both return one element each (different elements), but when I execute them together the log outputs that just one element is in the returned list.

How can I merge the emitions from two Flowables into one?

Body:
When you use the merge (or mergeWith) operator as you can see in the diagram, you will have an Observable that emits all the items emitted from all the Observable (or Flowable you are merging).

So, actually your subscriber will receive two List. If you want just one Flowable that emit one single item (a list) containing all the items contained in all the lists, you can use the toList operator:

doing

dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
            .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
    .toList()

you'll create a Flowable that emits a list of list, List<List< Expense>> that will contains your two lists. So you can map it in a single list:

dao.currentMonth(firstDayOfMonth, lastDayOfMonth, account.uuid)
   .mergeWith(dao.currentMonth(firstDayOfMonth, lastDayOfMonth, card.uuid))
    .toList()
    .map(lists -> {
     List<Expense> l = new ArrayList<>();
     for (List<Expense> list : lists) {
          l.addAll(list);
     }
     return l;
})

If you subscribe now, you will get a single list containing two Expense objects.


问:
mysql insert with select query to insert multiple rows
how to insert multiple rows with insert and select query.</p>

```<code>INSERT INTO contacts(`studentId`,`contactId`,`firstName`,`lastName`)
SELECT studentId ,'1234','kavin','kumar' FROM student WHERE sampId='8580',
SELECT studentId, '108','karthi','kumar' FROM student WHERE sampId='5650'
</code>```

答:
You can use union all:

```<code>INSERT INTO contacts(`studentId`, `contactId`, `firstName`, `lastName`)
    SELECT studentId, '1234', 'kavin', 'kumar'
    FROM student
    WHERE sampId = '8580'
    UNION ALL
    SELECT studentId, '108', 'karthi', 'kumar'
    FROM student
    WHERE sampId = '5650';
</code>```

If the id columns are numbers, then do not use single quotes around the values.

Body:
how to insert multiple rows with insert and select query.

INSERT INTO contacts(`studentId`,`contactId`,`firstName`,`lastName`)
SELECT studentId ,'1234','kavin','kumar' FROM student WHERE sampId='8580',
SELECT studentId, '108','karthi','kumar' FROM student WHERE sampId='5650'

Body:
You can use union all:

INSERT INTO contacts(`studentId`, `contactId`, `firstName`, `lastName`)
    SELECT studentId, '1234', 'kavin', 'kumar'
    FROM student
    WHERE sampId = '8580'
    UNION ALL
    SELECT studentId, '108', 'karthi', 'kumar'
    FROM student
    WHERE sampId = '5650';

If the id columns are numbers, then do not use single quotes around the values.


问:
In Angular 4, how to dynamically set min date and max date in date picker?
I am  trying to show disable past dates from current date, meaning user should not select past date from date picker.

Below is the code I am using to set min date in Datepicker

Component.html

```<code><input type="text" formControlName="eventStart" [(ngModel)]="event_start" class="form-control pull-right"
  id="event_start" required placeholder='{{ "EVENT.FORM.START_DATE"  | translate }}'>

  <input type="text" formControlName="eventEnd" [(ngModel)]="event_end"  class="form-control pull-right"
id="event_end" placeholder='{{ "EVENT.FORM.END_DATE"  | translate }}'>
</code>```

Component.ts

```<code>this.datePicker = jQuery('#event_start').datepicker({
      autoclose: true,
      orientation: 'left bottom',
    });
this.datePicker = jQuery('#event_end').datepicker({
          autoclose: true,
          orientation: 'left bottom',
    });
</code>```

答:
You're setting this.datePicker twice:

jQuery('#event_start')

jQuery('#event_end')

I suggest you to refactor your code like this:

```<code>const datePickerConfig = {
    autoclose: true,
    orientation: 'left bottom',
};

this.startDatePicker = document.querySelector('#event_start').datepicker(datePickerConfig);
this.endDatePicker = document.querySelector('#event_end').datepicker(datePickerConfig);
</code>```

In order to help you efficiently, please tell which date picker library you're using.

Body:
I am  trying to show disable past dates from current date, meaning user should not select past date from date picker.

Below is the code I am using to set min date in Datepicker

Component.html

<input type="text" formControlName="eventStart" [(ngModel)]="event_start" class="form-control pull-right"
  id="event_start" required placeholder='{{ "EVENT.FORM.START_DATE"  | translate }}'>

  <input type="text" formControlName="eventEnd" [(ngModel)]="event_end"  class="form-control pull-right"
id="event_end" placeholder='{{ "EVENT.FORM.END_DATE"  | translate }}'>

Component.ts

this.datePicker = jQuery('#event_start').datepicker({
      autoclose: true,
      orientation: 'left bottom',
    });
this.datePicker = jQuery('#event_end').datepicker({
          autoclose: true,
          orientation: 'left bottom',
    });

Body:
You're setting this.datePicker twice:

jQuery('#event_start')

jQuery('#event_end')

I suggest you to refactor your code like this:

const datePickerConfig = {
    autoclose: true,
    orientation: 'left bottom',
};

this.startDatePicker = document.querySelector('#event_start').datepicker(datePickerConfig);
this.endDatePicker = document.querySelector('#event_end').datepicker(datePickerConfig);

In order to help you efficiently, please tell which date picker library you're using.


问:
Insert blank line in Detail section of Crystal Report
I have an issue concerning inserting blank line in Detail Section of Crystal Report (using SAP Crystal Report with VS 2013)
For example, if there is only 01 record , it should be always 05 lines instead of 01 lines. The below is the form created in Excel

And here is the form created with Crystal Report:

I googled a lot but no solution is satisfied in my case.

Please help. Thanks in advance!

答:
first of all you have fix detail section
then you want 5 blank rows if there are total 6 rows and 1 row have data then design detail section and under detail section -> Report section leave blank with needed space and put your footer details in page footer
then check result ->it show blank rows as well after 6 rows it go next page for 7th row</p>


问:
How to sort a nested list by reverse length of the sublists and keep the original order
Example:

```<code>a =
[
[['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]],
[['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]],
[['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]],
[['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
]
</code>```

What I want to do is to sort the nested list by reversed length of the sublists
but to keep the original order if the length of sublists is the same.

Expected result:

```<code>[
[['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]],
[['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]],
[['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]],
[['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
]
</code>```

I know I can use this to sort the list by reverse length but it will not keep the original order:

```<code>a = sorted(a, key=len, reverse=True)
</code>```

(it reverses the sublists 'Delete' and 'Columns')

How can I sort the list by reverse length of the sublists and keep the original order?

答:
TimSort is a stable sort, so it normally preserves the order of equal items. So your code should work correctly.

Alternatively, get rid of the reverse=True and use a key function that returns the negative of the sublist length.

```<code>a = [
    [['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]],
    [['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]],
    [['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]],
    [['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
]

a.sort(key=lambda x: -len(x))
for row in a:
    print(row)
</code>```

output

```<code>[['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]]
[['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]]
[['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]]
[['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
</code>```

If I use

```<code>a.sort(key=len, reverse=True)
</code>```

I get the same output as above. If you don't get that output too, something very weird is going on. Note that this version is more efficient than the version above, since it calls len directly (which is implemented in C and it does a fast attribute lookup to determine the object's length), and Python function calls are relatively slow, whether they are def functions or lambdas.

BTW, when you want to sort a list in-place you should always call its .sort method. The built-in sorted function actually creates a new list, copies the original data to that list, and then calls .sort on it, and then binds the new list to the destination. So it's much more efficient to avoid creating that copy and call .sort yourself on the original list.

Body:
Example:

a =
[
[['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]],
[['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]],
[['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]],
[['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
]

What I want to do is to sort the nested list by reversed length of the sublists
but to keep the original order if the length of sublists is the same.

Expected result:

[
[['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]],
[['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]],
[['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]],
[['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
]

I know I can use this to sort the list by reverse length but it will not keep the original order:

a = sorted(a, key=len, reverse=True)

(it reverses the sublists 'Delete' and 'Columns')

How can I sort the list by reverse length of the sublists and keep the original order?

Body:
TimSort is a stable sort, so it normally preserves the order of equal items. So your code should work correctly.

Alternatively, get rid of the reverse=True and use a key function that returns the negative of the sublist length.

a = [
    [['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]],
    [['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]],
    [['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]],
    [['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]
]

a.sort(key=lambda x: -len(x))
for row in a:
    print(row)

output

[['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]]
[['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]]
[['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]]
[['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]]

If I use

a.sort(key=len, reverse=True)

I get the same output as above. If you don't get that output too, something very weird is going on. Note that this version is more efficient than the version above, since it calls len directly (which is implemented in C and it does a fast attribute lookup to determine the object's length), and Python function calls are relatively slow, whether they are def functions or lambdas.

BTW, when you want to sort a list in-place you should always call its .sort method. The built-in sorted function actually creates a new list, copies the original data to that list, and then calls .sort on it, and then binds the new list to the destination. So it's much more efficient to avoid creating that copy and call .sort yourself on the original list.


问:
Delete folder in php
I am trying to delete a folder using this script :

```function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = array_diff(scandir($path), array('.', '..'));

        foreach ($files as $file)
        {
                Delete(realpath($path) . '/' . $file);
        }

        return rmdir($path);
    }

    else if (is_file($path) === true)
    {
        return unlink($path);
    }

    return false;
}

Delete('tmp');
```

It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable) but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?

答: May be some files are opened using php like fopen and that time it will not delete the folder or directory. I have faced the same issue when I tried to delete a file/folder</p>

Title: Delete folder in php

Body:
I am trying to delete a folder using this script :

function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = array_diff(scandir($path), array('.', '..'));

        foreach ($files as $file)
        {
                Delete(realpath($path) . '/' . $file);
        }

        return rmdir($path);
    }

    else if (is_file($path) === true)
    {
        return unlink($path);
    }

    return false;
}

Delete('tmp');

It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable) but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?


问:
How to output JSON from Pentaho xaction?
What's the best way to get a Pentaho xaction to return it's output in JSON format?

I have a dashboard that is driven by Pentaho xactions that return HTML fragments (tables) that I then insert into the page. It works okay, but I would like my xactions to return JSON instead of the HTML fragments to make things a bit more flexible and reusable.

Thanks.

答:
There is a sample available here

http://sandbox.pentaho.com/api-integration-samples/

Let us know how you do

Mike Tarallo
Sales Engineering Director
Pentaho


问:
C# - ListView won't refresh from different form
```<code>// PaddlerList (Form 1)
        public void RefreshListView()
        {
            PaddlerListView.Items.Clear();
            PaddlerToList();
            PaddlerListView.Refresh();
            Console.WriteLine("Refresh....");
        }
        public void PaddlerToList() // Just adds
        {
            for (int i = 1; i < Main.paddlerList.Count(); i++) // Repeats for all
            {
                string[] array = new string[4];
                ListViewItem item;
                array[0] = Main.paddlerList[i].FirstName.ToString();
                array[1] = Main.paddlerList[i].LastName.ToString();
                array[2] = Main.paddlerList[i].Weight.ToString();
                array[3] = Main.paddlerList[i].PreferredSide.ToString();
                item = new ListViewItem(array);
                PaddlerListView.Items.Add(item);
            }
        }

        private void RefreshList_button_Click(object sender, EventArgs e)
        {
            RefreshListView();
        }

// NewPaddler (Form 2)
            private void SubmitPaddler_button_Click(object sender, EventArgs e)
            {
            // Code here
            PaddlerList ListViewRefresh = new PaddlerList(); // Creates an instant of the other form, so it can run the procedure
            ListViewRefresh.RefreshListView();
            }
</code>```

When a new paddler is added (the submit button is pressed), the console outputs "Refresh...." showing that the function has been run, but the ListView doesn't refresh

However, when I set a button on the same form as the ListView, it does refresh the ListView with the new items, when the button is pressed.

I can't work out what the issue is here? I think it's something to do with protection levels of the ListView.

Thanks!

答: When a new PaddlerList object is created, all member variables, like in your case, Items, recieve a fresh start. I think you need to pass the original PaddlerList to your second form in order to actualize the correct form.

Body:
// PaddlerList (Form 1)
        public void RefreshListView()
        {
            PaddlerListView.Items.Clear();
            PaddlerToList();
            PaddlerListView.Refresh();
            Console.WriteLine("Refresh....");
        }
        public void PaddlerToList() // Just adds
        {
            for (int i = 1; i < Main.paddlerList.Count(); i++) // Repeats for all
            {
                string[] array = new string[4];
                ListViewItem item;
                array[0] = Main.paddlerList[i].FirstName.ToString();
                array[1] = Main.paddlerList[i].LastName.ToString();
                array[2] = Main.paddlerList[i].Weight.ToString();
                array[3] = Main.paddlerList[i].PreferredSide.ToString();
                item = new ListViewItem(array);
                PaddlerListView.Items.Add(item);
            }
        }

        private void RefreshList_button_Click(object sender, EventArgs e)
        {
            RefreshListView();
        }

// NewPaddler (Form 2)
            private void SubmitPaddler_button_Click(object sender, EventArgs e)
            {
            // Code here
            PaddlerList ListViewRefresh = new PaddlerList(); // Creates an instant of the other form, so it can run the procedure
            ListViewRefresh.RefreshListView();
            }

When a new paddler is added (the submit button is pressed), the console outputs "Refresh...." showing that the function has been run, but the ListView doesn't refresh

However, when I set a button on the same form as the ListView, it does refresh the ListView with the new items, when the button is pressed.

I can't work out what the issue is here? I think it's something to do with protection levels of the ListView.

Thanks!


问:
SF3 [Translator][Console] translation:update yaml nesting
I am using Symfony 3.4 and I have a question.

Nesting translations message codes (the dot being the separator) is a great feature of YAML translation files:

```<code>admin:
    title: Administration
    exit: Exit administration
</code>```

Translation:update generate:

```<code>admin.title: Administration
admin.exit: Exit administration
</code>```

I run the following command to update the yaml file:

```<code>php bin/console translation:update --output-format=yml  --force fr  NameBundle
</code>```

In my code, I use this syntax to translate the keys:

```<code>{{ 'layout.confirm.delete'|trans }}
</code>```

Do you have an idea for generate nested yml files with the translation:update command?

答:
The multiple levels are flattened into single id/translation pairs by adding a dot (.) between every level,
therefore this definition:

```<code>admin:
    title: Administration
    exit: Exit administration
</code>```

is equivalent to the following:

```<code>admin.title: Administration
admin.exit: Exit administration
</code>```

See the documentation

Body:
I am using Symfony 3.4 and I have a question.

Nesting translations message codes (the dot being the separator) is a great feature of YAML translation files:

admin:
    title: Administration
    exit: Exit administration

Translation:update generate:

admin.title: Administration
admin.exit: Exit administration

I run the following command to update the yaml file:

php bin/console translation:update --output-format=yml  --force fr  NameBundle

In my code, I use this syntax to translate the keys:

{{ 'layout.confirm.delete'|trans }}

Do you have an idea for generate nested yml files with the translation:update command?

Body:
The multiple levels are flattened into single id/translation pairs by adding a dot (.) between every level,
therefore this definition:

admin:
    title: Administration
    exit: Exit administration

is equivalent to the following:

admin.title: Administration
admin.exit: Exit administration

See the documentation


问:
How to run infinite loop on vertx using while() loop
I would like to run an infinite loop on verx on diff thread.
Should be something like this:

```<code>vertx.executeBlocking(future -> {
while(true){
}
   //some logic (e.g waiting on blocking-code)
}
</code>```

thing is that on vertx even for executeBlocking threads you have global timeout which you can increase. but I would like to set for this execution non-timeout warnings as it will run forever

am I achieving my purpose right with vertx?

In case 1 is true. how to exclude this specific blocking execution from the timeout warnings

答:
You don't.

If you have a condition that triggers processing, the have the processing happen at that point and not inside an infinite loop.

Example:

```<code>while ((event = eventQueue.take()) != null) {
  final Vertx target = event.target;
  executor.submit(() -> {
    doProcessing(target);
  });
}
</code>```

The main reason for this is that even threads in a blocking state do consume resources. If you have 1000 threads waiting on events, then the system is significantly wasting time on thread-scheduling. This is why all modern IO processing happens non-blocking, in a similar fashion as the code above.

Body:
I would like to run an infinite loop on verx on diff thread.
Should be something like this:

vertx.executeBlocking(future -> {
while(true){
}
   //some logic (e.g waiting on blocking-code)
}

thing is that on vertx even for executeBlocking threads you have global timeout which you can increase. but I would like to set for this execution non-timeout warnings as it will run forever

am I achieving my purpose right with vertx?

In case 1 is true. how to exclude this specific blocking execution from the timeout warnings

Body:
You don't.

If you have a condition that triggers processing, the have the processing happen at that point and not inside an infinite loop.

Example:

while ((event = eventQueue.take()) != null) {
  final Vertx target = event.target;
  executor.submit(() -> {
    doProcessing(target);
  });
}

The main reason for this is that even threads in a blocking state do consume resources. If you have 1000 threads waiting on events, then the system is significantly wasting time on thread-scheduling. This is why all modern IO processing happens non-blocking, in a similar fashion as the code above.


问:
Jmeter on running test plan log out issue
I'm testing log in/out functionality in my application. On log in, I'm inserting a database entry, as well as for log out.

My test setup with JMeter:

Recording a Test Plan using WorkBench -> Add -> Non - Test Elements
-> HTTP(s) Test Script Recorder. [Login/Logout]

Run the Test Plan.

On running the test plan, the user log in entry was  inserted into the database, but on log out, the user entry was not deleted from the database.

Can someone suggest what I'm doing wrong?

答:
Open J Meter via command prompt.
Click on File, click on Template, disable the "User defined variables", "HTTP default requests".

List item


问:
Finding the height of a row in a WPF datagrid
Can someone please advise me on how to do this?

I have tried

```<code>dtgMain.RowHeight;
</code>```

but this always returns NAN.

答:
In case anyone needs the VB.NET version these days...

```<code>Public Shared Function GetFirstVisualChild(Of T As DependencyObject)(depObj As DependencyObject) As T
    If (depObj IsNot Nothing) Then
        Dim i As Integer
        For i = 0 To VisualTreeHelper.GetChildrenCount(depObj) - 1

            Dim child As DependencyObject = VisualTreeHelper.GetChild(depObj, i)
            If (child IsNot Nothing AndAlso TypeOf child Is T) Then

                Return CType(child, T)
            End If

            Dim childItem As T = GetFirstVisualChild(Of T)(child)
            If (childItem IsNot Nothing) Then Return childItem
        Next
    End If
    Return Nothing
End Function
</code>```

then

```<code>Dim row As DataGridRow = CType(GetFirstVisualChild(Of DataGridRow)(grid), DataGridRow)
</code>```

Body:
Can someone please advise me on how to do this?

I have tried

dtgMain.RowHeight;

but this always returns NAN.

Body:
In case anyone needs the VB.NET version these days...

Public Shared Function GetFirstVisualChild(Of T As DependencyObject)(depObj As DependencyObject) As T
    If (depObj IsNot Nothing) Then
        Dim i As Integer
        For i = 0 To VisualTreeHelper.GetChildrenCount(depObj) - 1

            Dim child As DependencyObject = VisualTreeHelper.GetChild(depObj, i)
            If (child IsNot Nothing AndAlso TypeOf child Is T) Then

                Return CType(child, T)
            End If

            Dim childItem As T = GetFirstVisualChild(Of T)(child)
            If (childItem IsNot Nothing) Then Return childItem
        Next
    End If
    Return Nothing
End Function

then

Dim row As DataGridRow = CType(GetFirstVisualChild(Of DataGridRow)(grid), DataGridRow)


问:
What is ?: operator
I found this in a material-ui example:

```<code>type ProvidedProps = {
  classes: Object,
  theme?: Object,
};
</code>```

What does ?: mean?

答:
? Following a parameter or property, means that it is optional

Have a read of the Advanced Types Documentation Optionals and Defaults

This blog post explains the uses of optionals a bit clearer than the official documentation: https://basarat.gitbooks.io/typescript/content/docs/types/functions.html#optional-parameters

Title: What is ?: operator

Body:
I found this in a material-ui example:

type ProvidedProps = {
  classes: Object,
  theme?: Object,
};

What does ?: mean?