问:
How do I compare current time to a preset time in PHP?
I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,

```<code>$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
    $refresh = true;
}
</code>```

But the boolean doesn't change. Any idea what I did wrong?

答:
the code is fine untill i know. but still if you want to do some actions, you can do something like this.</p>

```<code>         $refresh=false;
         $eightthirtyam = "08:30:00";
         if(time() >= strtotime($eightthirtyam ))
         {
          $refresh = true;
         }
         if($refresh)
         {
            //your statement is true do something here
         }
         else
         {
           //false statement
         }
</code>```

Body:
I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,

$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
    $refresh = true;
}

But the boolean doesn't change. Any idea what I did wrong?

Body:
the code is fine untill i know. but still if you want to do some actions, you can do something like this.

         $refresh=false;
         $eightthirtyam = "08:30:00";
         if(time() >= strtotime($eightthirtyam ))
         {
          $refresh = true;
         }
         if($refresh)
         {
            //your statement is true do something here
         }
         else
         {
           //false statement
         }


来源: stackexchange

问:
kwargs does not pass key-value parameters inside function, but does outside function
I want to create an empty pandas.DataFrame and add some columns to it using **kwargs.  The DataFrame remains empty when I try to populate it inside the function make_new_data_frame (I tried adding columns one by one, and all at once using kwargs).  However, if I return kwargs and err_df2 from the function, the operation works (in a jupyter notebook).  How can I get this to work inside the function, and why doesn't it?  MWE below

```<code>from pandas import DataFrame
def make_data_frame():
    df = DataFrame({'foo':[1,2,3], 'bar':[1.1,2.2,3.3]})
    return df
def make_new_data_frame():
    df = make_data_frame()
    err_df = DataFrame()
    kwargs = {}
    for c in df.columns:
        if c == 'foo':
            continue
        err_df.assign(**{c: df['foo'] - df[c]})
        kwargs[c] = df['foo'] - df[c]
    err_df2 = DataFrame()
    err_df2.assign(**kwargs)
    return err_df, err_df2, kwargs
err_df, err_df2, kwargs = make_new_data_frame()
print(err_df,'\n')
print(err_df2,'\n')
print(raw_data,'\n')
err_df2.assign(**kwargs)
</code>```

output:

```<code>Empty DataFrame
Columns: []
Index: []

Empty DataFrame
Columns: []
Index: []

{'bar': 0   -0.1
1   -0.2
2   -0.3
dtype: float64}

Out[26]:
bar
0   -0.1
1   -0.2
2   -0.3
</code>```

答:
This is from assign docs:

Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.

So you need to do something like this inside the function:

```<code>err_df2 = err_df2.assign(**kwargs)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create an empty pandas.DataFrame and add some columns to it using **kwargs.  The DataFrame remains empty when I try to populate it inside the function make_new_data_frame (I tried adding columns one by one, and all at once using kwargs).  However, if I return kwargs and err_df2 from the function, the operation works (in a jupyter notebook).  How can I get this to work inside the function, and why doesn't it?  MWE below

from pandas import DataFrame
def make_data_frame():
    df = DataFrame({'foo':[1,2,3], 'bar':[1.1,2.2,3.3]})
    return df
def make_new_data_frame():
    df = make_data_frame()
    err_df = DataFrame()
    kwargs = {}
    for c in df.columns:
        if c == 'foo':
            continue
        err_df.assign(**{c: df['foo'] - df[c]})
        kwargs[c] = df['foo'] - df[c]
    err_df2 = DataFrame()
    err_df2.assign(**kwargs)
    return err_df, err_df2, kwargs
err_df, err_df2, kwargs = make_new_data_frame()
print(err_df,'\n')
print(err_df2,'\n')
print(raw_data,'\n')
err_df2.assign(**kwargs)

output:

Empty DataFrame
Columns: []
Index: []

Empty DataFrame
Columns: []
Index: []

{'bar': 0   -0.1
1   -0.2
2   -0.3
dtype: float64}

Out[26]:
bar
0   -0.1
1   -0.2
2   -0.3

Body:
This is from assign docs:

Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.

So you need to do something like this inside the function:

err_df2 = err_df2.assign(**kwargs)


问:
TSD error: self signed certificate in certificate chain
I am following the Angular 2 quick start guide and I'm stuck right at the beginning of it.

My company is filtering our network connections and modifying SSL negociation. In a man in the middle style they assign a self signed certificate as the CA of the destination's certificate.

Therefore when I execute the second command

```<code>npm install -g tsd
tsd query angular2 --action install
</code>```

I get this:

```<code>stream.js:75
      throw er; // Unhandled stream error in pipe.
            ^
Error: self signed certificate in certificate chain
    at Error (native)
    at TLSSocket.<anonymous> (_tls_wrap.js:908:38)
    at emitNone (events.js:67:13)
    at TLSSocket.emit (events.js:163:7)
    at TLSSocket._finishInit (_tls_wrap.js:496:8)
</code>```

Does anybody know a way of disabling the self signed certificate verification?

答:
For yarn a very similar error occurs:

```<code>error An unexpected error occurred:
"https://registry.yarnpkg.com/generator-jhipster: self signed
certificate in certificate chain".
</code>```

after

```<code>export NODE_TLS_REJECT_UNAUTHORIZED=0
</code>```

I get:

```<code>error An unexpected error occurred: "https://registry.yarnpkg.com/generator-jhipster: SSL Error: SELF_SIGNED_CERT_IN_CHAIN".
</code>```

Finally the solution, with the below yarn is now happy to accept the man in the middle attack by my corporate proxy.

```<code>export NODE_TLS_REJECT_UNAUTHORIZED=0
yarn config set strict-ssl false --global
</code>```

Body:
I am following the Angular 2 quick start guide and I'm stuck right at the beginning of it.

My company is filtering our network connections and modifying SSL negociation. In a man in the middle style they assign a self signed certificate as the CA of the destination's certificate.

Therefore when I execute the second command

npm install -g tsd
tsd query angular2 --action install

I get this:

stream.js:75
      throw er; // Unhandled stream error in pipe.
            ^
Error: self signed certificate in certificate chain
    at Error (native)
    at TLSSocket.<anonymous> (_tls_wrap.js:908:38)
    at emitNone (events.js:67:13)
    at TLSSocket.emit (events.js:163:7)
    at TLSSocket._finishInit (_tls_wrap.js:496:8)

Does anybody know a way of disabling the self signed certificate verification?

Body:
For yarn a very similar error occurs:

error An unexpected error occurred:
"https://registry.yarnpkg.com/generator-jhipster: self signed
certificate in certificate chain".

after

export NODE_TLS_REJECT_UNAUTHORIZED=0

I get:

error An unexpected error occurred: "https://registry.yarnpkg.com/generator-jhipster: SSL Error: SELF_SIGNED_CERT_IN_CHAIN".

Finally the solution, with the below yarn is now happy to accept the man in the middle attack by my corporate proxy.

export NODE_TLS_REJECT_UNAUTHORIZED=0
yarn config set strict-ssl false --global


问:
Object of class GuzzleHttp\Psr7\Request could not be converted to string
I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.

```<code>use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();

$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);

