问:
How to avoid repeated code in python class
After much effort on python class now my code working as expected.

But I used below code in every place in my script:

```<code>        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
</code>```

Any one can please help me to avoid using above code multiple times,  in the below code

```<code>class Asr:
    def __init__(self):

        ''' SSH connection Establish '''
        self.hostname = hostname
        self.net_username = net_username
        self.net_password = net_password
    def remote(self):
        self.remote_conn_pre = paramiko.SSHClient()
        self.remote_conn_pre.set_missing_host_key_policy(
             paramiko.AutoAddPolicy())
        self.remote_conn_pre.connect(self.hostname, username=self.net_username, password=self.net_password, look_for_keys=False, allow_agent=False)
        self.remote_conn = self.remote_conn_pre.invoke_shell()
    def disable_paging(self):
        self.remote_conn.send("terminal length 0\n")
    def inventory(self):

        self.remote()
        self.remote_conn.send("\n")
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.close()
    def version(self):
        self.remote()
        self.remote_conn.send("\n")
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.disable_paging()
        self.remote_conn.send("show inventory\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.close()
asr = Asr()
asr.inventory()
asr.version()
</code>```

答:
Use a function same as above
Eg:

```<code>def check_buff(self, buff):

    while not buff.endswith('#'):
        resp = self.remote_conn.recv(9999)
        buff += resp
        print resp
</code>```

call the function and pass the buff parameter each time.
Eg:

```<code>buff = ''
self.check_buff(buff)
</code>```

Body:
After much effort on python class now my code working as expected.

But I used below code in every place in my script:

        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp

Any one can please help me to avoid using above code multiple times,  in the below code

class Asr:
    def __init__(self):

        ''' SSH connection Establish '''
        self.hostname = hostname
        self.net_username = net_username
        self.net_password = net_password
    def remote(self):
        self.remote_conn_pre = paramiko.SSHClient()
        self.remote_conn_pre.set_missing_host_key_policy(
             paramiko.AutoAddPolicy())
        self.remote_conn_pre.connect(self.hostname, username=self.net_username, password=self.net_password, look_for_keys=False, allow_agent=False)
        self.remote_conn = self.remote_conn_pre.invoke_shell()
    def disable_paging(self):
        self.remote_conn.send("terminal length 0\n")
    def inventory(self):

        self.remote()
        self.remote_conn.send("\n")
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.close()
    def version(self):
        self.remote()
        self.remote_conn.send("\n")
        self.remote_conn.send("ping 1.1.1.1\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.disable_paging()
        self.remote_conn.send("show inventory\n")
        buff = ''
        while not buff.endswith('#'):
            resp = self.remote_conn.recv(9999)
            buff += resp
            print resp
        self.remote_conn.close()
asr = Asr()
asr.inventory()
asr.version()

Body:
Use a function same as above
Eg:

def check_buff(self, buff):

    while not buff.endswith('#'):
        resp = self.remote_conn.recv(9999)
        buff += resp
        print resp

call the function and pass the buff parameter each time.
Eg:

buff = ''
self.check_buff(buff)


来源: stackexchange

问:
LINQ to NHibernate: could not resolve property
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

```<code>public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}
</code>```

However, when running this method:

```<code>public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }
</code>```

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

```<code>public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}
</code>```

...and my config:

```<code>public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }
</code>```

I also just tried the Criteria API:

```<code>return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();
</code>```

No workie either.

答:
Are you auto mapping this? Because I would suspect it's attempted to map YearOfEvent and MonthOfEvent, and it's trying to pull those columns from the database, but they don't exist.

If you're manually mapping them, then this wouldn't be an issue.

ContentLicense: CC BY-SA 2.5

Body:
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}

However, when running this method:

public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}

...and my config:

public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }

I also just tried the Criteria API:

return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();

No workie either.


问:
How to dynamically discover endpoint
I want to implement openid connect in my project. Right now I am hard coding the discovery url like for google - https://accounts.google.com/.well-known/openid-configuration , same for other source and then make this call and getting the endpoints for all the respective sources.
but I want to make it full dynamic. I found something on openid.net

```<code>GET /.well-known/webfinger
    ?resource=acct%3Ajoe%40example.com
    &rel=http%3A%2F%2Fopenid.net%2Fspecs%2Fconnect%2F1.0%2Fissuer
    HTTP/1.1
  Host: example.com

  HTTP/1.1 200 OK
  Content-Type: application/jrd+json

  {
   "subject": "acct:joe@example.com",
   "links":
    [
     {
      "rel": "http://openid.net/specs/connect/1.0/issuer",
      "href": "https://server.example.com"
     }
    ]
  }
</code>```

How can I do this call. What should I placed in resouces, rel ?? I am beginner in oauth process. Could you plz help me out.

答:
Strictly speaking Dynamic Registration is not necessarily coupled one-on-one with Discovery although typically it would be.

As the OP suggests, one can lookup the Provider's metadata through applying Webfinger Discovery as described in: http://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery

The request and response would look as already presented in the question i.e. : http://openid.net/specs/openid-connect-discovery-1_0.html#URLSyntax The RP can parse the "hreft" value from the response that would present the "issuer" value (i.e. a unique DNS bound identifier for the Provider) and then construct the well-known endpoint where the Provider's configuration metadata can be retrieved from as described here: http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig

Assuming that the RP already has a client_id/client_secret established with that Provider in a previous out-of-bound step, this may avoid the RP having to store and/or cache the Provider's metadata.

ContentLicense: CC BY-SA 3.0

Title: How to dynamically discover endpoint

Body:
I want to implement openid connect in my project. Right now I am hard coding the discovery url like for google - https://accounts.google.com/.well-known/openid-configuration , same for other source and then make this call and getting the endpoints for all the respective sources.
but I want to make it full dynamic. I found something on openid.net

GET /.well-known/webfinger
    ?resource=acct%3Ajoe%40example.com
    &rel=http%3A%2F%2Fopenid.net%2Fspecs%2Fconnect%2F1.0%2Fissuer
    HTTP/1.1
  Host: example.com

  HTTP/1.1 200 OK
  Content-Type: application/jrd+json

  {
   "subject": "acct:joe@example.com",
   "links":
    [
     {
      "rel": "http://openid.net/specs/connect/1.0/issuer",
      "href": "https://server.example.com"
     }
    ]
  }

How can I do this call. What should I placed in resouces, rel ?? I am beginner in oauth process. Could you plz help me out.


问:
How to avoid packaging useless classes
I am working on a Intellij plugin and is my first attempt on Java language to build a "real project". On this plugin I have created a lot of classes (and enums) and, after refactoring the code, I ended up getting to the point where some classes I have created were no longer in use (except for unit tests, that is not packaged together on final package).

My question is: if a class are not need on package anymore, there is some way to it not be package without remove it from project? (Once that I could, futurely, need of this class again.)

Real example:

Finding by usage of UserDataHolderUtil enum on the project:

The .jar contents:

You can note that this enum is used currently only for unit tests, but it is packaged into final package and never is used.

答:
I would create a new module under the same project in IntelliJ IDEA and move all unused types to the new module.

This way, the package hierarchy of the types is retained, and the types remain in the same project, which means that they are included in any refactoring that you might do.

You make the "unused" module depend on the main module of the project, but of course no other module depends on it, so you do not have to include it in the final package.

Title: How to avoid packaging useless classes


问:
upload picture in database using android studio
```<code><?php ## Heading ##
  require_once 'include/db_connection.php';
  global $connection; $upload_path = 'uploads/';

  //this is our upload folder
  $server_ip = gethostbyname(gethostname());

  //Getting the server ip
  $upload_url = 'http://'.$server_ip.'/android_upload/'.$upload_path;

  //upload url
  //response array
  $response = array();
  if($_SERVER['REQUEST_METHOD']=='POST'){
    //checking the required parameters from the request
    if(isset($_POST['caption'])) {
      $caption = $_POST['caption'];
      $fileinfo = pathinfo($_FILES['image']['name']);
      //getting file info from the request
      $extension = $fileinfo['extension'];
      //getting the file extension
      $file_url = $upload_url . getFileName() . '.' . $extension;
      //file url to store in the database
      $file_path = $upload_path . getFileName() . '.'. $extension;
      //file path to upload in the server
      $img_name = getFileName() . '.'. $extension;

      //file name to store in the database
      try{
          move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
          //saving the file to the uploads folder;
          //adding the path and name to database
          $sql = "INSERT INTO photos(photo_name, photo_url, caption) ";
          $sql .= "VALUES ('{$img_name}', '{$file_url}', '{$caption}');";

          if(mysqli_query($connection,$sql)){
            //filling response array with values
            $response['error'] = false;
            $response['photo_name'] = $img_name;
            $response['photo_url'] = $file_url;
            $response['caption'] = $caption;
          }
          //if some error occurred
       }catch(Exception $e){
      $response['error']=true;
      $response['message']=$e->getMessage();
    }
    //displaying the response
    echo json_encode($response);
    //closing the connection
    mysqli_close($connection);
  }else{ $response['error'] = true;
        $response['message']='Please choose a file';
       }
 }
 /* We are generating the file name so this method will return a file name
 for the image to be uploaded */
  function getFileName(){
    global $connection;
    $sql = "SELECT max(id) as id FROM photos";
    $result = mysqli_fetch_array(mysqli_query($connection, $sql));
    if($result['id']== null) return 1;
    else return ++$result['id'];
    mysqli_close($connection);
  }
?>
</code>```