if ($res->getStatusCode() == 200)
{
 $json = (string)$res->getBody();
 return $json;
}
</code>```

and I've got this error on log:
Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string

what is wrong with my code? please kindly help me.
fyi, this error not always happen. sometimes it show this error, sometimes success.

thank you

答:
```<code>$json = $res->getBody()->getContents();
</code>```

try this

Body:
I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.

use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();

$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);

if ($res->getStatusCode() == 200)
{
 $json = (string)$res->getBody();
 return $json;
}

and I've got this error on log:
Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string

what is wrong with my code? please kindly help me.
fyi, this error not always happen. sometimes it show this error, sometimes success.

thank you

Body:
$json = $res->getBody()->getContents();

try this


问:
Data Annotation table columns
```<code>public partial class Employee
{
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}
</code>```

This is generated class for table Employee using EF. I want Emp_Name change to EmpName in application without changing table structure. But using below changes using data annotation dbEntity.Set<Employee>().ToList();  getting exception

"The entity type Employee is not part of the model for the current
  context."

System.InvalidOperationException.

How can solve this

```<code>public partial class Employee
{
    public int Emp_Id { get; set; }
    [Column("Emp_Name")]
    public string EmpName { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}
</code>```

答:
You don't need to change the column's name. You can easily use [Display] or [DisplayName] attribute like this:

Add using System.ComponentModel.DataAnnotations; to your using directives first then:

```<code>[Display(Name = "EmpName")]
public string Emp_Name { get; set; }
</code>```

Or:

```<code>[DisplayName("EmpName")]
public string Emp_Name { get; set; }
</code>```

Title: Data Annotation table columns

Body:
public partial class Employee
{
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}

This is generated class for table Employee using EF. I want Emp_Name change to EmpName in application without changing table structure. But using below changes using data annotation dbEntity.Set<Employee>().ToList();  getting exception

"The entity type Employee is not part of the model for the current
  context."

System.InvalidOperationException.

How can solve this

public partial class Employee
{
    public int Emp_Id { get; set; }
    [Column("Emp_Name")]
    public string EmpName { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}

Body:
You don't need to change the column's name. You can easily use [Display] or [DisplayName] attribute like this:

Add using System.ComponentModel.DataAnnotations; to your using directives first then:

[Display(Name = "EmpName")]
public string Emp_Name { get; set; }

Or:

[DisplayName("EmpName")]
public string Emp_Name { get; set; }


问:
Form Building UI for Rails?
I am developing my first Rails app, a web replacement to a paper form system.  Some way through development I discover my client wants to be able to add ad hoc new forms to the live system.

I have considered using wufoo/ google forms/ or survey monkey, but I don't think they are going to fit the bill, due to integration requirements.

What I basically want is to enable one or two super-users to create forms, which will then be available to other users in the system.  When the forms are completed the output should be made available to my system.  The data is to be manually collated for analysis, so even CSV is fine - there is no need for complex modelling.

I have been struggling to find any paths to a solution - I really don't want to build a form builder myself!  So if anybody can point me in the right direction it would be most appreciated!

Cheers!

答:
The liquid template is a good choice for custom building web pages. The easier approach is creating pure HTML pages with form to your system, if your customer allows to.

For the data storage, you'd better try nosql database, such as the mongodb and mongo gem as the ruby adapter, so you can save any data structure without managing the tables and columns. By the way, you have to learn some ruby meta-programming skills to process the dynamic data from the client.

ContentLicense: CC BY-SA 2.5

Title: Form Building UI for Rails?


答:
The function time() returns always timestamp that is timezone independent (=UTC), while strtotime() give a local time, So there is a timezone offset.

You need to subtract the timezone offset form the local time, before the compare, and check the live demo for a good understanding.

Title: How do I compare current time to a preset time in PHP?


问:
Image to Integer
How to convert image resources to integer?
I used this:

```<code>int rh=this.getResources().getIdentifier("ic_launcher", null, this.getPackageName());
</code>```

but it wont work.
I logcat this and the value of rh is 0 always.
is there any alternative way to convert image to integer?

答:
You can achieve this without using resource also.

```<code>int id=R.drawable.icon;
</code>```

Here, icon is image in your drawable folder.

To set this id value to integer

```<code>ImageView imageView=null;
imageView.setImageResource(id);
</code>```

Title: Image to Integer

Body:
How to convert image resources to integer?
I used this:

int rh=this.getResources().getIdentifier("ic_launcher", null, this.getPackageName());

but it wont work.
I logcat this and the value of rh is 0 always.
is there any alternative way to convert image to integer?

Body:
You can achieve this without using resource also.

int id=R.drawable.icon;

Here, icon is image in your drawable folder.

To set this id value to integer

ImageView imageView=null;
imageView.setImageResource(id);


答:
In php we have new DateTime function. So you can use this to match your date as give below example

```<code>$refresh = false;
$eightthirtyam = "08:30:00";
$date = new DateTime();
if($date->format('H:i:s') == $eightthirtyam)
{
    $refresh = true;
}
</code>```

Here is an example

```<code>$refresh = "false";
$eightthirtyam = "08:30:00";
$date = new DateTime("2017-06-07 8:30:00"); // suppose your system current time is this.
if($date->format('H:i:s') == $eightthirtyam)
{
    $refresh = "true";
}
echo $refresh;
</code>```

You can check answer by executing on online php editor http://www.writephponline.com/

Try above example, I think this may help you.

Body:
In php we have new DateTime function. So you can use this to match your date as give below example

$refresh = false;
$eightthirtyam = "08:30:00";
$date = new DateTime();
if($date->format('H:i:s') == $eightthirtyam)
{
    $refresh = true;
}

Here is an example

$refresh = "false";
$eightthirtyam = "08:30:00";
$date = new DateTime("2017-06-07 8:30:00"); // suppose your system current time is this.
if($date->format('H:i:s') == $eightthirtyam)
{
    $refresh = "true";
}
echo $refresh;

You can check answer by executing on online php editor http://www.writephponline.com/

Try above example, I think this may help you.


问:
Can I concat a string and a variable to select a DOM element in JavaScript?
I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

```<code>var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};
</code>```

Ideally I would be able to select an element and style that via javascript.

Much appreciated

Thanks All.

Moe

答:
Agree with @jaromanda-x:

```<code>var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
   console.log(window['copy'+i]);
};
</code>```

Or you can use more simple example, like:

```<code>for (var i=1; i<4; i++) {
    var name = 'copy' + i;
    console.log(document.getElementById(name));
};
</code>```

Or even:

```<code>for (var i=1; i<4; i++) {
    console.log(document.getElementById('copy' + i));
};
</code>```

Body:
I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};

Ideally I would be able to select an element and style that via javascript.

Much appreciated

Thanks All.

Moe

Body:
Agree with @jaromanda-x:

var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
   console.log(window['copy'+i]);
};

Or you can use more simple example, like:

for (var i=1; i<4; i++) {
    var name = 'copy' + i;
    console.log(document.getElementById(name));
};

Or even:

for (var i=1; i<4; i++) {
    console.log(document.getElementById('copy' + i));
};


问:
Hiding/Changing GIDSignInButton after signing in
So I'm pressing the GIDSignInButton, being taken through the sign in flow, but after the view controller is dismissed the button is still there with the same prompt: "Sign in". Well, I'm already signed in!

If my func signIn protocol is within my appDel, how can I hide or change the GIDSignInButton in a view controller after signing in?

答:
This is an old question, but I just spent some time with this and never found a good answer anywhere else. Turns out, there's no reason the GIDSignInDelegate implementation needs to be on the AppDelegate. I simply added sign in/out handlers on the UIViewController that hosts the signin button, and rearrange my view there.

```<code>class SettingsTableViewController: UITableViewController, LoginButtonDelegate, GIDSignInDelegate, GIDSignInUIDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().delegate = self
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            //hide sign-in buttons, add sign-out button, etc
        }
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            //show sign-in buttons, hide other stuff
        }
    }

    //similar methods for FBSDK signin, etc
}
</code>```

Body:
This is an old question, but I just spent some time with this and never found a good answer anywhere else. Turns out, there's no reason the GIDSignInDelegate implementation needs to be on the AppDelegate. I simply added sign in/out handlers on the UIViewController that hosts the signin button, and rearrange my view there.

class SettingsTableViewController: UITableViewController, LoginButtonDelegate, GIDSignInDelegate, GIDSignInUIDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().delegate = self
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            //hide sign-in buttons, add sign-out button, etc
        }
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            //show sign-in buttons, hide other stuff
        }
    }

    //similar methods for FBSDK signin, etc
}


问:
How does composition work in C#?
I have a Car Class:

```<code>public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}
</code>```

And an Engine Class:

```<code>public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}
</code>```

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

答:
You could refactor a bit your classes like below, in order to avoid boilerplate code. We just use a feature called auto implement properties.

```<code>public class Engine
{
    public int Code { get; set; }
    public DateTime Year { get; set; }
}

public class Car
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public Engine Engine {get; set; }
}
</code>```

Please notice now how many lines of codes have been removed.

Regarding your question, you could create an object of type Car using an object initializer like below:

```<code>var car = new Car
{
    Brand = "the brand name";
    Model = "the model name";
    Engine = new Engine
    {
        Code = "the code engine";
        Year = new DateTime(2017,1,1); // the year the engine manufactured.
    }
}
</code>```

I would suggest you read about both of these features, auto implemented properties and object initializers. Below, there are two links about these features.

Auto-Implemented Properties

Object and Collection Initializers

Title: How does composition work in C#?

Body:
I have a Car Class:

public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}

And an Engine Class:

public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

Body:
You could refactor a bit your classes like below, in order to avoid boilerplate code. We just use a feature called auto implement properties.

public class Engine
{
    public int Code { get; set; }
    public DateTime Year { get; set; }
}

public class Car
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public Engine Engine {get; set; }
}

Please notice now how many lines of codes have been removed.

Regarding your question, you could create an object of type Car using an object initializer like below:

var car = new Car
{
    Brand = "the brand name";
    Model = "the model name";
    Engine = new Engine
    {
        Code = "the code engine";
        Year = new DateTime(2017,1,1); // the year the engine manufactured.
    }
}

I would suggest you read about both of these features, auto implemented properties and object initializers. Below, there are two links about these features.

Auto-Implemented Properties

Object and Collection Initializers


问:
how do I use templates stored in a database for smarty?
how can I use the display function or fetch function of smarty on templates I have in a database?

I could get that template using a query, but from there on... i'm stuck.

anybody know how to do this?

答:
Google says...

http://www.smarty.net/forums/viewtopic.php?t=37&sid=277600ede9d67d68bb2521722fe8f011


问:
Retrieving data from a variable through http request
I am new to http request and php. I have a http:

```<code>xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
         var doc = xmlhttp.response;
         myFunc(doc);
       }
   };
   xmlhttp.open("GET",some.php",true);
   xmlhttp.responseType = "document";
   xmlhttp.send(null);
</code>```

The php file:

```<code><!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body id="idk">
        <?php
        include("include1.inc");
        include_once("include2.inc");

        $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
        $table = 'table';

        $data = retrieveData($table, $cxn);//selects data from mysql db return array
        var_dump($data);

         ?>
      </body>
    </html>
</code>```

How would I get the data variable which holds my array from my database?
When i dump or print the variable the array is passed `responseText. Is there a more eloquent way to just grab that array?

答:
You sets response type as 'document', so you'll get HTMLDocument onbject as a response. So if you need to get only data variable try change your code this way:
javascript:

```<code>   xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
         var doc = xmlhttp.response;
         myFunc(doc);
       }
   };
   xmlhttp.open("GET","some.php",true);
   xmlhttp.responseType = "json";
   xmlhttp.send();
</code>```

And php:

```<code><?php
        include("include1.inc");
        include_once("include2.inc");

        $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
        $table = 'table';

        $data = retrieveData($table, $cxn);//selects data from mysql db return array
        echo json_encode($data);
?>
</code>```

Please, note that in this case php script doesn't contain any html tag, only php code.

Body:
I am new to http request and php. I have a http:

xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
         var doc = xmlhttp.response;
         myFunc(doc);
       }
   };
   xmlhttp.open("GET",some.php",true);
   xmlhttp.responseType = "document";
   xmlhttp.send(null);

The php file:

<!DOCTYPE html>

        <meta charset="utf-8">
        <title></title>

        <?php
        include("include1.inc");
        include_once("include2.inc");

        $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
        $table = 'table';

        $data = retrieveData($table, $cxn);//selects data from mysql db return array
        var_dump($data);

         ?>

How would I get the data variable which holds my array from my database?
When i dump or print the variable the array is passed `responseText. Is there a more eloquent way to just grab that array?

Body:
You sets response type as 'document', so you'll get HTMLDocument onbject as a response. So if you need to get only data variable try change your code this way:
javascript:

   xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
         var doc = xmlhttp.response;
         myFunc(doc);
       }
   };
   xmlhttp.open("GET","some.php",true);
   xmlhttp.responseType = "json";
   xmlhttp.send();

And php:

<?php
        include("include1.inc");
        include_once("include2.inc");

        $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
        $table = 'table';

        $data = retrieveData($table, $cxn);//selects data from mysql db return array
        echo json_encode($data);
?>

Please, note that in this case php script doesn't contain any html tag, only php code.


问:
Python list of list sorting but with respect to specific elements
I am having list of list and when i am using sort() then it is sorting my list according to first element. What should i do to sort with respect to other elements in python.
Snapshot of code

```<code>sheetmarks=[]
for _ in range(int(input())):
sheetmarks.append([input(),float(input())])
sheetmarks.sort()
print(sheetmarks)
</code>```

Output::::[['Akriti', 41.0], ['Berry', 37.21], ['Harry', 37.21], ['Harsh', 39.0], ['Tina', 37.2]]

But i would like to sort this list of list according to number not by name. I am new at programming and python. Need some suggestions.

答:
```<code>output.sort(lambda element: element[1])
</code>```

Will sort by second element.

```<code>>>> output
[['Tina', 37.2], ['Berry', 37.21], ['Harry', 37.21], ['Harsh', 39.0], ['Akriti', 41.0]]
</code>```

Body:
I am having list of list and when i am using sort() then it is sorting my list according to first element. What should i do to sort with respect to other elements in python.
Snapshot of code

sheetmarks=[]
for _ in range(int(input())):
sheetmarks.append([input(),float(input())])
sheetmarks.sort()
print(sheetmarks)

Output::::[['Akriti', 41.0], ['Berry', 37.21], ['Harry', 37.21], ['Harsh', 39.0], ['Tina', 37.2]]

But i would like to sort this list of list according to number not by name. I am new at programming and python. Need some suggestions.

Body:
output.sort(lambda element: element[1])

Will sort by second element.

>>> output
[['Tina', 37.2], ['Berry', 37.21], ['Harry', 37.21], ['Harsh', 39.0], ['Akriti', 41.0]]


问:
Tensorflow program results in type conversion error
Tring to master Tensorflow, following documentation of TensorFlow.

Below program results in 'Incompatible type conversion error'

```<code>import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = 1.0
linear_model = W * x + b
#tf.to_float(linear_model, name='ToFloat')

# Global initialization is must
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))
</code>```

Above program results in this error

File "v-prog3-variables.py", line 7, in
      linear_model = W * x + b
  .. .. ..
  ValueError: Incompatible type conversion requested to type 'float32'
  for variable of type 'int32_ref'

I tried to solve the problem by defining the 'linear_model' variable as float (linear_model = 1.0) or tf.to_float(linear_model = W * x + b)

but nothing works

Im a TensorFlow newbie, please help me out.
Thanks in advance.

答:
You need to use a named argument for the type, e.g. tf.Variable([.3], dtype=tf.float32)

The signature of tf.Variable is __init__(self, initial_value=None, trainable=True,... leading to common errors.

The __init__ method will then infer type from your inputs:

[.3] will give a tf.float32, and

[-3] will give a tf.int32
leading to the error you got when you multiply them.

If you want to stick with the tf.float32 type, you could also use [-3.] as initial value for b.

Body:
Tring to master Tensorflow, following documentation of TensorFlow.

Below program results in 'Incompatible type conversion error'

import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = 1.0
linear_model = W * x + b
#tf.to_float(linear_model, name='ToFloat')

# Global initialization is must
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))

Above program results in this error

File "v-prog3-variables.py", line 7, in
      linear_model = W * x + b
  .. .. ..
  ValueError: Incompatible type conversion requested to type 'float32'
  for variable of type 'int32_ref'

I tried to solve the problem by defining the 'linear_model' variable as float (linear_model = 1.0) or tf.to_float(linear_model = W * x + b)

but nothing works

Im a TensorFlow newbie, please help me out.
Thanks in advance.


问:
Simple Angular Module not working properly
So I'm trying to do a small test app with angular js I have

    {{firstName + " " + lastName}}

in the the body and this

```<code><script>
      var testapp = angular.module("testApp",[]);
      testapp.controller("myCtrl",function ($scope) {
          $scope.firstName = "John";
          $scope.lastName = "Doe";
      });
  </script>
</code>```

is what it's going off of. However, I'm still receiving this:

How can I get it to display what I want which is "John Doe"? I know I'm probably doing something simple wrong...

答:
```<code>//Create a seperate js file named module.js in which add your code as below
var testapp = angular.module("testApp",[]);
  testapp.controller("myCtrl",function ($scope) {
      $scope.firstName = "John";
      $scope.lastName = "Doe";
  });

//then inject module.js file below the angular.min.js and please make
//angular.min.js locally because it won't work when you will offline
</code>```

Body:
So I'm trying to do a small test app with angular js I have

    {{firstName + " " + lastName}}

in the the body and this

is what it's going off of. However, I'm still receiving this:

How can I get it to display what I want which is "John Doe"? I know I'm probably doing something simple wrong...


问:
Prolog - infinite loop
I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.

My predicates:

```<code>remove_first([_,H1|T], [H1|T]).

remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).

remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).

member(X, [X|_]).
member(X, [_|T]) :- member(X, T).

is_middle(X, In) :-
    middle(In, Out),
    member(X, Out), !.
</code>```

And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.

答:
Debugging Prolog takes some different skills, so let's take the long road there.

First, let's notice something interesting about your two sample queries. The first one succeeds, and it should; the second one should fail, but instead it loops. This tidbit is a clue: it suggests that we're trying to handle a false case. This is a common mistake among people using Prolog after other languages. In Prolog, it's often enough to be explicit about successful cases and just let failures happen through failed unifications.

The standard tool for debugging Prolog is trace/0. The idea is, you activate trace mode and then run your query, like this:

```<code>?- trace,  is_middle(1,[2,2,3]).
</code>```

The trouble with trace/0 is that it can take some effort to understand what's happening with it. Each line starts with one of these four verbs: call, exit, redo, or fail. Then there's a number which indicates the nesting level of the call. The call and redo verbs tell you that you're entering a computation; exit and fail tell you a computation is ceasing and the nesting level is about to decrease. Call/exit are the normal case, fail/redo are what makes Prolog special, the non-determinism. In general, an infinite loop will look like some prefix of meaningful work (or possibly not) followed by an endlessly repeating chunk of output from trace. And we see that here. Prefix:

```<code>Call: (8) is_middle(1, [2, 2, 3]) ? creep
Call: (9) middle([2, 2, 3], _G1194) ? creep
Call: (10) remove_first_and_last([2, 2, 3], _G1194) ? creep
Call: (11) remove_first([2, 2, 3], _G1194) ? creep
Exit: (11) remove_first([2, 2, 3], [2, 3]) ? creep
Call: (11) remove_last([2, 3], _G1197) ? creep
Call: (12) remove_last([3], _G1190) ? creep
Exit: (12) remove_last([3], []) ? creep
Exit: (11) remove_last([2, 3], [2]) ? creep
Exit: (10) remove_first_and_last([2, 2, 3], [2]) ? creep
</code>```

Repeating chunk:

```<code>Call: (10) middle([2], _G1200) ? creep
Exit: (10) middle([2], [2]) ? creep
Exit: (9) middle([2, 2, 3], [2]) ? creep
Call: (9) member(1, [2]) ? creep
Call: (10) member(1, []) ? creep
Fail: (10) member(1, []) ? creep
Fail: (9) member(1, [2]) ? creep
Redo: (10) middle([2], _G1200) ? creep
Call: (11) remove_first_and_last([2], _G1200) ? creep
Exit: (11) remove_first_and_last([2], [2]) ? creep
</code>```

Now you can see it would be much easier to trigger the bad behavior just with this query:

```<code>[trace]  ?- is_middle(2,[3]).
   Call: (7) is_middle(2, [3]) ? creep
   Call: (8) middle([3], _G398) ? creep
   Exit: (8) middle([3], [3]) ? creep
   Call: (8) member(2, [3]) ? creep
   Call: (9) member(2, []) ? creep
   Fail: (9) member(2, []) ? creep
   Fail: (8) member(2, [3]) ? creep
   Redo: (8) middle([3], _G398) ? creep
   Call: (9) remove_first_and_last([3], _G398) ? creep
   Exit: (9) remove_first_and_last([3], [3]) ? creep
   Call: (9) middle([3], _G401) ? creep
   Exit: (9) middle([3], [3]) ? creep
   Exit: (8) middle([3], [3]) ? creep
   Call: (8) member(2, [3]) ? creep
   Call: (9) member(2, []) ? creep
   Fail: (9) member(2, []) ? creep
   Fail: (8) member(2, [3]) ? creep
   Redo: (9) middle([3], _G401) ? creep