答:
Here is picture  upload code and get response  image url save your database. u hope you try this.</p>

```<code><?php
include('confi.php');
/**********MYSQL Settings****************/
function GetImageExtension($imagetype)
     {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
           case 'image/png': return '.png';
           default: return false;
       }
     }
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (isset($_FILES["file"]["name"])) {
    $file_name=$_FILES["file"]["name"];
    $temp_name=$_FILES["file"]["tmp_name"];
    $imgtype=$_FILES["file"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("m-Y")."-".rand().$_FILES['file']['name'];
    $target_path ='images/'.$imagename;
    if(move_uploaded_file($temp_name, $target_path)) {
    $result = $url.'api/'.$target_path;
    $json = array( "status" =>1,"file-url" => $result, "files" => $_FILES);
}else{
    if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
           $json = array( "status" =>0, "error" => $_FILES['uploaded']);
        }
        else{
        $json = array( "status" =>0,"files" => $_FILES);
        }
}
}
else{
   $json = array("status" =>0, "error" => "Problem occurred");
}
}else{
        $json = array("status" => 0, "message" => "Request method is wrong!");
     }

    header('Content-type:application/json');
    echo json_encode($json);
?>
</code>```

Body:
Here is picture  upload code and get response  image url save your database. u hope you try this.

<?php
include('confi.php');
/**********MYSQL Settings****************/
function GetImageExtension($imagetype)
     {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
           case 'image/png': return '.png';
           default: return false;
       }
     }
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (isset($_FILES["file"]["name"])) {
    $file_name=$_FILES["file"]["name"];
    $temp_name=$_FILES["file"]["tmp_name"];
    $imgtype=$_FILES["file"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("m-Y")."-".rand().$_FILES['file']['name'];
    $target_path ='images/'.$imagename;
    if(move_uploaded_file($temp_name, $target_path)) {
    $result = $url.'api/'.$target_path;
    $json = array( "status" =>1,"file-url" => $result, "files" => $_FILES);
}else{
    if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
           $json = array( "status" =>0, "error" => $_FILES['uploaded']);
        }
        else{
        $json = array( "status" =>0,"files" => $_FILES);
        }
}
}
else{
   $json = array("status" =>0, "error" => "Problem occurred");
}
}else{
        $json = array("status" => 0, "message" => "Request method is wrong!");
     }

    header('Content-type:application/json');
    echo json_encode($json);
?>


问:
How to change one array's values from another array?
```<code>String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];
</code>```

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

```<code>board[0]="X";
board[1]="X";
board[2]="O";
</code>```

I am trying to run this for loop and I have to initialize the board array  before the sequences part as I am printing it out to the screen and can't have the values be null.

```<code>for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}
</code>```

答:
You can use String::split which return an array of String for example :

```<code>String[] board;//you could also to not initialize the array here
               //because you will do that in split
String[] sequence = new String[8];
sequence[0] = "XXO";
board = sequence[0].split("");//split and initialize the board array

//print the values
System.out.println(board[0]);
System.out.println(board[1]);
System.out.println(board[2]);
</code>```

Output

```<code>X
X
O
</code>```

Body:
String [] board = new String [9];
String [] sequence = new String [8];

sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];

Say I was to make sequence[0]="XXO";

How could I take sequence[0] and change the the board points so that:

board[0]="X";
board[1]="X";
board[2]="O";

I am trying to run this for loop and I have to initialize the board array  before the sequences part as I am printing it out to the screen and can't have the values be null.