</code>```

Now it should be clear that the problem has to do with the interplay of middle/2, remove_first_and_last/2 and member/2. Your definition of member/2 is exactly the standard definition so it probably isn't to blame. Now, interestingly, you have middle/2 calling both itself and remove_first_and_last/2. And both middle/2 and remove_first_and_last/2 have an identical clause: m([X], [X]).

This kind of thing is a great generator of infinite recursion, because the first thing middle/2 does in its second clause is exactly what it just tried to do and failed with its own first clause. So it can find itself entering a recursive call in the second clause with exactly the same state it had in an earlier failed call to itself.

The solution is to look at remove_first_and_last/2 and realize that your first clause there does not actually remove the first and last element. Removing the remove_first_and_last([X], [X]) clause fixes the code:

```<code>[trace]  ?- is_middle(2,[3]).
   Call: (7) is_middle(2, [3]) ? creep
   Call: (8) middle([3], _G398) ? creep
   Exit: (8) middle([3], [3]) ? creep
   Call: (8) member(2, [3]) ? creep
   Call: (9) member(2, []) ? creep
   Fail: (9) member(2, []) ? creep
   Fail: (8) member(2, [3]) ? creep
   Redo: (8) middle([3], _G398) ? creep
   Call: (9) remove_first_and_last([3], _G398) ? creep
   Call: (10) remove_first([3], _G398) ? creep
   Fail: (10) remove_first([3], _G398) ? creep
   Fail: (9) remove_first_and_last([3], _G398) ? creep
   Fail: (8) middle([3], _G398) ? creep
   Fail: (7) is_middle(2, [3]) ? creep
false.
</code>```

Both your tests also now work:

```<code>?- is_middle(1,[2,1,3]).
true.

?- is_middle(1,[2,2,3]).
false.
</code>```

I think you added the base case here out of a sense of duty to have one. But the reality is that if you have a list of one element, it should fail to unify with remove_first_and_last/2 under any circumstance. This is very similar to handling an error case explicitly with Prolog, which tends to interfere with the working of the machinery.

Now, one thing that's missing is, how do you want to handle even-length lists? What you have right now won't, with or without my change. Even-length lists don't have a middle element; is that what you intend? I suspect it isn't, because of the appearance of member/2 in is_middle/2.

Comments on is_middle/2

What you have here could be restructured like so:

```<code>is_middle(X, In) :- middle(In, [X]).
</code>```

Usage of member/2 isn't buying you anything because middle/2 can't ever produce a non-singleton list in its second argument. But, if it did, because you had even-length lists, it would be profitable. You could even make this code work that way by adding a third clause to middle/2:

```<code>middle([X,Y], [X,Y]).
</code>```

Now see middle/2 works on even-length lists like so:

```<code>?- middle([2,1,3,4], X).
X = [1, 3] ;
false.
</code>```

Now the cut gets you into trouble though. For instance, 1 and 3 are both is_middle/2:

```<code>?- is_middle(1, [2,1,3,4]).
true.

?- is_middle(3, [2,1,3,4]).
true.
</code>```

Unfortunately though, if you ask for middle elements, you just have 1:

```<code>Call: (8) is_middle(1, [2, 2, 3]) ? creep
Call: (9) middle([2, 2, 3], _G1194) ? creep
Call: (10) remove_first_and_last([2, 2, 3], _G1194) ? creep
Call: (11) remove_first([2, 2, 3], _G1194) ? creep
Exit: (11) remove_first([2, 2, 3], [2, 3]) ? creep
Call: (11) remove_last([2, 3], _G1197) ? creep
Call: (12) remove_last([3], _G1190) ? creep
Exit: (12) remove_last([3], []) ? creep
Exit: (11) remove_last([2, 3], [2]) ? creep
Exit: (10) remove_first_and_last([2, 2, 3], [2]) ? creep
</code>```0

What happened to 3? You prevented it from being generated with your cut. I am not sure why the cut is here. I think you must have put it in to try and control the infinite recursion, but it doesn't help you, so get rid of it.

Debugging by random addition of cuts is generally not a great idea. A much better approach is using Ulrich Neumerkel's failure slice approach (see this paper or search the tag for more information).

DCG bonus

You can rephrase remove_first_and_last/2 as a DCG rule:

```<code>Call: (8) is_middle(1, [2, 2, 3]) ? creep
Call: (9) middle([2, 2, 3], _G1194) ? creep
Call: (10) remove_first_and_last([2, 2, 3], _G1194) ? creep
Call: (11) remove_first([2, 2, 3], _G1194) ? creep
Exit: (11) remove_first([2, 2, 3], [2, 3]) ? creep
Call: (11) remove_last([2, 3], _G1197) ? creep
Call: (12) remove_last([3], _G1190) ? creep
Exit: (12) remove_last([3], []) ? creep
Exit: (11) remove_last([2, 3], [2]) ? creep
Exit: (10) remove_first_and_last([2, 2, 3], [2]) ? creep
</code>```1

Pretty cool, huh? :) That's because the kind of input/output threading you're doing in that rule exactly what DCG rules get transformed into.

Summary of changes

```<code>Call: (8) is_middle(1, [2, 2, 3]) ? creep
Call: (9) middle([2, 2, 3], _G1194) ? creep
Call: (10) remove_first_and_last([2, 2, 3], _G1194) ? creep
Call: (11) remove_first([2, 2, 3], _G1194) ? creep
Exit: (11) remove_first([2, 2, 3], [2, 3]) ? creep
Call: (11) remove_last([2, 3], _G1197) ? creep
Call: (12) remove_last([3], _G1190) ? creep
Exit: (12) remove_last([3], []) ? creep
Exit: (11) remove_last([2, 3], [2]) ? creep
Exit: (10) remove_first_and_last([2, 2, 3], [2]) ? creep
</code>```2

Title: Prolog - infinite loop

Body:
I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.

My predicates:

remove_first([_,H1|T], [H1|T]).

remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).

remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).

member(X, [X|_]).
member(X, [_|T]) :- member(X, T).

is_middle(X, In) :-
    middle(In, Out),
    member(X, Out), !.

And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.

Body:
Debugging Prolog takes some different skills, so let's take the long road there.

First, let's notice something interesting about your two sample queries. The first one succeeds, and it should; the second one should fail, but instead it loops. This tidbit is a clue: it suggests that we're trying to handle a false case. This is a common mistake among people using Prolog after other languages. In Prolog, it's often enough to be explicit about successful cases and just let failures happen through failed unifications.

The standard tool for debugging Prolog is trace/0. The idea is, you activate trace mode and then run your query, like this:

?- trace,  is_middle(1,[2,2,3]).

The trouble with trace/0 is that it can take some effort to understand what's happening with it. Each line starts with one of these four verbs: call, exit, redo, or fail. Then there's a number which indicates the nesting level of the call. The call and redo verbs tell you that you're entering a computation; exit and fail tell you a computation is ceasing and the nesting level is about to decrease. Call/exit are the normal case, fail/redo are what makes Prolog special, the non-determinism. In general, an infinite loop will look like some prefix of meaningful work (or possibly not) followed by an endlessly repeating chunk of output from trace. And we see that here. Prefix:

Call: (8) is_middle(1, [2, 2, 3]) ? creep
Call: (9) middle([2, 2, 3], _G1194) ? creep
Call: (10) remove_first_and_last([2, 2, 3], _G1194) ? creep
Call: (11) remove_first([2, 2, 3], _G1194) ? creep
Exit: (11) remove_first([2, 2, 3], [2, 3]) ? creep
Call: (11) remove_last([2, 3], _G1197) ? creep
Call: (12) remove_last([3], _G1190) ? creep
Exit: (12) remove_last([3], []) ? creep
Exit: (11) remove_last([2, 3], [2]) ? creep
Exit: (10) remove_first_and_last([2, 2, 3], [2]) ? creep

Repeating chunk:

Call: (10) middle([2], _G1200) ? creep
Exit: (10) middle([2], [2]) ? creep
Exit: (9) middle([2, 2, 3], [2]) ? creep
Call: (9) member(1, [2]) ? creep
Call: (10) member(1, []) ? creep
Fail: (10) member(1, []) ? creep
Fail: (9) member(1, [2]) ? creep
Redo: (10) middle([2], _G1200) ? creep
Call: (11) remove_first_and_last([2], _G1200) ? creep
Exit: (11) remove_first_and_last([2], [2]) ? creep

Now you can see it would be much easier to trigger the bad behavior just with this query:

[trace]  ?- is_middle(2,[3]).
   Call: (7) is_middle(2, [3]) ? creep
   Call: (8) middle([3], _G398) ? creep
   Exit: (8) middle([3], [3]) ? creep
   Call: (8) member(2, [3]) ? creep
   Call: (9) member(2, []) ? creep
   Fail: (9) member(2, []) ? creep
   Fail: (8) member(2, [3]) ? creep
   Redo: (8) middle([3], _G398) ? creep
   Call: (9) remove_first_and_last([3], _G398) ? creep
   Exit: (9) remove_first_and_last([3], [3]) ? creep
   Call: (9) middle([3], _G401) ? creep
   Exit: (9) middle([3], [3]) ? creep
   Exit: (8) middle([3], [3]) ? creep
   Call: (8) member(2, [3]) ? creep
   Call: (9) member(2, []) ? creep
   Fail: (9) member(2, []) ? creep
   Fail: (8) member(2, [3]) ? creep
   Redo: (9) middle([3], _G401) ? creep

Now it should be clear that the problem has to do with the interplay of middle/2, remove_first_and_last/2 and member/2. Your definition of member/2 is exactly the standard definition so it probably isn't to blame. Now, interestingly, you have middle/2 calling both itself and remove_first_and_last/2. And both middle/2 and remove_first_and_last/2 have an identical clause: m([X], [X]).

This kind of thing is a great generator of infinite recursion, because the first thing middle/2 does in its second clause is exactly what it just tried to do and failed with its own first clause. So it can find itself entering a recursive call in the second clause with exactly the same state it had in an earlier failed call to itself.

The solution is to look at remove_first_and_last/2 and realize that your first clause there does not actually remove the first and last element. Removing the remove_first_and_last([X], [X]) clause fixes the code:

[trace]  ?- is_middle(2,[3]).
   Call: (7) is_middle(2, [3]) ? creep
   Call: (8) middle([3], _G398) ? creep
   Exit: (8) middle([3], [3]) ? creep
   Call: (8) member(2, [3]) ? creep
   Call: (9) member(2, []) ? creep
   Fail: (9) member(2, []) ? creep
   Fail: (8) member(2, [3]) ? creep
   Redo: (8) middle([3], _G398) ? creep
   Call: (9) remove_first_and_last([3], _G398) ? creep
   Call: (10) remove_first([3], _G398) ? creep
   Fail: (10) remove_first([3], _G398) ? creep
   Fail: (9) remove_first_and_last([3], _G398) ? creep
   Fail: (8) middle([3], _G398) ? creep
   Fail: (7) is_middle(2, [3]) ? creep
false.

Both your tests also now work:

?- is_middle(1,[2,1,3]).
true.

?- is_middle(1,[2,2,3]).
false.

I think you added the base case here out of a sense of duty to have one. But the reality is that if you have a list of one element, it should fail to unify with remove_first_and_last/2 under any circumstance. This is very similar to handling an error case explicitly with Prolog, which tends to interfere with the working of the machinery.

Now, one thing that's missing is, how do you want to handle even-length lists? What you have right now won't, with or without my change. Even-length lists don't have a middle element; is that what you intend? I suspect it isn't, because of the appearance of member/2 in is_middle/2.

Comments on is_middle/2

What you have here could be restructured like so:

is_middle(X, In) :- middle(In, [X]).

Usage of member/2 isn't buying you anything because middle/2 can't ever produce a non-singleton list in its second argument. But, if it did, because you had even-length lists, it would be profitable. You could even make this code work that way by adding a third clause to middle/2:

middle([X,Y], [X,Y]).

Now see middle/2 works on even-length lists like so:

?- middle([2,1,3,4], X).
X = [1, 3] ;
false.

Now the cut gets you into trouble though. For instance, 1 and 3 are both is_middle/2:

?- is_middle(1, [2,1,3,4]).
true.

?- is_middle(3, [2,1,3,4]).
true.

Unfortunately though, if you ask for middle elements, you just have 1:

?- is_middle(X, [2,1,3,4]).
X = 1.

What happened to 3? You prevented it from being generated with your cut. I am not sure why the cut is here. I think you must have put it in to try and control the infinite recursion, but it doesn't help you, so get rid of it.

Debugging by random addition of cuts is generally not a great idea. A much better approach is using Ulrich Neumerkel's failure slice approach (see this paper or search the tag for more information).

DCG bonus

You can rephrase remove_first_and_last/2 as a DCG rule:

remove_first_and_last --> remove_first, remove_last.

Pretty cool, huh? :) That's because the kind of input/output threading you're doing in that rule exactly what DCG rules get transformed into.

Summary of changes

remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle([X,Y], [X,Y]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).


问:
Drawing Pixels in WPF
how would I manage pixel-by-pixel rendering in WPF (like, say, for a raytracer)? My initial guess was to create a BitmapImage, modify the buffer, and display that in an Image control, but I couldn't figure out how to create one (the create method requires a block of unmanaged memory)</p>

答:
You can add small rects if you want, but each of those is a FrameworkElement, so it's probably a bit heavyweight. The other option is to create yourself a DrawingVisual, draw on it, render it then stick it in an image:</p>

```<code>private void DrawRubbish()
{
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext dc = dv.RenderOpen())
    {
        Random rand = new Random();

        for (int i = 0; i < 200; i++)
            dc.DrawRectangle(Brushes.Red, null, new Rect(rand.NextDouble() * 200, rand.NextDouble() * 200, 1, 1));

        dc.Close();
    }
    RenderTargetBitmap rtb = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
    rtb.Render(dv);
    Image img = new Image();
    img.Source = rtb;
    MainGrid.Children.Add(img);
}
</code>```

OwnerDisplayName: Jimmy

Title: Drawing Pixels in WPF

LastEditorDisplayName: Jimmy

Body:
You can add small rects if you want, but each of those is a FrameworkElement, so it's probably a bit heavyweight. The other option is to create yourself a DrawingVisual, draw on it, render it then stick it in an image:

private void DrawRubbish()
{
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext dc = dv.RenderOpen())
    {
        Random rand = new Random();

        for (int i = 0; i < 200; i++)
            dc.DrawRectangle(Brushes.Red, null, new Rect(rand.NextDouble() * 200, rand.NextDouble() * 200, 1, 1));

        dc.Close();
    }
    RenderTargetBitmap rtb = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
    rtb.Render(dv);
    Image img = new Image();
    img.Source = rtb;
    MainGrid.Children.Add(img);
}

OwnerDisplayName: Steve Robbins


问:
telnetlib read_until() function confusion
I am trying to automate some telnet actions with python3. So I started to use the build in telnetlib (not pexpect).

Actually everything works so far but I do not understand completly how read_until works - actually the documentation says that you can set a timeout and if the search string is not found the timeout sends back a empty byte value or or if there is another value thats the one which can be stored as a return value!

Does that make sense ?!

If I wanna read_until a certain value - how do I find out that this value was really the one the function read. Also I couldn't find out how to check if the timeout was hit.

My workaround for now is:

```<code>output = telnet.read_until(str.encode(hostname), 3)
if re.search(hostname, bytes.decode(output), re.IGNORECASE):
   #do something when the output matches the searchstring
else:
   #stop the function
</code>```

but that doesn't make any sense for me, so perhaps you now a better solution

答:
Yes, if your hostname is example.com, read_until will return something like weijwrgnerg hgqwv  blather example.com. Except if it hasn't found the hostname after three seconds, it will just spit out whatever it's got by then: weijwrgnerg hg.

So I think you're doing it almost right. You probably want to re.escape your hostname, otherwise it will interpret it as a regex. Alternatively, you could just use Python's .endswith(). And you can do output.decode() to get a string (rather than bytes.decode(output)).

Body:
I am trying to automate some telnet actions with python3. So I started to use the build in telnetlib (not pexpect).

Actually everything works so far but I do not understand completly how read_until works - actually the documentation says that you can set a timeout and if the search string is not found the timeout sends back a empty byte value or or if there is another value thats the one which can be stored as a return value!

Does that make sense ?!

If I wanna read_until a certain value - how do I find out that this value was really the one the function read. Also I couldn't find out how to check if the timeout was hit.

My workaround for now is:

output = telnet.read_until(str.encode(hostname), 3)
if re.search(hostname, bytes.decode(output), re.IGNORECASE):
   #do something when the output matches the searchstring
else:
   #stop the function

but that doesn't make any sense for me, so perhaps you now a better solution


问:
How to populate TextBoxes using StreamReader and arrays?
I’m trying to create a solution that will pull employee information from a text file, load it to an array, and then have a series of TextBoxes populated from the array when a button is clicked.

I’ve made some progress to where I’m pulling data from the array, and getting it into the text boxes.  However, it’s only individual letters populating the TextBoxes, not the full data.

I’ve attached the code I’ve been working on to achieve my goal, but I’m really hitting a block on where to go next.

For reference the data from the text file is:

Janice

  Jones

  101

  5.25

  Chris

  O Connel

  102

  5.35

  Karen

  Fisk

  103

  6.00

  Tom

  Winn

  104

  5.75

```<code>Private Sub nextButton_Click(sender As Object, e As EventArgs) Handles nextButton.Click
    Dim EmpoyeeStreamReader As New StreamReader("employee.txt")
    Dim EmployeeLineInfoString As String
    Dim EmployeeIndex As Decimal

    EmployeeLineInfoString = EmpoyeeStreamReader.ReadLine()

    Dim EmployeeArray = (EmployeeLineInfoString).ToString

    EmployeeIndex = 0

    Try
        For EmployeeIndex = 0 To 16
            firstNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            lastNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            employeeNumberTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            payRateTextBox.Text = EmployeeArray(EmployeeIndex)
        Next

        For EmployeeIndex = 5 To 16
            firstNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            lastNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            employeeNumberTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            payRateTextBox.Text = EmployeeArray(EmployeeIndex)
        Next
    Catch ex As Exception
        MessageBox.Show("All Employee's have been entered")
    End Try
</code>```

答:
Try something like this out (though it might be better to declare your StreamReader at Form level!):</p>

```<code>Private Sub nextButton_Click(sender As Object, e As EventArgs) Handles nextButton.Click
    Static EmpoyeeStreamReader As StreamReader = Nothing

    If IsNothing(EmpoyeeStreamReader) Then
        EmpoyeeStreamReader = New StreamReader("employee.txt")
    End If

    If Not EmpoyeeStreamReader.EndOfStream Then
        Try
            firstNameTextBox.Text = EmpoyeeStreamReader.ReadLine
            lastNameTextBox.Text = EmpoyeeStreamReader.ReadLine
            employeeNumberTextBox.Text = EmpoyeeStreamReader.ReadLine
            payRateTextBox.Text = EmpoyeeStreamReader.ReadLine
        Catch ex As Exception
            MessageBox.Show("Error Reading Record: Insufficient Number of Lines!")
        End Try
    Else
        MessageBox.Show("No more records!")
        EmpoyeeStreamReader.Close()
        EmpoyeeStreamReader = Nothing
    End If