for(int i = 0; i < 8; i++
{
    if(sequence[i].equals("X"+"X"+" "))
    {
        sequence[i] = "XXO";
    }
}

Body:
You can use String::split which return an array of String for example :

String[] board;//you could also to not initialize the array here
               //because you will do that in split
String[] sequence = new String[8];
sequence[0] = "XXO";
board = sequence[0].split("");//split and initialize the board array

//print the values
System.out.println(board[0]);
System.out.println(board[1]);
System.out.println(board[2]);

Output

X
X
O


问:
I have 10 nodes .. each node has known number of transceivers .. I want to know How can I obtain all possible connections between nodes ? using MATLAB
I have 10 nodes .. each node has known number of transceivers as indicated in this vector:

```<code>[8 3 3 3 3 3 2 1 1 1]
</code>```

where: 8 is the number of transceivers at the 1st node, 3 is the number of transceivers at the 2nd node and so on ..

Each transceiver can only receive from one source at a time .. it is required that all transceivers must be in use simultaneously .. it is permitted for the same node to use more than one transceiver to transmit to another node that has enough transceivers to receive with .. it is not possible for a single transceiver to be considered to be transmitting to multiple transceivers ..

I want to know How can I obtain all possible connections between nodes and each obtained connection matrix identify the number of transceivers used between the connected nodes ?

答:
I don't know how to do this in Matlab.

With Minizinc, I found the following solution (slightly massaged with Microsoft Word):

Note that I used node number 0..9 rather than 1..10 to compact the matrix text.
There is a huge number of possible solutions. This is just one of them.

The Minizinc script:

```<code>include "globals.mzn";

set of int: Transceivers = 1..28;
set of int: Nodes = 1..10;

array[Transceivers] of Nodes: node = [1,1,1,1,1,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,8,9,10];
array[Transceivers] of Nodes: seq  = [1,2,3,4,5,6,7,8,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,1,1,1];

array[Transceivers] of var Transceivers: aTo;

array[Nodes, Nodes] of var Transceivers: connections;

% Each transceiver can only receive from one source at a time
constraint all_different([aTo[t] | t in Transceivers]);

% transceivers have to connect to other nodes rather than to their own node
constraint
  forall(t in Transceivers)
    (node[aTo[t]] != node[t]);

% no more than 1 connection between any pair of nodes
constraint
  forall(i in Nodes, j in Nodes where j > i)
    (sum([bool2int((node[t] == i) /\ (node[aTo[t]] == j)) | t in Transceivers]) < 2);

solve satisfy;

output ["     "] ++ [ show(node[i]-1) ++ "." ++ show(seq[i]) ++ " | " | i in Transceivers] ++
       [ if j == 1 then ("\n" ++ show(node[i]-1) ++ "." ++ show(seq[i]) ++ ": ") else "" endif ++
         if fix(aTo[i]) == j then " x  | " else "    | " endif
        | i in Transceivers, j in Transceivers ];
</code>```

Body:
I have 10 nodes .. each node has known number of transceivers as indicated in this vector:

[8 3 3 3 3 3 2 1 1 1]

where: 8 is the number of transceivers at the 1st node, 3 is the number of transceivers at the 2nd node and so on ..

Each transceiver can only receive from one source at a time .. it is required that all transceivers must be in use simultaneously .. it is permitted for the same node to use more than one transceiver to transmit to another node that has enough transceivers to receive with .. it is not possible for a single transceiver to be considered to be transmitting to multiple transceivers ..

I want to know How can I obtain all possible connections between nodes and each obtained connection matrix identify the number of transceivers used between the connected nodes ?

Body:
I don't know how to do this in Matlab.

With Minizinc, I found the following solution (slightly massaged with Microsoft Word):

Note that I used node number 0..9 rather than 1..10 to compact the matrix text.
There is a huge number of possible solutions. This is just one of them.

The Minizinc script:

include "globals.mzn";

set of int: Transceivers = 1..28;
set of int: Nodes = 1..10;

array[Transceivers] of Nodes: node = [1,1,1,1,1,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,8,9,10];
array[Transceivers] of Nodes: seq  = [1,2,3,4,5,6,7,8,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,1,1,1];

array[Transceivers] of var Transceivers: aTo;

array[Nodes, Nodes] of var Transceivers: connections;

% Each transceiver can only receive from one source at a time
constraint all_different([aTo[t] | t in Transceivers]);

% transceivers have to connect to other nodes rather than to their own node
constraint
  forall(t in Transceivers)
    (node[aTo[t]] != node[t]);

% no more than 1 connection between any pair of nodes
constraint
  forall(i in Nodes, j in Nodes where j > i)
    (sum([bool2int((node[t] == i) /\ (node[aTo[t]] == j)) | t in Transceivers]) < 2);

solve satisfy;

output ["     "] ++ [ show(node[i]-1) ++ "." ++ show(seq[i]) ++ " | " | i in Transceivers] ++
       [ if j == 1 then ("\n" ++ show(node[i]-1) ++ "." ++ show(seq[i]) ++ ": ") else "" endif ++
         if fix(aTo[i]) == j then " x  | " else "    | " endif
        | i in Transceivers, j in Transceivers ];


问:
How to set stickerSize in MSStickerBrowserViewController
When I create a MSStickerBrowserViewController subclass by embedding it in a container view (using a storyboard) as the documentation suggests, I appear to have no opportunity to set the stickerSize. The Sticker Browser VC is initialized with init(coder:), and I have no way that I can see to override the get-only property stickerSize. I can only get stickerSize = MSStickerSize.regular.

I don't see any control in interface builder to configure the property either, though the documentation says "You can also customize the size of the stickers inside the browser."

Thanks to shallowThought, I see that an initializer is available init(stickerSize: MSStickerSize) on MSStickerBrowserViewController, but so far I have been unable to find a way to trigger that initializer when using a storyboard and overriding the required init(coder:) initializer.

Am i missing something?

Thanks!

答:
This worked for me: I added stickerSize to the "User Defined Runtime Attributes" section of the Identity Inspector.

In this example, PetStickerBrowserViewController is a subclass of MSBrowserStickerViewController. stickerSize is set to 0, which corresponds to MSStickerSize.small.

At runtime, when the view controller is instantiated from the storyboard, its stickerSize property is set to .small. Use 1 for .regular (the default), and 2 for .large.


问:
cf.net app protection (antidebug, obfuscate)
Is there any out-of-the box solution that protects cf.net (3.5) software against reverse engineering and unlicensed redistribution (average hacker protection)? Any option of packer/native wrapper?

答: All the above solutions will work for you but if you want something cost effective, you can try http://www.eziriz.com/ - .NET reactor. I have used the trial version and it is as effective as preemptive and remotesoft salamander but for a much lower cost - it is only $179 for a single developer license and $279 for a company license - more details here - http://www.eziriz.com/order.htm</p>


问:
UICollectionView, full width cells, allow autolayout dynamic height?
Note For 2021!  See @Ely answer regarding UICollectionLayoutListConfiguration !!!!

In a vertical UICollectionView ,

Is it possible to have full-width cells, but, allow the dynamic height to be controlled by autolayout?

This strikes me as perhaps the "most important question in iOS with no really good answer."

Important:

Note that in 99% of cases, to achieve full width cells + autolayout dynamic height, simply use a table view. It's that easy.

So what's an example of where you need a collection view?

Collection views are far more powerful than table views.

One straightforward example where you must use a collection view with autolayout dynamic height:

If you animate between two layouts in a collection view. For example, between a 1 and 2 column layout, when the device rotates.

That's a common idiom in iOS. Unfortunately it can only be achieved by solving the problem posed in this QA.  :-/

答:
From iOS 10, we've got new API on flow layout to do that.

All you have to do is set your flowLayout.estimatedItemSize to a new constant, UICollectionViewFlowLayoutAutomaticSize.

Source

ContentLicense: CC BY-SA 4.0


问:
retrieve file information from url using php
i am trying to retrieve information of file from the url containing the file. but how can i get the information of file before downloading it to my server.
i need file information like file size,file type  etc

i had found the code to validate and download file but how to get information from it before downloading file actually to server

```<code><?php
function is_url_exist($url)
    {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($code == 200)
        {
        $status = "true";
        }
    curl_close($ch);
    if ( $status == true)
        {
        $name = "abc.png";
        if (file_put_contents("uploads/$name", file_get_contents($url)))
            echo "file uploaded";
        else
            echo "error check upload link";
        }
    }
$url = "http://theonlytutorials.com/wp-content/uploads/2015/06/blog-logo1.png";
echo is_url_exist($url);
?>
</code>```

答:
you can get all information of remote file by get_headers function. Try following code to find out type, content length etc.

```<code>$url = "http://theonlytutorials.com/wp-content/uploads/2015/06/blog-logo1.png";
$headers = get_headers($url,1);
print_r($headers);
</code>```

Know more about get_headers click http://php.net/manual/en/function.get-headers.php

Body:
i am trying to retrieve information of file from the url containing the file. but how can i get the information of file before downloading it to my server.
i need file information like file size,file type  etc

i had found the code to validate and download file but how to get information from it before downloading file actually to server

<?php
function is_url_exist($url)
    {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($code == 200)
        {
        $status = "true";
        }
    curl_close($ch);
    if ( $status == true)
        {
        $name = "abc.png";
        if (file_put_contents("uploads/$name", file_get_contents($url)))
            echo "file uploaded";
        else
            echo "error check upload link";
        }
    }
$url = "http://theonlytutorials.com/wp-content/uploads/2015/06/blog-logo1.png";
echo is_url_exist($url);
?>

Body:
you can get all information of remote file by get_headers function. Try following code to find out type, content length etc.

$url = "http://theonlytutorials.com/wp-content/uploads/2015/06/blog-logo1.png";
$headers = get_headers($url,1);
print_r($headers);

Know more about get_headers click http://php.net/manual/en/function.get-headers.php


问:
Angular JS manipulating dom by element from link function
we know that we can access dom from directive by element because element is injected in link function.

see the approach

```<code>var app = angular.module("myApp", []);

app.directive('busyBox',function(){
     return  {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.on('click', function(){
            if(attrs.id=='btnadd')
            {

              var divElement = angular.element(document.body.querySelector('.parent')).append('<div class="child">Some text</div>');
        //     console.log(divElement);
             //  element.parent().find('.parent').append('<div>Some text</div>')
                //element.closest('.parent').append('<div class="child">child</div>')
              //angular.element(document).find('.parent').append('<div class="child">child</div>');
            }
            else if(attrs.id=='btnDel')
            {
            angular.element(document.body.querySelector('.child')).remove();
           //    m.removeChild(m.firstChild);
            }
          });

        }
        }
})
</code>```

the above code is working but if i do not use angular.element() instead if i use element(document.body.querySelector('.parent')) the code is not working.

the element is injected in link function link: function(scope, element, attrs)
when element is there in directive then why should i use angular.element() ?

please tell me how could i use element from directive to access dom instead of angular.element().

thanks

答:
please tell me how could i use element from directive to access dom instead of angular.element()

If you want to use the element object that is passed into the link function of the directive to manipulate the DOM, you have to use various methods that the element object exposes, like find.

Do not use it like this:

```<code>element(document.body.querySelector('.parent'))
</code>```

Instead you can do:

```<code>// works only if you are using jQuery
element.find('.parent');
// for JQLite, the find method is limited to lookup by tag name:
element.find('div');
</code>```

Note that as mentioned in the answer from @georgeawg, that you might be using JQLite or JQuery ... where the JQLite functionality is not as full featured as JQuery.

Body:
we know that we can access dom from directive by element because element is injected in link function.

see the approach

var app = angular.module("myApp", []);

app.directive('busyBox',function(){
     return  {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.on('click', function(){
            if(attrs.id=='btnadd')
            {

              var divElement = angular.element(document.body.querySelector('.parent')).append('
Some text
');
        //     console.log(divElement);
             //  element.parent().find('.parent').append('
Some text
')
                //element.closest('.parent').append('
child
')
              //angular.element(document).find('.parent').append('
child
');
            }
            else if(attrs.id=='btnDel')
            {
            angular.element(document.body.querySelector('.child')).remove();
           //    m.removeChild(m.firstChild);
            }
          });

        }
        }
})

the above code is working but if i do not use angular.element() instead if i use element(document.body.querySelector('.parent')) the code is not working.

the element is injected in link function link: function(scope, element, attrs)
when element is there in directive then why should i use angular.element() ?

please tell me how could i use element from directive to access dom instead of angular.element().

thanks

Body:
please tell me how could i use element from directive to access dom instead of angular.element()

If you want to use the element object that is passed into the link function of the directive to manipulate the DOM, you have to use various methods that the element object exposes, like find.

Do not use it like this:

element(document.body.querySelector('.parent'))

Instead you can do:

// works only if you are using jQuery
element.find('.parent');
// for JQLite, the find method is limited to lookup by tag name:
element.find('div');

Note that as mentioned in the answer from @georgeawg, that you might be using JQLite or JQuery ... where the JQLite functionality is not as full featured as JQuery.


问:
Tensorflow session and graph context
My question is about context and the TensorFlow default sessions and graph.

The problem:
Tensorflow is unable to feed a placeholder in the following scenario:
Function Test defines a graph.
Function Test_Once defines a session.
When Function Test calls Test_Once -> Feeding fails.
When I change the code so function Test declares the graph + the session -> all is working.

Here is the code:

```<code>def test_once(g, saver, summary_writer, logits, images, summary_op):
  """Run a session once for a givven test image.

  Args:
    saver: Saver.
    summary_writer: Summary writer.
    logits:
    summary_op: Summary op.
  """
  with tf.Session(graph=g) as sess:
    ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
      # Restores from checkpoint
      saver.restore(sess, ckpt.model_checkpoint_path)

      # extract global_step from it.
      global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    else:
      print('No checkpoint file found')
      return

    images.astype(np.float32)

    predictions = sess.run(logits, feed_dict={'InputPlaceHolder/TestInput:0':images})

    summary = tf.Summary()
    summary.ParseFromString(sess.run(summary_op))
    summary_writer.add_summary(summary, global_step)

    return (predictions)

def test():
  """Test LCPR with a test image"""
  with tf.Graph().as_default() as g:

    # Get image for testing
    images, labels = lcpr.test_input()

    # Build a Graph that computes the logits predictions from the
    # inference model.
    with tf.name_scope('InputPlaceHolder'):

        test_image_placeholder = tf.placeholder(tf.float32, (None,None,None,3), 'TestInput')
        # Display the training images in the visualizer.
        # The 'max_outputs' default is 3. Not stated. (Max number of batch elements to generate images for.)
        #tf.summary.image('input_images', test_image_placeholder)

    with tf.name_scope('Inference'):
        logits = lcpr.inference(test_image_placeholder)

    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(
        lcpr.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()
    saver = tf.train.Saver(variables_to_restore)

    # Build the summary operation based on the TF collection of Summaries.
    writer = tf.summary.FileWriter("/tmp/lcpr/test")
    writer.add_graph(g)

    summary_op = tf.summary.merge_all()
    summary_writer = tf.summary.FileWriter(FLAGS.test_dir, g)

    #Sadly, this will not work:
    predictions = test_once(g, saver, summary_writer, logits, images, summary_op)

    '''Alternative working option :
    with tf.Session() as sess:
        ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
        if ckpt and ckpt.model_checkpoint_path:
          # Restores from checkpoint
          saver.restore(sess, ckpt.model_checkpoint_path)
          # Assuming model_checkpoint_path looks something like:
          #   /my-favorite-path/cifar10_train/model.ckpt-0,
          # extract global_step from it.
          global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
        else:
          print('No checkpoint file found')
          return

        x = sess.run(logits, feed_dict={'InputPlaceHolder/TestInput:0':images})
        print(x)
    '''
</code>```

The above code yeilds an error that the placeholder is not fed:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'InputPlaceHolder/TestInput' with dtype float

And it's not that TensorFlow does not recognize the placeholder. If I change the name from 'InputPlaceHolder/TestInput:0' to 'InputPlaceHolder/TestInput:1' I receive a message calming that 'InputPlaceHolder/TestInput' exists but has only 1 output. This makes sense, and I guess the session runs on my default graph.

Things only work for me if I stay within the same def:
If I change the code by running the commented part (starting  ' with tf.Session() as sess:) directly from within the first function all works.

I wonder what am I missing?
My guess that is context related, maybe not assigning the session to the graph?

答:
Solved. Stupid mistake
test_once calls sess.run twice. On the second time, indeed no placeholder is fed.... : summary.ParseFromString(sess.run(summary_op))</p>

Title: Tensorflow session and graph context

Body:
My question is about context and the TensorFlow default sessions and graph.

The problem:
Tensorflow is unable to feed a placeholder in the following scenario:
Function Test defines a graph.
Function Test_Once defines a session.
When Function Test calls Test_Once -> Feeding fails.
When I change the code so function Test declares the graph + the session -> all is working.

Here is the code:

def test_once(g, saver, summary_writer, logits, images, summary_op):
  """Run a session once for a givven test image.

  Args:
    saver: Saver.
    summary_writer: Summary writer.
    logits:
    summary_op: Summary op.
  """
  with tf.Session(graph=g) as sess:
    ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
      # Restores from checkpoint
      saver.restore(sess, ckpt.model_checkpoint_path)

      # extract global_step from it.
      global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    else:
      print('No checkpoint file found')
      return

    images.astype(np.float32)

    predictions = sess.run(logits, feed_dict={'InputPlaceHolder/TestInput:0':images})

    summary = tf.Summary()
    summary.ParseFromString(sess.run(summary_op))
    summary_writer.add_summary(summary, global_step)

    return (predictions)

def test():
  """Test LCPR with a test image"""
  with tf.Graph().as_default() as g:

    # Get image for testing
    images, labels = lcpr.test_input()

    # Build a Graph that computes the logits predictions from the
    # inference model.
    with tf.name_scope('InputPlaceHolder'):

        test_image_placeholder = tf.placeholder(tf.float32, (None,None,None,3), 'TestInput')
        # Display the training images in the visualizer.
        # The 'max_outputs' default is 3. Not stated. (Max number of batch elements to generate images for.)
        #tf.summary.image('input_images', test_image_placeholder)

    with tf.name_scope('Inference'):
        logits = lcpr.inference(test_image_placeholder)

    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(
        lcpr.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()
    saver = tf.train.Saver(variables_to_restore)

    # Build the summary operation based on the TF collection of Summaries.
    writer = tf.summary.FileWriter("/tmp/lcpr/test")
    writer.add_graph(g)

    summary_op = tf.summary.merge_all()
    summary_writer = tf.summary.FileWriter(FLAGS.test_dir, g)

    #Sadly, this will not work:
    predictions = test_once(g, saver, summary_writer, logits, images, summary_op)

    '''Alternative working option :
    with tf.Session() as sess:
        ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
        if ckpt and ckpt.model_checkpoint_path:
          # Restores from checkpoint
          saver.restore(sess, ckpt.model_checkpoint_path)
          # Assuming model_checkpoint_path looks something like:
          #   /my-favorite-path/cifar10_train/model.ckpt-0,
          # extract global_step from it.
          global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
        else:
          print('No checkpoint file found')
          return

        x = sess.run(logits, feed_dict={'InputPlaceHolder/TestInput:0':images})
        print(x)
    '''

The above code yeilds an error that the placeholder is not fed:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'InputPlaceHolder/TestInput' with dtype float

And it's not that TensorFlow does not recognize the placeholder. If I change the name from 'InputPlaceHolder/TestInput:0' to 'InputPlaceHolder/TestInput:1' I receive a message calming that 'InputPlaceHolder/TestInput' exists but has only 1 output. This makes sense, and I guess the session runs on my default graph.

Things only work for me if I stay within the same def:
If I change the code by running the commented part (starting  ' with tf.Session() as sess:) directly from within the first function all works.

I wonder what am I missing?
My guess that is context related, maybe not assigning the session to the graph?


问:
Why this SQL query does not work?
I wrote this query but I get the following error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'BEGIN INSERT
  INTO forum_topics_track (userid, topic_id, `c' at line 3

I guess it is self explanatory but my goal is to check if the record exists and if it doesn't, to insert it.

```<code>IF NOT EXISTS
                (SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}')
            BEGIN
                INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
                VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
            END;
</code>```

答:
IF NOT EXISTS is a clause that is available to use in MS-SQL but not in MySQL. Please try following query.</p>

```<code>INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
SELECT '{$topic_id}', '{$category_id}', '{$userid}'
WHERE NOT EXISTS(
    SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}'
)
</code>```

Title: Why this SQL query does not work?

Body:
I wrote this query but I get the following error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'BEGIN INSERT
  INTO forum_topics_track (userid, topic_id, `c' at line 3

I guess it is self explanatory but my goal is to check if the record exists and if it doesn't, to insert it.

IF NOT EXISTS
                (SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}')
            BEGIN
                INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
                VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
            END;

Body:
IF NOT EXISTS is a clause that is available to use in MS-SQL but not in MySQL. Please try following query.

INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
SELECT '{$topic_id}', '{$category_id}', '{$userid}'
WHERE NOT EXISTS(
    SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}'
)


问:
Python Youtube API Client Warnings

TLDR, using google-api-python-client, it's giving me a couple of warnings,

```<code>WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ModuleNotFoundError: No module named 'google'
</code>```

And I want to hide them. How do I hide them?

Details

I'm using google-api-python-client==1.6.2 to perform searching using YouTube data API. I don't need OAuth in this case, so I've not installed anything besides google-api-python-client.

When I run my code, I get a long WARNING with a couple of Tracebacks. My application is still running as I can still use curl to hit the server and I get a result.

```<code>WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ModuleNotFoundError: No module named 'google'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0
</code>```

Here's my code,

my_package/main.py

```<code>from my_package.server import app

HOST = 'localhost'
PORT = 8100
app.run(HOST, PORT)
</code>```

my_package/server.py

```<code>from flask import Flask, request
from flask_restful import Resource, Api
from logging import info
from my_package.youtube import YouTube

app = Flask(__name__)
api = Api(app)

yt_client = YouTube()

class Search(Resource):
    def get(self, query):
        info("Handling `get` request for the resource 'Search'.")
        return yt_client.search(query)

api.add_resource(Search, '/search/<string:query>')

if __name__ == '__main__':
    info('Application starting.')
    app.run(debug=True)
</code>```

my_package/youtube.py

```<code>from logging import info
import apiclient as google

class YouTube:
    MAX_RESULTS = 25

    def __init__(self):
        info('Creating a YouTube API instance.')
        self.API_KEY = 'MY_API_KEY'
        self.youtube = google.discovery.build('youtube', 'v3',
                                              developerKey=self.API_KEY)

    def search(self, query):
        info(f"Performing a search for '{query}'")
        results = self.youtube.search().list(
            q=query,
            part='snippet',
            maxResults=self.MAX_RESULTS
        ).execute()

        return results.get('items', [])
</code>```

Here's my requirements.txt

```<code>aniso8601==1.2.1
certifi==2017.4.17
chardet==3.0.3
click==6.7
Flask==0.12.2
Flask-RESTful==0.3.6
google-api-python-client==1.6.2
httplib2==0.10.3
idna==2.5
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
oauth2client==4.1.0
pyasn1==0.2.3
pyasn1-modules==0.0.9
python-dateutil==2.6.0
pytz==2017.2
requests==2.17.3
rsa==3.4.2
six==1.10.0
uritemplate==3.0.0
urllib3==1.21.1
Werkzeug==0.12.2
</code>```

答:
Set the cache_discovery parameter in your build call to False.

```<code>google.discovery.build('youtube','v3',developerKey=self.API_KEY,
                       cache_discovery=False)
</code>```

That will prevent the import of the cache.discovery module which is what is logging the warning.

Title: Python Youtube API Client Warnings

Body:
TLDR, using google-api-python-client, it's giving me a couple of warnings,

WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ModuleNotFoundError: No module named 'google'

And I want to hide them. How do I hide them?

Details

I'm using google-api-python-client==1.6.2 to perform searching using YouTube data API. I don't need OAuth in this case, so I've not installed anything besides google-api-python-client.

When I run my code, I get a long WARNING with a couple of Tracebacks. My application is still running as I can still use curl to hit the server and I get a result.

WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ModuleNotFoundError: No module named 'google'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/home/user/.virtualenvs/tmp/lib/python3.6/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0

Here's my code,

my_package/main.py

from my_package.server import app

HOST = 'localhost'
PORT = 8100
app.run(HOST, PORT)

my_package/server.py

from flask import Flask, request
from flask_restful import Resource, Api
from logging import info
from my_package.youtube import YouTube

app = Flask(__name__)
api = Api(app)

yt_client = YouTube()

class Search(Resource):
    def get(self, query):
        info("Handling `get` request for the resource 'Search'.")
        return yt_client.search(query)

api.add_resource(Search, '/search/<string:query>')

if __name__ == '__main__':
    info('Application starting.')
    app.run(debug=True)

my_package/youtube.py

from logging import info
import apiclient as google

class YouTube:
    MAX_RESULTS = 25

    def __init__(self):
        info('Creating a YouTube API instance.')
        self.API_KEY = 'MY_API_KEY'
        self.youtube = google.discovery.build('youtube', 'v3',
                                              developerKey=self.API_KEY)

    def search(self, query):
        info(f"Performing a search for '{query}'")
        results = self.youtube.search().list(
            q=query,
            part='snippet',
            maxResults=self.MAX_RESULTS
        ).execute()

        return results.get('items', [])

Here's my requirements.txt

aniso8601==1.2.1
certifi==2017.4.17
chardet==3.0.3
click==6.7
Flask==0.12.2
Flask-RESTful==0.3.6
google-api-python-client==1.6.2
httplib2==0.10.3
idna==2.5
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
oauth2client==4.1.0
pyasn1==0.2.3
pyasn1-modules==0.0.9
python-dateutil==2.6.0
pytz==2017.2
requests==2.17.3
rsa==3.4.2
six==1.10.0
uritemplate==3.0.0
urllib3==1.21.1
Werkzeug==0.12.2

Body:
Set the cache_discovery parameter in your build call to False.

google.discovery.build('youtube','v3',developerKey=self.API_KEY,
                       cache_discovery=False)

That will prevent the import of the cache.discovery module which is what is logging the warning.


问:
How do I use JAXB annotations with Spring RestTemplate?
I'm trying to automatically deserialize XML formatted response using Spring's RestTemplate. I'm using Jackson's jackson-dataformat-xml module, for which Spring Boot is set to auto-configure. I want to use JAXB annotations in the class I want to deserialize to, but it won't seem to work. Here's a sample of what I want the class to look like:

```<code>@XmlRootElement(name="Book")
public class Book {

    @XmlElement(name="Title")
    private String title;
    @XmlElement(name="Author")
    private String author;

}
</code>```

This is based on the following XML sample:

```<code><Book>
    <Title>My Book</Title>
    <Author>Me</Author>
</Book>
</code>```

However, with class annotated like that above, the fields are always set null. I did some experiments and found out that the deserialization works if I use Jackson's @JsonProperty to annotate the child elements:

```<code>@XmlRootElement(name="Book")
public class Book {

    @JsonProperty("Title")
    private String title;
    @JsonProperty("Author")
    private String author;

}
</code>```

It works, but somehow I feel like it's kind of awkward. Is there a way to get the JAXB annotations work like in my first example?

Jackson provides jackson-module-jaxb-annotations module for the XML databinding to work with JAXB annotations. However, I'm not sure how to setup the ObjectMapper being used by RestTemplate to use this module.

答:
To address this issue, I needed to register an instance of JaxbAnnotationModule to every ObjectMapper used by converters added to Spring's RestTemplate. The class is included in Jackson's jackson-module-jaxb-annotations module, which I added to my build through Gradle.

With the dependency added to my project, what I did next was to configure the RestTemplate used by my application. The ObjectMapper instances are being used by MappingJackson2XmlHttpMessageConverters configured automatically by Spring. I had to register JaxbAnnotationModule instance to each ObjectMapper used in every converter, so the first task was to find all MappingJackson2XmlHttpMessageConverters using:

```<code>//create module
JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();

restTemplate.getMessageConverters().stream().filter(converter -> {
    return converter instanceof MappingJackson2XmlHttpMessageConverter;
})
</code>```

Once I had all the relevant converters, I then registered the module to each of their ObjectMappers:

```<code>forEach(converter -> {
    ((MappingJackson2XmlHttpMessageConverter) converter)
            .getObjectMapper()
            .register(jaxbAnnotationModule);
});
</code>```

Body:
I'm trying to automatically deserialize XML formatted response using Spring's RestTemplate. I'm using Jackson's jackson-dataformat-xml module, for which Spring Boot is set to auto-configure. I want to use JAXB annotations in the class I want to deserialize to, but it won't seem to work. Here's a sample of what I want the class to look like:

@XmlRootElement(name="Book")
public class Book {

    @XmlElement(name="Title")
    private String title;
    @XmlElement(name="Author")
    private String author;

}

This is based on the following XML sample:

<Book>
    <Title>My Book</Title>
    <Author>Me</Author>
</Book>

However, with class annotated like that above, the fields are always set null. I did some experiments and found out that the deserialization works if I use Jackson's @JsonProperty to annotate the child elements:

@XmlRootElement(name="Book")
public class Book {

    @JsonProperty("Title")
    private String title;
    @JsonProperty("Author")
    private String author;

}

It works, but somehow I feel like it's kind of awkward. Is there a way to get the JAXB annotations work like in my first example?

Jackson provides jackson-module-jaxb-annotations module for the XML databinding to work with JAXB annotations. However, I'm not sure how to setup the ObjectMapper being used by RestTemplate to use this module.

Body:
To address this issue, I needed to register an instance of JaxbAnnotationModule to every ObjectMapper used by converters added to Spring's RestTemplate. The class is included in Jackson's jackson-module-jaxb-annotations module, which I added to my build through Gradle.

With the dependency added to my project, what I did next was to configure the RestTemplate used by my application. The ObjectMapper instances are being used by MappingJackson2XmlHttpMessageConverters configured automatically by Spring. I had to register JaxbAnnotationModule instance to each ObjectMapper used in every converter, so the first task was to find all MappingJackson2XmlHttpMessageConverters using:

//create module
JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();

restTemplate.getMessageConverters().stream().filter(converter -> {
    return converter instanceof MappingJackson2XmlHttpMessageConverter;
})

Once I had all the relevant converters, I then registered the module to each of their ObjectMappers:

forEach(converter -> {
    ((MappingJackson2XmlHttpMessageConverter) converter)
            .getObjectMapper()
            .register(jaxbAnnotationModule);
});


问:
Scheme # void error
I tried running the following scheme code:

```<code>(define affiche-gagnant
  (lambda (j1 j2 g1 g2)
    (begin
      (display "Le gagnant est : ")
      (display
       (cond ((> g1 g2) j1)
             ((< g1 g2) j2)
             (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. "))))))))
</code>```

But I get the following output:

```<code>Le gagnant est : personne. Alper et Ezgi sont exaequos. #<void>
</code>```

Where did the #void come from? How do I get rid of it?

答:
Oops, wrong answer. You have an extra display:

```<code>(define affiche-gagnant
  (lambda (j1 j2 g1 g2)
    (begin
      (display "Le gagnant est : ")
       (cond ((> g1 g2) (display j1))
             ((< g1 g2) (display j2))
             (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. ")))))))
</code>```

Should work.

Title: Scheme # void error

Body:
I tried running the following scheme code:

(define affiche-gagnant
  (lambda (j1 j2 g1 g2)
    (begin
      (display "Le gagnant est : ")
      (display
       (cond ((> g1 g2) j1)
             ((< g1 g2) j2)
             (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. "))))))))

But I get the following output:

Le gagnant est : personne. Alper et Ezgi sont exaequos. #<void>

Where did the #void come from? How do I get rid of it?

Body:
Oops, wrong answer. You have an extra display:

(define affiche-gagnant
  (lambda (j1 j2 g1 g2)
    (begin
      (display "Le gagnant est : ")
       (cond ((> g1 g2) (display j1))
             ((< g1 g2) (display j2))
             (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. ")))))))

Should work.


问:
What is a hash function in java?
I have check out this Wikipedia page on it, but I still don't understand it. Can someone please help my dim-witted mind to understand the concepts of hashing, hashtable/hashmap, and hash functions? Some examples would really help.</p>

答:
Hash function: If you pass the same object to this function any number of times, be it text, binary or number, you always get the same output. For the hash table purposes an integer returning hash function is used.

Above functionality is calling hashing.

Hash table: Miracle data structure of computer science that returns search result in constant time or O(1). It is based on the above concept of hashing.
So, it has better access time than linkedlist, binary search trees etc.

Why nearly O(1): It uses an array as its base structure internally to store the objects and as arrays have constant access time hence, the Hash table does too.

[Basic internal]:
So, it uses an array of fixed size internally and when you insert an (Key, Value) pair, it calculates key's hash and uses this hash value as index to store the (Key,Value) pair in the array. Next, when you search for the object using the same key, it uses the hash of the key again as index to search for the key in the array.
Now, two objects can have same hash value and hence, while inserting these objects in the hash table there will be collision. There are two ways for collision resolution. You can refer this link for a sufficiently detailed discussion on this topic.

Title: What is a hash function in java?


问:
How do I pass data from an asynchronous task to a view controller?
Summary

I'm querying an API for a user with the user's login username and password in an asynchronous task. I found one method of doing this by:

Create a protocol delegate in the same file as my UIViewController.

Make the protocol delegate a member of the UIViewController.

Create an API class for executing the async. task.

Define the completion handler functions of the delegate member variable of the UIViewController.

Pass the  URL, delegate, parameters, etc... to the API class.

Execute the async. task in the API class.

Once the async. task is complete the completion handlers are executed in the original view controller.

API File

```<code>class API {
    var delegate: APIDelegate?
    required init(providedDelegate: APIDelegate){
        delegate = providedDelegate
    }
    func getPOSTData(){
        API.request(URL, method: .post).responseJSON
        { response in
            if response.result.value != nil {
                //print("JSON: \(JSON)")
                self.delegate?.onSuccess(jsonData: JSON as! [String : Any])
            } else {
                self.delegate?.onFailure(error: "No JSON Data")
            }
        }
    }
}
</code>```

View Controller File

```<code>protocol APIDelegate{
    func onSuccess(jsonData: [String:Any])
    func onFailure(error: Any)
}
UIViewControllerName : UIViewController, APIDelegate{
    var delegate: APIDelegate?

    func testAPICall(sender: UIButton){
        let client = API(providedDelegate: delegate!)
        client.getPOSTData()
    }

    func onSuccess(jsonData: [String:Any]) {
        print("JSON: \(jsonData)")
    }
    func onFailure(error: Any) {
        print(error)
    }

}
</code>```

Question

Is this going to cause problems in the long run? Is there a better way to share data between an asynchronous task from another class back up to the calling UIViewController?

答:
You can pass data through closure

Declare block

```<code>typealias responseHandler = (_ responseObject: [String : Any]) -> Void

 func getPOSTData(with callback : responseHandler){
        API.request(URL, method: .post).responseJSON
            { response in
                if response.result.value != nil {
                    //print("JSON: \(JSON)")
                    self.delegate?.onSuccess(jsonData: JSON as! [String : Any])
                    callback(JSON as! [String : Any])

                } else {
                    callback([:] as! [String : Any] )
                }
        }
    }
</code>```

Invoke as below

```<code>client.getPOSTData { (responseData) in
            print(responseData)
            // here your data
        }
</code>```

Body:
Summary

I'm querying an API for a user with the user's login username and password in an asynchronous task. I found one method of doing this by:

Create a protocol delegate in the same file as my UIViewController.

Make the protocol delegate a member of the UIViewController.

Create an API class for executing the async. task.

Define the completion handler functions of the delegate member variable of the UIViewController.

Pass the  URL, delegate, parameters, etc... to the API class.

Execute the async. task in the API class.

Once the async. task is complete the completion handlers are executed in the original view controller.

API File

class API {
    var delegate: APIDelegate?
    required init(providedDelegate: APIDelegate){
        delegate = providedDelegate
    }
    func getPOSTData(){
        API.request(URL, method: .post).responseJSON
        { response in
            if response.result.value != nil {
                //print("JSON: \(JSON)")
                self.delegate?.onSuccess(jsonData: JSON as! [String : Any])
            } else {
                self.delegate?.onFailure(error: "No JSON Data")
            }
        }
    }
}

View Controller File

protocol APIDelegate{
    func onSuccess(jsonData: [String:Any])
    func onFailure(error: Any)
}
UIViewControllerName : UIViewController, APIDelegate{
    var delegate: APIDelegate?

    func testAPICall(sender: UIButton){
        let client = API(providedDelegate: delegate!)
        client.getPOSTData()
    }

    func onSuccess(jsonData: [String:Any]) {
        print("JSON: \(jsonData)")
    }
    func onFailure(error: Any) {
        print(error)
    }

}

Question

Is this going to cause problems in the long run? Is there a better way to share data between an asynchronous task from another class back up to the calling UIViewController?

Body:
You can pass data through closure

Declare block

typealias responseHandler = (_ responseObject: [String : Any]) -> Void

 func getPOSTData(with callback : responseHandler){
        API.request(URL, method: .post).responseJSON
            { response in
                if response.result.value != nil {
                    //print("JSON: \(JSON)")
                    self.delegate?.onSuccess(jsonData: JSON as! [String : Any])
                    callback(JSON as! [String : Any])

                } else {
                    callback([:] as! [String : Any] )
                }
        }
    }

Invoke as below

client.getPOSTData { (responseData) in
            print(responseData)
            // here your data
        }


答:
Basically your code is supposed to work, however I highly recommend to use a callback closure rather than protocol / delegate.

The code uses an enum to be able to return a single value and a switch statement to handle the cases on the caller side:

```<code>enum APIResult {
    case success([String:Any])
    case failure(Any)
}

class UIViewControllerName : UIViewController {

    func testAPICall(sender: UIButton) {

        let client = API()
        client.getPOSTData() { result in
            switch result {
               case .success(let jsonData) :  print("JSON: \(jsonData)")
               case .failure(let error) :  print("JSON: \(error)")
            }
        }
    }
}

class API {

    func getPOSTData(completion: (APIResult)->() ) {
        API.request(URL, method: .post).responseJSON
            { response in
                if response.result.value != nil {
                    //print("JSON: \(JSON)")
                    completion(.success(JSON as! [String : Any]))
                } else {
                    completion(.failure("No JSON Data"))
                }
        }
    }
}
</code>```

Title: How do I pass data from an asynchronous task to a view controller?

Body:
Basically your code is supposed to work, however I highly recommend to use a callback closure rather than protocol / delegate.

The code uses an enum to be able to return a single value and a switch statement to handle the cases on the caller side:

enum APIResult {
    case success([String:Any])
    case failure(Any)
}

class UIViewControllerName : UIViewController {

    func testAPICall(sender: UIButton) {

        let client = API()
        client.getPOSTData() { result in
            switch result {
               case .success(let jsonData) :  print("JSON: \(jsonData)")
               case .failure(let error) :  print("JSON: \(error)")
            }
        }
    }
}

class API {

    func getPOSTData(completion: (APIResult)->() ) {
        API.request(URL, method: .post).responseJSON
            { response in
                if response.result.value != nil {
                    //print("JSON: \(JSON)")
                    completion(.success(JSON as! [String : Any]))
                } else {
                    completion(.failure("No JSON Data"))
                }
        }
    }
}


问:
Does Google BigQuery supports ARRAY<STRING>?
I am pushing the data from Google dataflow to Google BigQuery. I have TableRow object with data in it. One of columns in TableRow does contain Array of String.

From here, I found that Google BigQuery supports Array column type.
So I tried to create table with ARRAY<SCHEMA> as type. But I got the below error

```<code>com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid value for: ARRAY<STRING> is not a valid value",
    "reason" : "invalid"
  } ],
  "message" : "Invalid value for: ARRAY<STRING> is not a valid value"
}
com.google.cloud.dataflow.sdk.util.UserCodeException.wrapIf(UserCodeException.java:47)
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.wrapUserCodeException(DoFnRunnerBase.java:369)
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.finishBundle(DoFnRunnerBase.java:162)
com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn.finishBundle(SimpleParDoFn.java:194)
com.google.cloud.dataflow.sdk.runners.worker.ForwardingParDoFn.finishBundle(ForwardingParDoFn.java:47)
</code>```

Here is the code that I use to publish values into BigQuery

```<code>    .apply(BigQueryIO.Write.named("Write enriched data")
               .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
               .withSchema(getSchema())
               .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
               .to("table_name"));
</code>```

And here is the schema construction

```<code>private static TableSchema getSchema() {
    List<TableFieldSchema> fields = new ArrayList<>();

    fields.add(new TableFieldSchema().setName("column1").setType("STRING"));
    fields.add(new TableFieldSchema().setName("column2").setType("STRING"));
    fields.add(new TableFieldSchema().setName("array_column").setType("ARRAY<STRING>"));

    return new TableSchema().setFields(fields);
}
</code>```

How can I insert array of string into BigQuery table?

答:
To define a ARRAY<STRING> in BigQuery I set the field as 'STRING' and its mode as 'REPEATED'.

In Python for instance it's defined as field = SchemaField(name='field_1', type='STRING', mode='REPEATED')

For the Java client for what I could see you have the same options, you could define the TYPE as STRING and the MODE as REPEATED.

Body:
I am pushing the data from Google dataflow to Google BigQuery. I have TableRow object with data in it. One of columns in TableRow does contain Array of String.

From here, I found that Google BigQuery supports Array column type.
So I tried to create table with ARRAY<SCHEMA> as type. But I got the below error

com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid value for: ARRAY<STRING> is not a valid value",
    "reason" : "invalid"
  } ],
  "message" : "Invalid value for: ARRAY<STRING> is not a valid value"
}
com.google.cloud.dataflow.sdk.util.UserCodeException.wrapIf(UserCodeException.java:47)
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.wrapUserCodeException(DoFnRunnerBase.java:369)
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.finishBundle(DoFnRunnerBase.java:162)
com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn.finishBundle(SimpleParDoFn.java:194)
com.google.cloud.dataflow.sdk.runners.worker.ForwardingParDoFn.finishBundle(ForwardingParDoFn.java:47)

Here is the code that I use to publish values into BigQuery

    .apply(BigQueryIO.Write.named("Write enriched data")
               .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
               .withSchema(getSchema())
               .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
               .to("table_name"));

And here is the schema construction

private static TableSchema getSchema() {
    List<TableFieldSchema> fields = new ArrayList<>();

    fields.add(new TableFieldSchema().setName("column1").setType("STRING"));
    fields.add(new TableFieldSchema().setName("column2").setType("STRING"));
    fields.add(new TableFieldSchema().setName("array_column").setType("ARRAY<STRING>"));

    return new TableSchema().setFields(fields);
}

How can I insert array of string into BigQuery table?


问:
JS Need to add value every 1.5 sec
This is my code that is unfortunately not working.

It is taking value from html (600) and then dividing it (var f = 600/20). It should start onclick button (which already has onclick function).

function enemy() {
  var iFrequency = 2500;
  var myInterval = 0;
  var e = document.getElementById('stre').innerHTML;
  var f = e / 20;

  function startLoop() {
    if (myInterval > 0) clearInterval(myInterval); // stop
    myInterval = setInterval("doSomething()", iFrequency);
  }

  function doSomething() {
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) + f;
    document.getElementById('wallvalue').style.color = 'red';
    document.getElementById('resultr').innerHTML = f;
    document.getElementById('resultr').style.color = 'red';
    document.getElementById('resultrc').innerHTML = f;
    document.getElementById('resultrc').style.color = 'red';
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><BUTTON class="doit" onclick="damagec(); iFrequency+=1000; startLoop(); return false;"><b>FIGHT</b></BUTTON></code>```

答:
Looks like youve tried to do some inheritance, but your code is not working in any way. You may do this:

function enemy(name) { // a constructor for our enemy
  this.name=name;
  this.iFrequency = 2500;
  this.myInterval = false;
  this.el=document.createElement("div");
  document.body.appendChild(this.el);
  this.f = 1;
}

enemy.prototype={ //functions for all enemys
  startLoop:function() {
    if (this.myInterval) clearInterval(this.myInterval); // stop
    this.myInterval = setInterval(this.doSomething.bind(this), this.iFrequency);
  },
  doSomething:function () {
    this.el.innerHTML = this.name+":"+(++this.f);
    this.el.style.color = 'red';
  }
};

var Monster=new enemy("Monster");//create a new Enemey
var button=document.createElement("button");
button.textContent="Start Monster";
document.body.appendChild(button);

button.onclick=Monster.startLoop.bind(Monster);```

Title: JS Need to add value every 1.5 sec

Body:
This is my code that is unfortunately not working.

It is taking value from html (600) and then dividing it (var f = 600/20). It should start onclick button (which already has onclick function).

function enemy() {
  var iFrequency = 2500;
  var myInterval = 0;
  var e = document.getElementById('stre').innerHTML;
  var f = e / 20;

  function startLoop() {
    if (myInterval > 0) clearInterval(myInterval); // stop
    myInterval = setInterval("doSomething()", iFrequency);
  }

  function doSomething() {
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) + f;
    document.getElementById('wallvalue').style.color = 'red';
    document.getElementById('resultr').innerHTML = f;
    document.getElementById('resultr').style.color = 'red';
    document.getElementById('resultrc').innerHTML = f;
    document.getElementById('resultrc').style.color = 'red';
  }

<BUTTON class="doit" onclick="damagec(); iFrequency+=1000; startLoop(); return false;">FIGHT</BUTTON>


问:
Retrieve attribute value from one xml and use it as a value for another attribute in other xml file
Say I have File1.xml and File2.xml

File1.xml has the following :

```<code><tag1 attribute1 = "value1" attribute2 = "value2">tagvalue</tag1>
</code>```

I want the following in  File2 to have the below :

```<code><tag2 attribute1 = "value of the attribute1 of the tag1 in file1" />
</code>```

Please let me know if I am not clear with my question.

答:
Let, there is file1.xml that contains

```<code><tags>
    <tag1 attribute1 = "value1" attribute2 = "value2">tagvalue</tag1>
    <tag2 attribute1 = "value21" attribute2 = "value22">tagvalue</tag2>
    <tag3 attribute1 = "value31" attribute2 = "value22">tagvalue</tag3>
</tags>
</code>```

Then you could use following transformation:

```<code><xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
    <tags>
        <xsl:apply-templates select="./*" />
    </tags>
    </xsl:template>
    <xsl:template match="*/*">
      <xsl:element name="tag2">
        <xsl:attribute name="attribute1">
            <xsl:text>value of the attribute1 of the attribute1 of </xsl:text>
            <xsl:value-of select="name(.)"></xsl:value-of>
            <xsl:text> is </xsl:text>
            <xsl:value-of select="@attribute1"></xsl:value-of>
        </xsl:attribute>
      </xsl:element>
    </xsl:template>
</xsl:transform>
</code>```

Body:
Say I have File1.xml and File2.xml

File1.xml has the following :

<tag1 attribute1 = "value1" attribute2 = "value2">tagvalue</tag1>

I want the following in  File2 to have the below :

<tag2 attribute1 = "value of the attribute1 of the tag1 in file1" />

Please let me know if I am not clear with my question.

Body:
Let, there is file1.xml that contains

<tags>
    <tag1 attribute1 = "value1" attribute2 = "value2">tagvalue</tag1>
    <tag2 attribute1 = "value21" attribute2 = "value22">tagvalue</tag2>
    <tag3 attribute1 = "value31" attribute2 = "value22">tagvalue</tag3>
</tags>

Then you could use following transformation:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
    <tags>
        <xsl:apply-templates select="./*" />
    </tags>
    </xsl:template>
    <xsl:template match="*/*">
      <xsl:element name="tag2">
        <xsl:attribute name="attribute1">
            <xsl:text>value of the attribute1 of the attribute1 of </xsl:text>
            <xsl:value-of select="name(.)"></xsl:value-of>
            <xsl:text> is </xsl:text>
            <xsl:value-of select="@attribute1"></xsl:value-of>
        </xsl:attribute>
      </xsl:element>
    </xsl:template>
</xsl:transform>


问:
Pandas read_csv() - Flie contains different data
Problem:
I am trying to read in a csv to a pandas dataframe that contains data of different column sizes.

Example & Description:

```<code>Code:
df = pd.read_csv(input, error_bad_lines=False)

input:
ID, Time, Val
15, 18:00:01, 4
15, 18:00:02, 6
15, 18:00:03, 5
ID, Time, Val1, Val2
16 18:00:03, 1, 43
ID, Time, Val
15, 18:00:04, 8
</code>```

and this pattern continues for the entirety of the file. Originally I was thinking about throwing away the extra columns since read_csv option throws and error and doesn't read them I just started to ignore them. However I then get duplicate headers in my dataframe... To combat this I tried the drop_duplicates() but found out that only in V0.17 of pandas do they include the keep=False option. I eventually started to convince myself that try to keep the data. So here is my question. Based on the dataset above I was hoping that I might be able to create two unique dataframes. You can assume that the ID will always be unique so you can create N number of frames for the number of different IDs you have. Each ID will not have the same number of headers. Once a different ID is encountered its header will be printed. So for example if we hit another ID 16 its header will be printed prior to the data. And again if we hit another ID 15 its header will be printed prior to its data.

I was thinking maybe to just preprocess the data before I started using dataframes since that is an option. But since I am still fairly new to all that pandas can do, I was hoping maybe some people here would have suggestions before I went ahead and wrote some nasty preprocessing code :). The other thought I had which turns into a question is - For the error_bad_lines, is there a way to save those lines to another dataframe or something else? Additionally, I tell pandas in the read_csv to only look for items that have an ID of X and just do that for all my ID's? I will add that the number of IDs is finite and known.

My current version of pandas is 0.14.

答:
Note I corrected what I think is a typo in your sample data.

I split your data with a lookahead regular expression.  I look for newline characters that are followed by ID.

Then parse each element of the list and concatenate.

```<code>from io import StringIO
import pandas as pd
import re

txt = """ID, Time, Val
15, 18:00:01, 4
15, 18:00:02, 6
15, 18:00:03, 5
ID, Time, Val1, Val2
16, 18:00:03, 1, 43
ID, Time, Val
15, 18:00:04, 8"""

def parse(s):
    return pd.read_csv(StringIO(s), skipinitialspace=True)

pd.concat([parse(s) for s in re.split('\n(?=ID)', txt)])

   ID      Time  Val  Val1  Val2
0  15  18:00:01  4.0   NaN   NaN
1  15  18:00:02  6.0   NaN   NaN
2  15  18:00:03  5.0   NaN   NaN
0  16  18:00:03  NaN   1.0  43.0
0  15  18:00:04  8.0   NaN   NaN
</code>```

The above was working with the sample data provided by OP.  If this were in a csv file the solution would look like this

```<code>from io import StringIO
import pandas as pd
import re

with open('myfile.csv') as f:
    txt = f.read()

def parse(s):
    return pd.read_csv(StringIO(s), skipinitialspace=True)

pd.concat([parse(s) for s in re.split('\n(?=ID)', txt)])
</code>```

Body:
Problem:
I am trying to read in a csv to a pandas dataframe that contains data of different column sizes.

Example & Description:

Code:
df = pd.read_csv(input, error_bad_lines=False)

input:
ID, Time, Val
15, 18:00:01, 4
15, 18:00:02, 6
15, 18:00:03, 5
ID, Time, Val1, Val2
16 18:00:03, 1, 43
ID, Time, Val
15, 18:00:04, 8

and this pattern continues for the entirety of the file. Originally I was thinking about throwing away the extra columns since read_csv option throws and error and doesn't read them I just started to ignore them. However I then get duplicate headers in my dataframe... To combat this I tried the drop_duplicates() but found out that only in V0.17 of pandas do they include the keep=False option. I eventually started to convince myself that try to keep the data. So here is my question. Based on the dataset above I was hoping that I might be able to create two unique dataframes. You can assume that the ID will always be unique so you can create N number of frames for the number of different IDs you have. Each ID will not have the same number of headers. Once a different ID is encountered its header will be printed. So for example if we hit another ID 16 its header will be printed prior to the data. And again if we hit another ID 15 its header will be printed prior to its data.

I was thinking maybe to just preprocess the data before I started using dataframes since that is an option. But since I am still fairly new to all that pandas can do, I was hoping maybe some people here would have suggestions before I went ahead and wrote some nasty preprocessing code :). The other thought I had which turns into a question is - For the error_bad_lines, is there a way to save those lines to another dataframe or something else? Additionally, I tell pandas in the read_csv to only look for items that have an ID of X and just do that for all my ID's? I will add that the number of IDs is finite and known.

My current version of pandas is 0.14.

Body:
Note I corrected what I think is a typo in your sample data.

I split your data with a lookahead regular expression.  I look for newline characters that are followed by ID.

Then parse each element of the list and concatenate.

from io import StringIO
import pandas as pd
import re

txt = """ID, Time, Val
15, 18:00:01, 4
15, 18:00:02, 6
15, 18:00:03, 5
ID, Time, Val1, Val2
16, 18:00:03, 1, 43
ID, Time, Val
15, 18:00:04, 8"""

def parse(s):
    return pd.read_csv(StringIO(s), skipinitialspace=True)

pd.concat([parse(s) for s in re.split('\n(?=ID)', txt)])

   ID      Time  Val  Val1  Val2
0  15  18:00:01  4.0   NaN   NaN
1  15  18:00:02  6.0   NaN   NaN
2  15  18:00:03  5.0   NaN   NaN
0  16  18:00:03  NaN   1.0  43.0
0  15  18:00:04  8.0   NaN   NaN

The above was working with the sample data provided by OP.  If this were in a csv file the solution would look like this

from io import StringIO
import pandas as pd
import re

with open('myfile.csv') as f:
    txt = f.read()

def parse(s):
    return pd.read_csv(StringIO(s), skipinitialspace=True)

pd.concat([parse(s) for s in re.split('\n(?=ID)', txt)])