End Sub
</code>```

Body:
I’m trying to create a solution that will pull employee information from a text file, load it to an array, and then have a series of TextBoxes populated from the array when a button is clicked.

I’ve made some progress to where I’m pulling data from the array, and getting it into the text boxes.  However, it’s only individual letters populating the TextBoxes, not the full data.

I’ve attached the code I’ve been working on to achieve my goal, but I’m really hitting a block on where to go next.

For reference the data from the text file is:

Janice

  Jones

  101

  5.25

  Chris

  O Connel

  102

  5.35

  Karen

  Fisk

  103

  6.00

  Tom

  Winn

  104

  5.75

Private Sub nextButton_Click(sender As Object, e As EventArgs) Handles nextButton.Click
    Dim EmpoyeeStreamReader As New StreamReader("employee.txt")
    Dim EmployeeLineInfoString As String
    Dim EmployeeIndex As Decimal

    EmployeeLineInfoString = EmpoyeeStreamReader.ReadLine()

    Dim EmployeeArray = (EmployeeLineInfoString).ToString

    EmployeeIndex = 0

    Try
        For EmployeeIndex = 0 To 16
            firstNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            lastNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            employeeNumberTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            payRateTextBox.Text = EmployeeArray(EmployeeIndex)
        Next

        For EmployeeIndex = 5 To 16
            firstNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            lastNameTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            employeeNumberTextBox.Text = EmployeeArray(EmployeeIndex)
            EmployeeIndex += 1
            payRateTextBox.Text = EmployeeArray(EmployeeIndex)
        Next
    Catch ex As Exception
        MessageBox.Show("All Employee's have been entered")
    End Try

Body:
Try something like this out (though it might be better to declare your StreamReader at Form level!):

Private Sub nextButton_Click(sender As Object, e As EventArgs) Handles nextButton.Click
    Static EmpoyeeStreamReader As StreamReader = Nothing

    If IsNothing(EmpoyeeStreamReader) Then
        EmpoyeeStreamReader = New StreamReader("employee.txt")
    End If

    If Not EmpoyeeStreamReader.EndOfStream Then
        Try
            firstNameTextBox.Text = EmpoyeeStreamReader.ReadLine
            lastNameTextBox.Text = EmpoyeeStreamReader.ReadLine
            employeeNumberTextBox.Text = EmpoyeeStreamReader.ReadLine
            payRateTextBox.Text = EmpoyeeStreamReader.ReadLine
        Catch ex As Exception
            MessageBox.Show("Error Reading Record: Insufficient Number of Lines!")
        End Try
    Else
        MessageBox.Show("No more records!")
        EmpoyeeStreamReader.Close()
        EmpoyeeStreamReader = Nothing
    End If
End Sub


问:
Unable to switch from PHP5 to PHP7 using Apache 2.4
I recently downloaded the latest version of AppServ (Appserv8) for Windows.
It installs Apache 2.4, MySQL 5.7 and both version of PHP5 and PHP7. After installing, the used version of PHP is 5.

I've tried to switch the version using the script "PHP Version Switch" provided with the installation but it seems not working.

I've tried to manually edit the http.conf file in Apache24 folder but without results.

With these lines Apache starts normally with PHP5:

```<code>LoadModule php5_module C:/AppServ/php5/php5apache2_4.dll
PHPIniDir "C:/AppServ/php5/"
</code>```

If I edit with:

```<code>LoadModule php7_module C:/AppServ/php7/php7apache2_4.dll
PHPIniDir "C:/AppServ/php7/"
</code>```

When I try to start Apache, I obtain the following error:

```<code>httpd.exe: Syntax error on line 180 of C:/Appserv/Apache24/conf/httpd.conf: Cannot load C:/Appserv/php7/php7apache2_4.dll into server: Impossibile trovare il modulo specificato.
</code>```

(Part of the error is in italian: unable to find the specified module)

Note that the dll is in the folder as specified in the path. I'm stuck with this error and I don't know where I have to modify configuration file (if is this the problem).

EDIT1:
Somewhere I've found this discussion in which the author explain that, because of a dependencies of Visual C++, the DLL can be not readable. I checked my system, I cleaned it from multiple installation of Microsoft Visual C++ redistributable and I tried to install x64 or x86 versions.

With the x86 version, I have the previous problem.
With the x64 version, I can't start Apache because of a missing dll: it should be because apache is x86 version (I'm not sure of this).

EDIT2:
As suggested from @chugadie, I tried to use dependencywalker to trace dependencies.
I found several missing files with prefix API-MS-WIN-CRT.
Now I'm trying to fix but I have several problems with dll which are x86 and x64. I think the best way is to reinstall all components in x64 architecture.

Any help is very appreciated.

答:
On AppServ folder on Start Menu (or Win Key + S) you must sear for PHP Version Switch and it will request admin privileges (if you deny it, it won't work), then it will show a cmd console rquesting you the PHP version to set on Apache, press 7 to switch PHP 7 or press 5 to switch PHP5.

If you did this and it won't work you should undo changes you did it on AppServ files.

Body:
I recently downloaded the latest version of AppServ (Appserv8) for Windows.
It installs Apache 2.4, MySQL 5.7 and both version of PHP5 and PHP7. After installing, the used version of PHP is 5.

I've tried to switch the version using the script "PHP Version Switch" provided with the installation but it seems not working.

I've tried to manually edit the http.conf file in Apache24 folder but without results.

With these lines Apache starts normally with PHP5:

LoadModule php5_module C:/AppServ/php5/php5apache2_4.dll
PHPIniDir "C:/AppServ/php5/"

If I edit with:

LoadModule php7_module C:/AppServ/php7/php7apache2_4.dll
PHPIniDir "C:/AppServ/php7/"

When I try to start Apache, I obtain the following error:

httpd.exe: Syntax error on line 180 of C:/Appserv/Apache24/conf/httpd.conf: Cannot load C:/Appserv/php7/php7apache2_4.dll into server: Impossibile trovare il modulo specificato.

(Part of the error is in italian: unable to find the specified module)

Note that the dll is in the folder as specified in the path. I'm stuck with this error and I don't know where I have to modify configuration file (if is this the problem).

EDIT1:
Somewhere I've found this discussion in which the author explain that, because of a dependencies of Visual C++, the DLL can be not readable. I checked my system, I cleaned it from multiple installation of Microsoft Visual C++ redistributable and I tried to install x64 or x86 versions.

With the x86 version, I have the previous problem.
With the x64 version, I can't start Apache because of a missing dll: it should be because apache is x86 version (I'm not sure of this).

EDIT2:
As suggested from @chugadie, I tried to use dependencywalker to trace dependencies.
I found several missing files with prefix API-MS-WIN-CRT.
Now I'm trying to fix but I have several problems with dll which are x86 and x64. I think the best way is to reinstall all components in x64 architecture.

Any help is very appreciated.


问:
How can I use JSON_MODIFY to update all elements in an array that match a some criteria
I've got a table with a json column and that json contains an array of items. I want to update some of those items where  a given criteria is met. So the path to the array is $.activities. And where type equals multichoice, I want to set data.insightsTitle to data.title.

There doesn't seem to be anyway to query the path (like good ol' xpath) so I've been scratching my head a bit.

答:
I came up with this solution, seems to work and isn't too gross! It needs a loop as it is writing to the json column for each of the array items that matches.

```<code>begin tran t1

DECLARE @Count int = -1

while @Count != 0
begin
update dp
    set definition = JSON_MODIFY(dp.definition, '$.activities[' + (CAST(src.[key] as nvarchar(6)) COLLATE SQL_Latin1_General_CP1_CI_AS) + ']', JSON_MODIFY(src.value, '$.data.insightsTitle', JSON_VALUE(src.value, '$.data.title')))
from
    deviceprofile dp
join (
select dp.deviceprofileid, g.*--dp.definition
from deviceprofile dp
CROSS APPLY OPENJSON(dp.definition, '$.activities') g
) src on dp.deviceprofileid = src.deviceprofileid
where JSON_VALUE(src.value, '$.type') = 'multichoice' and JSON_VALUE(src.value, '$.data.insightsTitle') is null

select @count = count(distinct dp.deviceprofileid)
from deviceprofile dp
CROSS APPLY OPENJSON(dp.definition, '$.activities') WITH (type nvarchar(100), insightsTitle nvarchar(256) '$.data.insightsTitle') g
where g.type = 'multichoice' and g.insightsTitle is null

print @count
end

rollback tran
</code>```

So if you dont specify WITH you get this magic Key column which gives you the index and the full json for the array item. you then update just that block and the use they key to update the entire json string one by one for each matching array item. Enjoy.

ContentLicense: CC BY-SA 4.0

Body:
I came up with this solution, seems to work and isn't too gross! It needs a loop as it is writing to the json column for each of the array items that matches.

begin tran t1

DECLARE @Count int = -1

while @Count != 0
begin
update dp
    set definition = JSON_MODIFY(dp.definition, '$.activities[' + (CAST(src.[key] as nvarchar(6)) COLLATE SQL_Latin1_General_CP1_CI_AS) + ']', JSON_MODIFY(src.value, '$.data.insightsTitle', JSON_VALUE(src.value, '$.data.title')))
from
    deviceprofile dp
join (
select dp.deviceprofileid, g.*--dp.definition
from deviceprofile dp
CROSS APPLY OPENJSON(dp.definition, '$.activities') g
) src on dp.deviceprofileid = src.deviceprofileid
where JSON_VALUE(src.value, '$.type') = 'multichoice' and JSON_VALUE(src.value, '$.data.insightsTitle') is null

select @count = count(distinct dp.deviceprofileid)
from deviceprofile dp
CROSS APPLY OPENJSON(dp.definition, '$.activities') WITH (type nvarchar(100), insightsTitle nvarchar(256) '$.data.insightsTitle') g
where g.type = 'multichoice' and g.insightsTitle is null

print @count
end

rollback tran

So if you dont specify WITH you get this magic Key column which gives you the index and the full json for the array item. you then update just that block and the use they key to update the entire json string one by one for each matching array item. Enjoy.


问:
Refactoring advice: maps to POJOs
I currently am part of a project where there is an interface like this:

```<code>public interface RepositoryOperation {

    public OperationResult execute(Map<RepOpParam, Object> params);
}
</code>```

This interface has about ~100 implementers.

To call an implementer one needs to do the following:

```<code>final Map<RepOpParam, Object> opParams = new HashMap<RepOpParam, Object>();
opParams.put(ParamName.NAME1, val1);
opParams.put(ParamName.NAME2, val2);
</code>```

Now I think that there is obviously something wrong with anything with a<Something, Object> generic declaration.

Currently this causes a caller of a OperationImpl to have to actually read the code of the operation in order to know how to build the argument map. (and this is not even the worst of the problems, but I don't want to cite them all since they are fairly obvious)

After some discussion I managed to convince my colleagues to let me do some refactoring.

It seems to me that the simplest 'fix' would be to change the interface like so:

```<code>public interface RepositoryOperation {

    public OperationResult execute(OperationParam param);
}
</code>```

After all the concrete operations will define (extend) their own OperationParam and the needed arguments would be visible to everybody. (which is the 'normal way' to do things like that IMHO)

So as I see it since the interface implementers are quite numerous I have several choices:

Try to change the interface and rewrite all the Operation calls to use objects instead of maps. This seems the cleanest, but I think that since the operations are a lot it might be too much work in practice. (~2 weeks with tests probably)

Add an additional method to the interface like so:

```<code>public interface RepositoryOperation {
    public OperationResult execute(Map<String, Object> params);
    public OperationResult execute(OperationParam params);
}
</code>```

and fix the map calls whenever I come across them during functionality implementation.

Live with it (please no !).

So my question is.

Does anyone see a better approach for 'fixing' the maps and if you do would you fix them with method 1 or 2 or not fix them at all.

EDIT:
Thanks for the great answers. I would accept both Max's and Riduidel's answers if I could, but since I can't I'm leaning a bit more towards Riduidel's.

答:
First of all, I think the interface is not perfect. You could add some generics to make it prettier:

```<code>public interface RepositoryOperation<P extends OperationParam, R extends OperationResult> {
    public R execute(T params);
}
</code>```

Now, we will need some backward compatibility code. I'd go with this:

```<code>//We are using basic types for deprecated operations
public abstract class DeprecatedRepositoryOperation implements RepositoryOperation<OperationParam, OperationResult> {
    //Each of our operations will need to implement this method
    public abstract OperationResult execute(Map<String, Object> params);

    //This will be the method that we can call from the outside
    public OperationResult execute(OperationParam params) {
        Map<String, Object> paramMap = getMapFromObj(params);
        return execute(paramMap);
    }
}
</code>```

Here is how will old operation look like:

```<code>public class SomeOldOperation extends DeprecatedRepositoryOperation {
    public OperationResult execute(Map<String, Object> params) {
        //Same old code as was here before. Nothing changes
    }
}
</code>```

New operation will be prettier:

```<code>public class DeleteOperation implements RepositoryOperation<DeleteParam, DeleteResult> {
    public DeleteResult execute(DeleteParam param) {
        database.delete(param.getID());
        ...
    }
}
</code>```

But the calling code can use both functions now (an example of code):

```<code>String operationName = getOperationName(); //="Delete"
Map<String, RepositoryOperation> operationMap = getOperations(); //=List of all operations
OperationParam param = getParam(); //=DeleteParam
operationMap.execute(param);
</code>```

In case the operation was old one - it will use the converter method from DeprecatedRepositoryOperation.
In case the operation is a new one - it will use the new public R execute(T params) function.

Title: Refactoring advice: maps to POJOs

Body:
I currently am part of a project where there is an interface like this:

public interface RepositoryOperation {

    public OperationResult execute(Map<RepOpParam, Object> params);
}

This interface has about ~100 implementers.

To call an implementer one needs to do the following:

final Map<RepOpParam, Object> opParams = new HashMap<RepOpParam, Object>();
opParams.put(ParamName.NAME1, val1);
opParams.put(ParamName.NAME2, val2);

Now I think that there is obviously something wrong with anything with a<Something, Object> generic declaration.

Currently this causes a caller of a OperationImpl to have to actually read the code of the operation in order to know how to build the argument map. (and this is not even the worst of the problems, but I don't want to cite them all since they are fairly obvious)

After some discussion I managed to convince my colleagues to let me do some refactoring.

It seems to me that the simplest 'fix' would be to change the interface like so:

public interface RepositoryOperation {

    public OperationResult execute(OperationParam param);
}

After all the concrete operations will define (extend) their own OperationParam and the needed arguments would be visible to everybody. (which is the 'normal way' to do things like that IMHO)

So as I see it since the interface implementers are quite numerous I have several choices:

Try to change the interface and rewrite all the Operation calls to use objects instead of maps. This seems the cleanest, but I think that since the operations are a lot it might be too much work in practice. (~2 weeks with tests probably)

Add an additional method to the interface like so:

public interface RepositoryOperation {
    public OperationResult execute(Map<String, Object> params);
    public OperationResult execute(OperationParam params);
}

and fix the map calls whenever I come across them during functionality implementation.

Live with it (please no !).

So my question is.

Does anyone see a better approach for 'fixing' the maps and if you do would you fix them with method 1 or 2 or not fix them at all.

EDIT:
Thanks for the great answers. I would accept both Max's and Riduidel's answers if I could, but since I can't I'm leaning a bit more towards Riduidel's.

Body:
First of all, I think the interface is not perfect. You could add some generics to make it prettier:

public interface RepositoryOperation<P extends OperationParam, R extends OperationResult> {
    public R execute(T params);
}

Now, we will need some backward compatibility code. I'd go with this:

//We are using basic types for deprecated operations
public abstract class DeprecatedRepositoryOperation implements RepositoryOperation<OperationParam, OperationResult> {
    //Each of our operations will need to implement this method
    public abstract OperationResult execute(Map<String, Object> params);

    //This will be the method that we can call from the outside
    public OperationResult execute(OperationParam params) {
        Map<String, Object> paramMap = getMapFromObj(params);
        return execute(paramMap);
    }
}

Here is how will old operation look like:

public class SomeOldOperation extends DeprecatedRepositoryOperation {
    public OperationResult execute(Map<String, Object> params) {
        //Same old code as was here before. Nothing changes
    }
}

New operation will be prettier:

public class DeleteOperation implements RepositoryOperation<DeleteParam, DeleteResult> {
    public DeleteResult execute(DeleteParam param) {
        database.delete(param.getID());
        ...
    }
}

But the calling code can use both functions now (an example of code):

String operationName = getOperationName(); //="Delete"
Map<String, RepositoryOperation> operationMap = getOperations(); //=List of all operations
OperationParam param = getParam(); //=DeleteParam
operationMap.execute(param);

In case the operation was old one - it will use the converter method from DeprecatedRepositoryOperation.
In case the operation is a new one - it will use the new public R execute(T params) function.


问:
Service Worker Install fails: "cannot read property 'addAll of undefined"
So I'll keep this succinct: When trying to install, my service worker fails. This is all of my code in sw.js:

```<code>var cacheName = 'randomstring';
var filesToCache = [ '/' ];

self.addEventListener('install', function (e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName)
            .then(function (cache) {
                console.log('[ServiceWorker] About to fail');
                return cache.addAll(filesToCache);
            })
    );
});
</code>```

I get an exception because cache is undefined (on the cache.addAll bit).

Not really sure why this is the case?

I've used service workers before and never encountered this issue. This is my first time using a service worker with an ASP.Net back-end though, so not sure if that's the problem?

答:
So, I figured this out. I was going to vote to close the question, but I figured I'd leave it here as I saw some other people with this issue who didn't know how to resolve it. Even though it's super-stupid :) (or more accurately, I am).

So I was running the website via the "Play" button, aka "Start Debugging", which, in Visual Studio 2017, launches a special Chrome window, in which the above error will be thrown.

To work around the issue, I can (or you can, internet traveller of the future) simply start without debugging, host the website in IIS, etc.

EDIT: If there's a better workaround where I can use the service worker in debug mode, please suggest it and I'll mark that as the answer. For my specific problem though, the above workaround is fine :).

Body:
So I'll keep this succinct: When trying to install, my service worker fails. This is all of my code in sw.js:

var cacheName = 'randomstring';
var filesToCache = [ '/' ];

self.addEventListener('install', function (e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName)
            .then(function (cache) {
                console.log('[ServiceWorker] About to fail');
                return cache.addAll(filesToCache);
            })
    );
});

I get an exception because cache is undefined (on the cache.addAll bit).

Not really sure why this is the case?

I've used service workers before and never encountered this issue. This is my first time using a service worker with an ASP.Net back-end though, so not sure if that's the problem?


问:
not getting proper base_url in codeigniter app
i am getting this type of url when trying to access pages other than index page

```<code>http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home
</code>```

but url to access page must be

```<code>http://localhost:8012/health-care/index.php/home
</code>```

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

答:
```<code>$config['base_url'] = 'http//localhost:8012/health-care/';
</code>```

used this base url you getting this url

http://localhost:8012/health-care/index.php/home

Body:
i am getting this type of url when trying to access pages other than index page

http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home

but url to access page must be

http://localhost:8012/health-care/index.php/home

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

Body:
$config['base_url'] = 'http//localhost:8012/health-care/';

used this base url you getting this url

http://localhost:8012/health-care/index.php/home


问:
What does `tf.strided_slice()` do?
I am wondering what tf.strided_slice() operator actually does.

The doc says,

To a first order, this operation extracts a slice of size end - begin from a tensor input starting at the location specified by begin. The slice continues by adding stride to the begin index until all dimensions are not less than end. Note that components of stride can be negative, which causes a reverse slice.

And in the sample,

```<code># 'input' is [[[1, 1, 1], [2, 2, 2]],
#             [[3, 3, 3], [4, 4, 4]],
#             [[5, 5, 5], [6, 6, 6]]]
tf.slice(input, [1, 0, 0], [2, 1, 3], [1, 1, 1]) ==> [[[3, 3, 3]]]
tf.slice(input, [1, 0, 0], [2, 2, 3], [1, 1, 1]) ==> [[[3, 3, 3],
                                                       [4, 4, 4]]]
tf.slice(input, [1, 1, 0], [2, -1, 3], [1, -1, 1]) ==>[[[4, 4, 4],
                                                        [3, 3, 3]]]
</code>```

So in my understanding of the doc, the first sample (tf.slice(input, begin=[1, 0, 0], end=[2, 1, 3], strides=[1, 1, 1])),

resulting size is end - begin = [1, 1, 3]. The sample result shows [[[3, 3, 3,]]], that shape is [1, 1, 3], it seems OK.

the first element of the result is at begin = [1, 0, 0]. The first element of the sample result is 3, which is input[1,0,0], it seems OK.

the slice continues by adding stride to the begin index. So the second element of the result should be input[begin + strides] = input[2, 1, 1] = 6, but the sample shows the second element is 3.

What strided_slice() does?

(Note: method names in the samples and the last example is incorrect.)

答:
The conceptualization that really helped me understand this was that this function emulates the indexing behavior of numpy arrays.

If you're familiar with numpy arrays, you'll know that you can make slices via input[start1:end1:step1, start2:end2:step2, ... startN:endN:stepN]. Basically, a very succinct way of writing for loops to get certain elements of the array.

(If you're familiar with python indexing, you know that you can grab an array slice via input[start:end:step]. Numpy arrays, which may be nested, make use of the above tuple of slice objects.)

Well, strided_slice just allows you to do this fancy indexing without the syntactic sugar. The numpy example from above just becomes

```<code># input[start1:end1:step1, start2:end2:step2, ... startN:endN:stepN]
tf.strided_slice(input, [start1, start2, ..., startN],
    [end1, end2, ..., endN], [step1, step2, ..., stepN])
</code>```

The documentation is a bit confusing about this in the sense that:

a) begin - end is not strictly the shape of the return value:

The documentation claims otherwise, but this is only true if your strides are all ones.
Examples:

```<code>rank1 = tf.constant(list(range(10)))
# The below op is basically:
# rank1[1:10:2] => [1, 3, 5, 7, 9]
tf.strided_slice(rank1, [1], [10], [2])

# [10,10] grid of the numbers from 0 to 99
rank2 = tf.constant([[i+j*10 for i in range(10)] for j in range(10)])
# The below op is basically:
# rank2[3:7:1, 5:10:2] => numbers 30 - 69, ending in 5, 7, or 9
sliced = tf.strided_slice(rank2, [3, 5], [7, 10], [1, 2])
# The below op is basically:
# rank2[3:7:1] => numbers 30 - 69
sliced = tf.strided_slice(rank2, [3], [7], [1])
</code>```

b) it states that "begin, end, and strides will be all length n, where n is in general not the same dimensionality as input"

It sounds like dimensionality means rank here - but input does have to be a tensor of at least rank-n; it can't be lower (see rank-2 example above).

N.B. I've said nothing/not really explored the masking feature, but that seems beyond the scope of the question.

Title: What does `tf.strided_slice()` do?

Body:
I am wondering what tf.strided_slice() operator actually does.

The doc says,

To a first order, this operation extracts a slice of size end - begin from a tensor input starting at the location specified by begin. The slice continues by adding stride to the begin index until all dimensions are not less than end. Note that components of stride can be negative, which causes a reverse slice.

And in the sample,

# 'input' is [[[1, 1, 1], [2, 2, 2]],
#             [[3, 3, 3], [4, 4, 4]],
#             [[5, 5, 5], [6, 6, 6]]]
tf.slice(input, [1, 0, 0], [2, 1, 3], [1, 1, 1]) ==> [[[3, 3, 3]]]
tf.slice(input, [1, 0, 0], [2, 2, 3], [1, 1, 1]) ==> [[[3, 3, 3],
                                                       [4, 4, 4]]]
tf.slice(input, [1, 1, 0], [2, -1, 3], [1, -1, 1]) ==>[[[4, 4, 4],
                                                        [3, 3, 3]]]

So in my understanding of the doc, the first sample (tf.slice(input, begin=[1, 0, 0], end=[2, 1, 3], strides=[1, 1, 1])),

resulting size is end - begin = [1, 1, 3]. The sample result shows [[[3, 3, 3,]]], that shape is [1, 1, 3], it seems OK.

the first element of the result is at begin = [1, 0, 0]. The first element of the sample result is 3, which is input[1,0,0], it seems OK.

the slice continues by adding stride to the begin index. So the second element of the result should be input[begin + strides] = input[2, 1, 1] = 6, but the sample shows the second element is 3.

What strided_slice() does?

(Note: method names in the samples and the last example is incorrect.)

Body:
The conceptualization that really helped me understand this was that this function emulates the indexing behavior of numpy arrays.

If you're familiar with numpy arrays, you'll know that you can make slices via input[start1:end1:step1, start2:end2:step2, ... startN:endN:stepN]. Basically, a very succinct way of writing for loops to get certain elements of the array.

(If you're familiar with python indexing, you know that you can grab an array slice via input[start:end:step]. Numpy arrays, which may be nested, make use of the above tuple of slice objects.)

Well, strided_slice just allows you to do this fancy indexing without the syntactic sugar. The numpy example from above just becomes

# input[start1:end1:step1, start2:end2:step2, ... startN:endN:stepN]
tf.strided_slice(input, [start1, start2, ..., startN],
    [end1, end2, ..., endN], [step1, step2, ..., stepN])

The documentation is a bit confusing about this in the sense that:

a) begin - end is not strictly the shape of the return value:

The documentation claims otherwise, but this is only true if your strides are all ones.
Examples:

rank1 = tf.constant(list(range(10)))
# The below op is basically:
# rank1[1:10:2] => [1, 3, 5, 7, 9]
tf.strided_slice(rank1, [1], [10], [2])

# [10,10] grid of the numbers from 0 to 99
rank2 = tf.constant([[i+j*10 for i in range(10)] for j in range(10)])
# The below op is basically:
# rank2[3:7:1, 5:10:2] => numbers 30 - 69, ending in 5, 7, or 9
sliced = tf.strided_slice(rank2, [3, 5], [7, 10], [1, 2])
# The below op is basically:
# rank2[3:7:1] => numbers 30 - 69
sliced = tf.strided_slice(rank2, [3], [7], [1])

b) it states that "begin, end, and strides will be all length n, where n is in general not the same dimensionality as input"

It sounds like dimensionality means rank here - but input does have to be a tensor of at least rank-n; it can't be lower (see rank-2 example above).

N.B. I've said nothing/not really explored the masking feature, but that seems beyond the scope of the question.


问:
GWT - internationalization of entity properties
I'm looking for an elegant solution for the following problem:

In my database, I have some predefined(!) entities. These entities have names and descriptions (Strings). Around the data access layer, there are some EJBs containing business logic to load/search for/etc. those entities.

Now for the frontend, we are developing a GWT application which calls the EJB methods on our backend.

The problem is, that the name and the descriptions of the entities mentioned above must be internationalized - e.g., depending on the user's locale, an entity's description must be "My cool description" (English) or "Beschreibung bla" (German) or whatever :)

My first approach was to use a resource string in the database. So entity A has a description "descriptionA", entity B has a description "descriptionB"... Later on, the GWT app (or any other client) translates this resource string into the actual description using some kind of "resource bundle". E.g.:

*resources_en.properties*:

descriptionA=Actual Description of Entity A

descriptionB=Actual Description of Entity B

*resources_de.properties*:

descriptionA=Beschreibung A

descriptionB=Beschreibung B

(Remember, the entities are predefined, so it's possible to "know" all descriptions at compile time. BUT it would be better if the resource bundle could be enhanced without having to recompile the application).

Is this possible with GWT? How can I do this? Is it better to "translate" on the server or on the client side?

Otherwise, I've to deal with all that i18n stuff on the backend side. Well, this would allow to keep data together (instead of defining the descriptions on the client side). But the big drawback is that the backend must be aware of the caller's locale.

Regards,
Frank

答:
Everything is possible for those who try...

Back to your question: there are several ways to resolve your issue. One would be to introduce some kind of i18n facade and treat your descriptions and names as resource keys. Then you could define convenience methods to access translations i.e. public String translate(String message, Locale locale);. This method could use standard Java ResourceBundle class to access resources at runtime.

The only real problem I see is how to deal with compound messages (i.e. "Blah, blah 4 items" where 4 is a placeholder). Well, what we did in one project in similar situation, we added delimiter and actual resource key then another delimiter and count: "Blah, blah 4 items##items.in.your.whatever##4". In the case of English you could simply trim the first part and for other languages you would need to process whole string.


问:
How do I compare current time to a preset time in PHP?
I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,

```<code>$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
    $refresh = true;
}
</code>```

But the boolean doesn't change. Any idea what I did wrong?

答:
strtotime depends on the time zone.. so you should define timezone too.
You should set your default timezone before comparing.

http://php.net/strtotime

Example:

```<code>date_default_timezone_set('America/Los_Angeles');

$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
    $refresh = true;
}
</code>```

http://codepad.org/GC0VA7nw

Body:
I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,

$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
    $refresh = true;
}

But the boolean doesn't change. Any idea what I did wrong?

Body:
strtotime depends on the time zone.. so you should define timezone too.
You should set your default timezone before comparing.

http://php.net/strtotime

Example:

date_default_timezone_set('America/Los_Angeles');

$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
    $refresh = true;
}

http://codepad.org/GC0VA7nw