问:
Angular 4 add click event on button dynamically
Here is the code of button displayed from loop.

```<code>for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "<tr>";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "<td>" + this.newTmpArr[k][key2] + "</td>";
        }

    }
    myTable += "</tr>";
}

test(){
  alert("Working!");
}
</code>```

Here is the screenshot of the page look like after dynamic data rendered.

答:
Read for detail : Dynamic Html Structure with - *ngIf, *ngFor & ngSwitch

you can try out , Template way below is working fine without much change, below took just 20 min

App.Component.html --- template file

```<code><table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Ammount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
   <tr *ngFor="let ele of newTmpArr" >
     <td>{{ele[0]}}</td>
     <td>{{ele[1]}}</td>
     <td>{{ele[2]}}</td>
     <td>
        <div ngSwitch="{{ele[3]}}">
            <div *ngSwitchCase="'button'">
              <input type="button" (click)="DoWork(1)" value="click"/>
            </div>
            <div *ngSwitchCase="'link'">
                <a href="#" (click)="DoWork(1)" >click</a>
            </div>
        </div>
     </td>
   </tr>
  </tbody>
</table>
</code>```

App.Component.ts--typescript

```<code>export class AppComponent implements OnInit {
ngOnInit(): void {}
title = 'app';
DoWork()
  {
    //here you can do work ,
    //this get called when you press "click" button in table
    alert(this.title);
  }
}
</code>```

Without template dynamic way

It took me 5 hours to reach this code but fater that Following is working fine , you need to by pass security with the help of DomSanitizer as you want to put input element from you template file.

```<code>//typings.d.ts
interface Window { my: any; }
</code>```

above one extends your window object

app.Component.html

```<code><table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Ammount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody id="tid" [innerHTML]="bodytext"></tbody>
</table>
</code>```

typescript file - app.Component.ts

```<code>import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import {Component, NgZone, OnInit, OnDestroy} from '@angular/core';

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

export class AppComponent implements OnInit {
   title = 'app';
  _myTable : string;
  bodytext ;
  newTmpArr = [
          ["567", "2017-04-17T14:22:48", "45000", "button"],
          ["567", "2017-04-17T14:22:48", "45000", "button"],
          ["567", "2017-04-17T14:22:48", "45000", "link"],
          ["567", "2017-04-17T14:22:48", "45000", "button"]
        ];
   constructor(private http: Http,private _sanitizer:
                 DomSanitizer,private ngZone: NgZone) {
   }

  ngOnInit(): void {
    //below code add dynamci table to your html
    for( let k=0; k<this.newTmpArr.length; k++ ){
            this._myTable += "<tr>";
            for( let key2 in this.newTmpArr[k] ){
                if(this.newTmpArr[k][key2] == 'button' ){
                //below is table click button calls angular function,
                //here 1 is passed as arugment you can pass
                //any other value you want
                //or if you dont want to pass than just do
                // onclick="my.namespace.publicFunc();"
                // and remove parameter from typscript function also
                this._myTable += `<td><input  type="button"
                   onclick="my.namespace.publicFunc(1);"
                   value="Click me"  /></td>`;
                break;
                }
                if(this.newTmpArr[k][key2] == 'link' ){
                this._myTable += `<td><a href="#"
                        onclick="my.namespace.publicFunc(1);
                             return false;">Click</a>
                         </td>`;
                break;
                } else {
                this._myTable += "<td>" +
                   this.newTmpArr[k][key2] + "</td>";
                }
            }
            this._myTable += "</tr>";
        }
         this.bodytext =
        this._sanitizer.bypassSecurityTrustHtml(this._myTable);
        //code to add dynamic html ends here

         //below script helps to expose anglar function to javascript
         window.my = window.my || {};
         window.my.namespace = window.my.namespace || {};
        //below line bind typescript function to window object publicFunc
         window.my.namespace.publicFunc =
          this.OnTableButtonClick.bind(this);
        //code to expose typscipt function ends here
  }

  //this function get called when Table click button ge clicked
  public OnTableButtonClick(input:string):void{
    this.ngZone.run(() => this.DoWork(input));
  }

  DoWork(input:string)
  {
    //here you can do work ,
    //this get called when you press "click" button in table
    alert(this.title + input);
    //this will display app1 in output
  }
}
</code>```

Body:
Here is the code of button displayed from loop.

for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "
";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "" + this.newTmpArr[k][key2] + "	";
        }

    }
    myTable += "
";
}

test(){
  alert("Working!");
}

Here is the screenshot of the page look like after dynamic data rendered.

Body:
Read for detail : Dynamic Html Structure with - *ngIf, *ngFor & ngSwitch

you can try out , Template way below is working fine without much change, below took just 20 min

App.Component.html --- template file

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Ammount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
   <tr *ngFor="let ele of newTmpArr" >
     <td>{{ele[0]}}</td>
     <td>{{ele[1]}}</td>
     <td>{{ele[2]}}</td>
     <td>
        <div ngSwitch="{{ele[3]}}">
            <div *ngSwitchCase="'button'">
              <input type="button" (click)="DoWork(1)" value="click"/>
            </div>
            <div *ngSwitchCase="'link'">
                <a href="#" (click)="DoWork(1)" >click</a>
            </div>
        </div>
     </td>
   </tr>
  </tbody>
</table>

App.Component.ts--typescript

export class AppComponent implements OnInit {
ngOnInit(): void {}
title = 'app';
DoWork()
  {
    //here you can do work ,
    //this get called when you press "click" button in table
    alert(this.title);
  }
}

Without template dynamic way

It took me 5 hours to reach this code but fater that Following is working fine , you need to by pass security with the help of DomSanitizer as you want to put input element from you template file.

//typings.d.ts
interface Window { my: any; }

above one extends your window object

app.Component.html

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Ammount</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody id="tid" [innerHTML]="bodytext"></tbody>
</table>

typescript file - app.Component.ts

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import {Component, NgZone, OnInit, OnDestroy} from '@angular/core';

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

export class AppComponent implements OnInit {
   title = 'app';
  _myTable : string;
  bodytext ;
  newTmpArr = [
          ["567", "2017-04-17T14:22:48", "45000", "button"],
          ["567", "2017-04-17T14:22:48", "45000", "button"],
          ["567", "2017-04-17T14:22:48", "45000", "link"],
          ["567", "2017-04-17T14:22:48", "45000", "button"]
        ];
   constructor(private http: Http,private _sanitizer:
                 DomSanitizer,private ngZone: NgZone) {
   }

  ngOnInit(): void {
    //below code add dynamci table to your html
    for( let k=0; k<this.newTmpArr.length; k++ ){
            this._myTable += "<tr>";
            for( let key2 in this.newTmpArr[k] ){
                if(this.newTmpArr[k][key2] == 'button' ){
                //below is table click button calls angular function,
                //here 1 is passed as arugment you can pass
                //any other value you want
                //or if you dont want to pass than just do
                // onclick="my.namespace.publicFunc();"
                // and remove parameter from typscript function also
                this._myTable += `<td><input  type="button"
                   onclick="my.namespace.publicFunc(1);"
                   value="Click me"  /></td>`;
                break;
                }
                if(this.newTmpArr[k][key2] == 'link' ){
                this._myTable += `<td><a href="#"
                        onclick="my.namespace.publicFunc(1);
                             return false;">Click</a>
                         </td>`;
                break;
                } else {
                this._myTable += "<td>" +
                   this.newTmpArr[k][key2] + "</td>";
                }
            }
            this._myTable += "</tr>";
        }
         this.bodytext =
        this._sanitizer.bypassSecurityTrustHtml(this._myTable);
        //code to add dynamic html ends here

         //below script helps to expose anglar function to javascript
         window.my = window.my || {};
         window.my.namespace = window.my.namespace || {};
        //below line bind typescript function to window object publicFunc
         window.my.namespace.publicFunc =
          this.OnTableButtonClick.bind(this);
        //code to expose typscipt function ends here
  }

  //this function get called when Table click button ge clicked
  public OnTableButtonClick(input:string):void{
    this.ngZone.run(() => this.DoWork(input));
  }

  DoWork(input:string)
  {
    //here you can do work ,
    //this get called when you press "click" button in table
    alert(this.title + input);
    //this will display app1 in output
  }
}


来源: stackexchange

问:
How to check identical of dictionary key values?
Hi I am trying to do simple task of Python whether the dictionary's keys are equal or not.
here is my example code

```<code>loc = {'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206, 'name': "SNU",  'keywords':["school, hard"],}
</code>```

This is my example data. And if I print out the loc's key values, then I got...

```<code>print(loc.keys())
</code>```

Print: dict_keys(['latitude', 'longitude', 'timestamp', 'name', 'keywords'])

So what I wanted to do is checking whether the data is same as dictionary's key or not. I use this but it does not work at all....

```<code>print(loc.keys() == ['latitude', 'longitude', 'timestamp', 'name', 'keywords'])
</code>```

This still gets me False. Is there any other way that I can make this into false?

答:
Just convert list of keys to set and compare with another set:

```<code>set(loc.keys()) == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'}
</code>```

As @juanpa.arrivillaga kindly noted you don't need to get keys() of dict to convert the into set, you can do it right away:

```<code>set(loc) == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'}
</code>```

NOTE: To the best answer please refer to @PM2Ring answer

ContentLicense: CC BY-SA 3.0

Body:
Hi I am trying to do simple task of Python whether the dictionary's keys are equal or not.
here is my example code

loc = {'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206, 'name': "SNU",  'keywords':["school, hard"],}

This is my example data. And if I print out the loc's key values, then I got...

print(loc.keys())

Print: dict_keys(['latitude', 'longitude', 'timestamp', 'name', 'keywords'])

So what I wanted to do is checking whether the data is same as dictionary's key or not. I use this but it does not work at all....

print(loc.keys() == ['latitude', 'longitude', 'timestamp', 'name', 'keywords'])

This still gets me False. Is there any other way that I can make this into false?

Body:
Just convert list of keys to set and compare with another set:

set(loc.keys()) == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'}

As @juanpa.arrivillaga kindly noted you don't need to get keys() of dict to convert the into set, you can do it right away:

set(loc) == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'}

NOTE: To the best answer please refer to @PM2Ring answer


问:
How can I write data from JavaScript function which is in view index.html to json file in computer (MVC)?
I have MVC web application where user draws a shape on a map and the coordinates of it should be saved in Json file in user's computer, particular location, so that it can be accessed and displayed for the user later. I get the coordinates. But how can I write the coordinates to Json file from a Javascript function? </p>

答:
Here's a way to write to a text file using FileSystemObject Reference (Windows Scripting) and JavaScript. See CreateTextFile Method for more info.

```<code>function WriteToTextFile(text, path, overwrite) {
    var ov = false;
    var fso = new ActiveXObject("Scripting.FileSystemObject");

    if(overwrite === true)
        ov = true;

    var a = fso.CreateTextFile(path, overwrite);
    a.WriteLine(text);
    a.Close();
}
</code>```

Usage:

```<code>var obj =
{
    propA: "A",
    propB: "B",
    propC: 123
};
var text = JSON.stringify(obj);
var path = "c:\\testfile.txt";

WriteToTextFile(text, path, false);
</code>```

Note that you need to install the ActiveX plugin and this only works on IE. What you want to achieve is not considered a good practice and poses security risks which is why the ideal way is to generate the file on the server and prompt the user to save it. I also don't see why you are using web with a local database. Basing on your requirement, I'd suggest using localStorage.

Body:
Here's a way to write to a text file using FileSystemObject Reference (Windows Scripting) and JavaScript. See CreateTextFile Method for more info.

function WriteToTextFile(text, path, overwrite) {
    var ov = false;
    var fso = new ActiveXObject("Scripting.FileSystemObject");

    if(overwrite === true)
        ov = true;

    var a = fso.CreateTextFile(path, overwrite);
    a.WriteLine(text);
    a.Close();
}

Usage:

var obj =
{
    propA: "A",
    propB: "B",
    propC: 123
};
var text = JSON.stringify(obj);
var path = "c:\\testfile.txt";

WriteToTextFile(text, path, false);

Note that you need to install the ActiveX plugin and this only works on IE. What you want to achieve is not considered a good practice and poses security risks which is why the ideal way is to generate the file on the server and prompt the user to save it. I also don't see why you are using web with a local database. Basing on your requirement, I'd suggest using localStorage.


问:
How to read xml file in c# with specific attribute
I have an xml file with attribute

```<code> xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
</code>```

When I remove this attribute, then I can read each tag. If I don't remove attribute I receive error message "Object refrence not set to instance of object"

My C# code:

```<code>XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
                         .SelectSingleNode("/BookingCreate/CommitLevel")
                         .InnerText;
</code>```

My XML:

```<code><BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
  <Authority>
    <Org>danco</Org>
    <User>xmltest</User>
    <Password>xmltest</Password>
    <Language>en</Language>
    <Currency>EUR</Currency>
    <TestDebug>false</TestDebug>
    <Version>1.26</Version>
  </Authority>
  <QuoteId>17081233-3</QuoteId>
  <HotelStayDetails>
    <Room>
      <Guests>
        <Adult title="Mr" first="djkvb" last="jkj" />
        <Adult title="Mr" first="jfs" last="kjdjs" />
      </Guests>
    </Room>
  </HotelStayDetails>
  <HotelSearchCriteria>
    <AvailabilityStatus>allocation</AvailabilityStatus>
    <DetailLevel>basic</DetailLevel>
  </HotelSearchCriteria>
  <CommitLevel>prepare</CommitLevel>
</BookingCreate>
</code>```

What to do to read xml with xmlns attribute? It is necessary for me to have xmlns attribute.

答:
Using xml linq :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement bookingCreate = doc.Descendants().Where(x => x.Name.LocalName == "BookingCreate").FirstOrDefault();
            XNamespace ns = bookingCreate.GetDefaultNamespace();

            var results = doc.Descendants(ns + "BookingCreate").Select(x => new {
                org = (string)x.Descendants(ns + "Org").FirstOrDefault(),
                user = (string)x.Descendants(ns + "User").FirstOrDefault(),
                password = (string)x.Descendants(ns + "Password").FirstOrDefault(),
                language = (string)x.Descendants(ns + "Language").FirstOrDefault(),
                currency = (string)x.Descendants(ns + "Currency").FirstOrDefault(),
                testDebug = (Boolean)x.Descendants(ns + "TestDebug").FirstOrDefault(),
                version = (string)x.Descendants(ns + "Version").FirstOrDefault(),
                quoteId = (string)x.Element(ns + "QuoteId"),
                guests = x.Descendants(ns + "Adult").Select(y => new {
                    title = (string)y.Attribute("title"),
                    first = (string)y.Attribute("first"),
                    last = (string)y.Attribute("last")
                }).ToList(),
                availability = (string)x.Descendants(ns + "AvailabilityStatus").FirstOrDefault(),
                detailLevel = (string)x.Descendants(ns + "DetailLevel").FirstOrDefault()
            }).FirstOrDefault();
        }
    }
}
</code>```

Body:
I have an xml file with attribute

 xmlns="http://www.reservwire.com/namespace/WebServices/Xml">

When I remove this attribute, then I can read each tag. If I don't remove attribute I receive error message "Object refrence not set to instance of object"

My C# code:

XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
                         .SelectSingleNode("/BookingCreate/CommitLevel")
                         .InnerText;

My XML:

<BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
  <Authority>
    <Org>danco</Org>
    <User>xmltest</User>
    <Password>xmltest</Password>
    <Language>en</Language>
    <Currency>EUR</Currency>
    <TestDebug>false</TestDebug>
    <Version>1.26</Version>
  </Authority>
  <QuoteId>17081233-3</QuoteId>
  <HotelStayDetails>
    <Room>
      <Guests>
        <Adult title="Mr" first="djkvb" last="jkj" />
        <Adult title="Mr" first="jfs" last="kjdjs" />
      </Guests>
    </Room>
  </HotelStayDetails>
  <HotelSearchCriteria>
    <AvailabilityStatus>allocation</AvailabilityStatus>
    <DetailLevel>basic</DetailLevel>
  </HotelSearchCriteria>
  <CommitLevel>prepare</CommitLevel>
</BookingCreate>

What to do to read xml with xmlns attribute? It is necessary for me to have xmlns attribute.

Body:
Using xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement bookingCreate = doc.Descendants().Where(x => x.Name.LocalName == "BookingCreate").FirstOrDefault();
            XNamespace ns = bookingCreate.GetDefaultNamespace();

            var results = doc.Descendants(ns + "BookingCreate").Select(x => new {
                org = (string)x.Descendants(ns + "Org").FirstOrDefault(),
                user = (string)x.Descendants(ns + "User").FirstOrDefault(),
                password = (string)x.Descendants(ns + "Password").FirstOrDefault(),
                language = (string)x.Descendants(ns + "Language").FirstOrDefault(),
                currency = (string)x.Descendants(ns + "Currency").FirstOrDefault(),
                testDebug = (Boolean)x.Descendants(ns + "TestDebug").FirstOrDefault(),
                version = (string)x.Descendants(ns + "Version").FirstOrDefault(),
                quoteId = (string)x.Element(ns + "QuoteId"),
                guests = x.Descendants(ns + "Adult").Select(y => new {
                    title = (string)y.Attribute("title"),
                    first = (string)y.Attribute("first"),
                    last = (string)y.Attribute("last")
                }).ToList(),
                availability = (string)x.Descendants(ns + "AvailabilityStatus").FirstOrDefault(),
                detailLevel = (string)x.Descendants(ns + "DetailLevel").FirstOrDefault()
            }).FirstOrDefault();
        }
    }
}


问:
C# : The best solution to parse the xml file?
I can write this employee object's information into the XML file. Look like this.

Employee's class

```<code>class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;
        string _text;
        public Employee(int id, string firstName, string lastName, int salary,string text)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
            this._text = text;
        }
        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
        public string Text { get { return _text; } }
    }
</code>```

Writen Xml.

```<code><Employees>
    <Employee Text="text1">
        <ID>1</ID>
        <FirstName>David</FirstName>
        <LastName>Smith</LastName>
        <Salary>10000</Salary>
    </Employee>
    <Employee Text="text2">
           <ID>3</ID>
           <FirstName>Mark</FirstName>
           <LastName>Drinkwater</LastName>
           <Salary>30000</Salary>
    </Employee>
<Employees>
</code>```

Then I want to parse xml back into Employee object, What's the best solution?

答:
You could use XmlSerializer.

```<code>var root = new XmlRootAttribute
{
    ElementName = "Employees"
};
var serializer = new XmlSerializer(typeof(Employee[]), root);
using (var reader = XmlReader.Create("employees.xml"))
{
    var employees = (Employee[])serializer.Deserialize(reader);
}
</code>```

Slight modification is required to your Employee class for this to work:

It needs to be public

It needs to have default constructor

The properties need to have setters

```<code>public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Salary { get; set; }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I can write this employee object's information into the XML file. Look like this.

Employee's class

class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;
        string _text;
        public Employee(int id, string firstName, string lastName, int salary,string text)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
            this._text = text;
        }
        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
        public string Text { get { return _text; } }
    }

Writen Xml.

<Employees>
    <Employee Text="text1">
        <ID>1</ID>
        <FirstName>David</FirstName>
        <LastName>Smith</LastName>
        <Salary>10000</Salary>
    </Employee>
    <Employee Text="text2">
           <ID>3</ID>
           <FirstName>Mark</FirstName>
           <LastName>Drinkwater</LastName>
           <Salary>30000</Salary>
    </Employee>
<Employees>

Then I want to parse xml back into Employee object, What's the best solution?

Body:
You could use XmlSerializer.

var root = new XmlRootAttribute
{
    ElementName = "Employees"
};
var serializer = new XmlSerializer(typeof(Employee[]), root);
using (var reader = XmlReader.Create("employees.xml"))
{
    var employees = (Employee[])serializer.Deserialize(reader);
}

Slight modification is required to your Employee class for this to work:

It needs to be public

It needs to have default constructor

The properties need to have setters

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Salary { get; set; }
}


问:
How can i restrict the request from the unauthorized users (url's)?
Here my problem is that in my spring project totally 3 Jsp pages are available.

home page

register page

register success full page

When i type url for the home page in a browser, i am getting home page.and inside one hyperlink is available to register data. automatically when i click on that link it will go to the register page.then after it will go to the register success full page.

So finally my problem is that when i gave home page url in browser, homepage comes and also if i give register page url it will go to the register page with out touches the home page. but actually i want to access the register page through home page.

答:
Spring Security allows user's to access the url's as per authorization.
You can specify, which user has access to which url, if the user is not authorized then redirect to home page or just say access denied.

Please refer the spring security doc.it might help you.


问:
How to Filter table by column in django
I was trying to filter my columns in my django project template
Currently I am able to search in the table and display the rows that have that that value
But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

```<code>def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q:
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 |
                 custom7 | custom8
</code>```

here name product l3 are my fields from my model that I would like to filter from

in my home.html

```<code> <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">
</code>```

my js.js

```<code>function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}
</code>```

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

答:
For adding a dynamic dropdown send column names from the backend.</p>

```<code><select name="columns">
    {% for column in columns %}
            <option value="{{column.name}}">Column {{column.id}}: {{column.name}}</option>
    {% endfor %}
</select>
</code>```

Title: How to Filter table by column in django

Body:
I was trying to filter my columns in my django project template
Currently I am able to search in the table and display the rows that have that that value
But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q:
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 |
                 custom7 | custom8

here name product l3 are my fields from my model that I would like to filter from

in my home.html

 <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">

my js.js

function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

Body:
For adding a dynamic dropdown send column names from the backend.

<select name="columns">
    {% for column in columns %}
            <option value="{{column.name}}">Column {{column.id}}: {{column.name}}</option>
    {% endfor %}
</select>


问:
Draw a box around a legend ggplot2
I created a plot with a custom legend in ggplot2. I tried to draw a box around all the items in the legend, however I could only draw a box around each individual item. How can I create only one box around all the items?

```<code>library(ggplot2)

ggplot(mpg, aes(displ, cty)) +
  geom_point(aes(shape = "Data")) +
  stat_smooth(aes(linetype = "Regression"), method = "lm",
              formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
  scale_shape_manual(values = 1) +
  labs(shape = "", linetype = "") +
  theme_classic() +
  theme(panel.border = element_rect(colour = "black", fill=NA),
        aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
        legend.background = element_rect(linetype = 2, size = 0.5, colour = 1))
</code>```

答:
It seems that the legend.background rectangle overlaps the legend.box.background rectangle. An easy fix is to set legend.background = element_blank().

But then, in my opinion, the spacing in the legend is ugly. The legend titles take up too much space even with no title set. Fix this be setting legend.title = element_blank(). Also the spacing between the two legends is too large. Fix this by setting the space to zero legend.spacing.y = unit(0, "mm")

```<code>library(ggplot2)

ggplot(mpg, aes(displ, cty)) +
  geom_point(aes(shape = "Data")) +
  stat_smooth(aes(linetype = "Regression"), method = "lm",
              formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
  scale_shape_manual(values = 1) +
  labs(shape = "", linetype = "") +
  theme_classic() +
  theme(legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"),
        panel.border = element_rect(colour = "black", fill=NA),
        aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "black"))
</code>```

Title: Draw a box around a legend ggplot2

Body:
I created a plot with a custom legend in ggplot2. I tried to draw a box around all the items in the legend, however I could only draw a box around each individual item. How can I create only one box around all the items?

library(ggplot2)

ggplot(mpg, aes(displ, cty)) +
  geom_point(aes(shape = "Data")) +
  stat_smooth(aes(linetype = "Regression"), method = "lm",
              formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
  scale_shape_manual(values = 1) +
  labs(shape = "", linetype = "") +
  theme_classic() +
  theme(panel.border = element_rect(colour = "black", fill=NA),
        aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
        legend.background = element_rect(linetype = 2, size = 0.5, colour = 1))

Body:
It seems that the legend.background rectangle overlaps the legend.box.background rectangle. An easy fix is to set legend.background = element_blank().

But then, in my opinion, the spacing in the legend is ugly. The legend titles take up too much space even with no title set. Fix this be setting legend.title = element_blank(). Also the spacing between the two legends is too large. Fix this by setting the space to zero legend.spacing.y = unit(0, "mm")

library(ggplot2)

ggplot(mpg, aes(displ, cty)) +
  geom_point(aes(shape = "Data")) +
  stat_smooth(aes(linetype = "Regression"), method = "lm",
              formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
  scale_shape_manual(values = 1) +
  labs(shape = "", linetype = "") +
  theme_classic() +
  theme(legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"),
        panel.border = element_rect(colour = "black", fill=NA),
        aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "black"))


问:
OSError: [WinError 6] The handle is invalid when calling subprocess from Python 3.6
I'm porting a project to Python3 and I'm running into a unexpected error on Windows:

Basically on Python 3.6 on Windows, each time a process is being created with subprocess, I have this exception:

```<code>d:\temp\backpack\venv\myvenv_py3.6\lib\site-packages\git\cmd.py:1011: in _call_process
    return self.execute(call, **exec_kwargs)
d:\temp\backpack\venv\myvenv_py3.6\lib\site-packages\git\cmd.py:732: in execute
    **subprocess_kwargs
D:\temp\cpython-3.6.3\Lib\subprocess.py:611: in __init__
    _cleanup()
D:\temp\cpython-3.6.3\Lib\subprocess.py:220: in _cleanup
    res = inst._internal_poll(_deadstate=sys.maxsize)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <subprocess.Popen object at 0x0000000004FD53C8>
_deadstate = 9223372036854775807
_WaitForSingleObject = <built-in function WaitForSingleObject>
_WAIT_OBJECT_0 = 0, _GetExitCodeProcess = <built-in function GetExitCodeProcess>

    def _internal_poll(self, _deadstate=None,
            _WaitForSingleObject=_winapi.WaitForSingleObject,
            _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
            _GetExitCodeProcess=_winapi.GetExitCodeProcess):
        """Check if child process has terminated.  Returns returncode
                attribute.

                This method is called by __del__, so it can only refer to objects
                in its local scope.

                """
        _log.debug('proc._internal_poll  self.pid=%s  self._handle=%s  self.returncode=%s  self=%s', self.pid, self._handle, self.returncode, self)
        if self.returncode is None:
>           if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
E           OSError: [WinError 6] The handle is invalid

D:\temp\cpython-3.6.3\Lib\subprocess.py:1051: OSError
</code>```

It doesn't matter where the subprocess call is being created from (in this project it's a lot from the GitPython package and from plumbum).

This execution occurs under this umbrella: build script which invokes venv/Scripts/coverage run -m pytest -v tests/. But I've also tried pytest-cov with venv/Scripts/pytest --cov=mypackage --cov-config .coveragerc - tests/
In terms of reproduction:

on my Win 7 PC it always passes :(

on a Win 7 virtual machine:

it always fails when [<build script> invokes venv/Scripts/coverage run -m pytest]

it always fails when coverage run -m pytest is invoked directly from the venv

but it always passes when pytest is invoked directly from the virtualenv

on a Win 10 PC it will always fails,  no matter if the the <build script> is invoked, or if  coverage or pytest are invoked directly from the venv

The only clue that I've got so far is from this StackOverflow thread: https://stackoverflow.com/a/43975118
and to be more precise, it's the comments from the first accepted answer that point to something useful related to the _cleanup method from the subprocess module.

答:
After a bit of pause, I quickly found the reason behind this.

It was because of the GitPython usage in the project which didn't call git.Repo.close() or used git.Repo as a context manager.
There is a warning about this on GitPython's readme.

It was helpful to add logging in subprocess's _internal_poll method to know which process (args) is the culprit. For GitPython it was git cat-file ...

Body:
I'm porting a project to Python3 and I'm running into a unexpected error on Windows:

Basically on Python 3.6 on Windows, each time a process is being created with subprocess, I have this exception:

d:\temp\backpack\venv\myvenv_py3.6\lib\site-packages\git\cmd.py:1011: in _call_process
    return self.execute(call, **exec_kwargs)
d:\temp\backpack\venv\myvenv_py3.6\lib\site-packages\git\cmd.py:732: in execute
    **subprocess_kwargs
D:\temp\cpython-3.6.3\Lib\subprocess.py:611: in __init__
    _cleanup()
D:\temp\cpython-3.6.3\Lib\subprocess.py:220: in _cleanup
    res = inst._internal_poll(_deadstate=sys.maxsize)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <subprocess.Popen object at 0x0000000004FD53C8>
_deadstate = 9223372036854775807
_WaitForSingleObject = <built-in function WaitForSingleObject>
_WAIT_OBJECT_0 = 0, _GetExitCodeProcess = <built-in function GetExitCodeProcess>

    def _internal_poll(self, _deadstate=None,
            _WaitForSingleObject=_winapi.WaitForSingleObject,
            _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
            _GetExitCodeProcess=_winapi.GetExitCodeProcess):
        """Check if child process has terminated.  Returns returncode
                attribute.

                This method is called by __del__, so it can only refer to objects
                in its local scope.

                """
        _log.debug('proc._internal_poll  self.pid=%s  self._handle=%s  self.returncode=%s  self=%s', self.pid, self._handle, self.returncode, self)
        if self.returncode is None:
>           if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
E           OSError: [WinError 6] The handle is invalid

D:\temp\cpython-3.6.3\Lib\subprocess.py:1051: OSError

It doesn't matter where the subprocess call is being created from (in this project it's a lot from the GitPython package and from plumbum).

This execution occurs under this umbrella: build script which invokes venv/Scripts/coverage run -m pytest -v tests/. But I've also tried pytest-cov with venv/Scripts/pytest --cov=mypackage --cov-config .coveragerc - tests/
In terms of reproduction:

on my Win 7 PC it always passes :(

on a Win 7 virtual machine:

it always fails when [<build script> invokes venv/Scripts/coverage run -m pytest]

it always fails when coverage run -m pytest is invoked directly from the venv

but it always passes when pytest is invoked directly from the virtualenv

on a Win 10 PC it will always fails,  no matter if the the <build script> is invoked, or if  coverage or pytest are invoked directly from the venv

The only clue that I've got so far is from this StackOverflow thread: https://stackoverflow.com/a/43975118
and to be more precise, it's the comments from the first accepted answer that point to something useful related to the _cleanup method from the subprocess module.


问:
Change color of span upon click
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

```<code>function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();
</code>```

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

答:
1 - JavaScript always garbing White backgrounds From HTML as null
  for Printing purpose .

so in case the background you trying to match is white

then replace :

this.style.backgroundColor === '#ffffff' ? ..... etc ;

with this :

```<code>this.style.backgroundColor === "" ? this.style.backgroundColor = 'yellow'
     : this.style.backgroundColor="#000000";
</code>```

otherways if the background your trying to match is Not white

then you can use the condition normal element === " color code here "

2 - finally as others mention add the loop in front of your span callback like this :

```<code>span[i].addEventListener('click', function(){ ... etc
</code>```

Title: Change color of span upon click

Body:
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

Body:
1 - JavaScript always garbing White backgrounds From HTML as null
  for Printing purpose .

so in case the background you trying to match is white

then replace :

this.style.backgroundColor === '#ffffff' ? ..... etc ;

with this :

this.style.backgroundColor === "" ? this.style.backgroundColor = 'yellow'
     : this.style.backgroundColor="#000000";

otherways if the background your trying to match is Not white

then you can use the condition normal element === " color code here "

2 - finally as others mention add the loop in front of your span callback like this :

span[i].addEventListener('click', function(){ ... etc


问:
Is it possible to have a single trial per device?
Is it possible to provide a service in which one free trial is given to each device without the possibility of an individual being able to get multiple free trials on a single device.  If its impossible,  do you know of a way of making it difficult to obtain multiple free trials.</p>

答:
I imagine you could get 99% of the effect of a more complex scheme with a brain-dead-simple one: just store a file somewhere on the device that indicates that the trial has expired. Granted, tech-savvy users would be able to find and remove the file, but the vast majority won't bother - the device is an inscrutable slab of magic to them, meddling with the internal files might displease the tiny gnomes peddling furiously behind the screen.

You can make things more challenging by hiding the lock file, changing the name and location based on the device id - that way it's a lot more difficult for someone to share instructions on how to evade your trial scheme.

As the other answers have noted: no system is foolproof, there is always someone out there who is cleverer than you and who will relish cracking your scheme. The trick is to not waste your time giving this guy a mental workout and instead cater for the majority.


问:
What are The Unit of measurement
I'm building an app which analysis the step of the person that wears the sensor, and I haven't found and mention in the API or the exapmle apps for what are the unit of measurement (in the linear acceleration and angular velocity).

I believe that timestamp is milliseconds (correct me if I'm wrong), but what are the others?

Thanks!

答:
Time Api returns data in uS

$ wbcmd --port com9 --op get --path Time
  {
    "response": 200,
    "responsestring": "HTTP_CODE_OK",
    "operation": "get",
    "uri": "/net/ECKIB9870DA4/Time",
    "content": 1420070440653000,
    "querytimems": 26,
    "querytimens": 26918122
  }

But Timestamp for Acc goes from the LSM6DS3 chip and it is in mS.

$ wbcmd --port com9 --op subscribe --path Meas/Acc/13
  /net/ECKIB9870DA4/Meas/Acc/13::onSubscribeResult
    Subscribed and listening for notifications. Press ESC to stop:

@191 { {
    "Timestamp": 158,
    "ArrayAcc": [
      {
        "x": -0.07657305896282196,
        "y": -0.66044265031814575,
        "z": 9.9186038970947266
      }
    ]
  } }

@255 { {
    "Timestamp": 235,
    "ArrayAcc": [
      {
        "x": -0.11485958844423294,
        "y": -0.64129936695098877,
        "z": 9.9377470016479492
      }
    ]
  } }

@383 { {
    "Timestamp": 312,
    "ArrayAcc": [
      {
        "x": -0.052643977105617523,
        "y": -0.6341206431388855,
        "z": 9.9329614639282227
      }
    ]
  } }

You have to know that LSM chip doesn't have any good clock. So real timestamp can drift a little (depends on temperature) like +-2%.

Title: What are The Unit of measurement


问:
Build "WPF application" as x86 and x64 at same build event
Requirement:
An existing WPF application is built as x64 exe, The requirement is to build it as a x86 exe as well. I should not configure it to build as "Any CPU". The build event should generate "x86" and "x64" executables.

Tried:
I have created a new WPF project which targets x86 platform and added the files from the existing project using "Add as link", which would prevent multiple copies of the same files.

Problem with this approach: Since it is a WPF project it links *.xaml.cs to corresponding *.xaml, When i add these files using "Add as link", *.xaml.cs is not under the corresponding *.xaml. Therefore it does not build the x86 executable. This would have worked if the project did not contain any xaml files which is evident from multiple answers given in stackoverflow.

Finally, Is there a way that i can build a "WPF application" as x86 and x64 in the same build event?
am i missing something in the approach i have tried?

答:
The recommended approach to solve this is to using build configurations and platforms. When building a project, a set of configuration parameters is used. You can not only have one configuration but as many as you like. Usually, a project is generated with a Debug and a Release configuration.

In addition, you can also define platforms that contain the parameters that are relevant for a specific platform. A WPF project is initially generated with the "Any CPU" platform, but you can easily add platforms that fit your needs.

When building a project, a configuration and a platform is selected. If you want to build for two platforms, you should build twice and change the platform for the second build.

The starting point to configure build configurations and platforms is the configuration manager (Menu Build -> Configuration Manager). You can use this dialog to create build configurations and platforms and choose which project configurations are used when building a specific solution configuration.

After you have set up the required configurations and platforms, you can change the settings in the project properties. At the top of the window you can select the build configuration and platform that you are editing.


问:
Reset Variable Counter after a fresh AJAX request. JavaScript/jQuery
Sorry If this Question is Trivial!! Well, I've a Page where I'm loading contents with AJAX.

Main Page (index.html):

```<code><a href="#" id="loadContent">Load Remote Page</a>

<div id="ajaxContent">

//Loads AJAX contents Here!!

</div>
</code>```

Remote Page (remote.html):

```<code><h2 id="counter"></h2>
<button class="counterPlus" type="button">++</button>
</code>```

jQuery (script.js):

```<code>$("#loadContent").on("click", function(){

        $.ajax({
                url: "remote.html",
                type: "GET",
                success: function(data){
                          $("#ajaxContent").html(data);
                }
        })

});

var counter = 1;
$("#ajaxContent").on("click", ".counterPlus", function(){
    console.log(counter);
    counter = counter + 1;
    $("#counter").text(counter);
});
</code>```

On clicking the link in the Loaded page, I can see incremented value but the problem is Counter is not resetting After a fresh AJAX load (Click on the Link). I'm aware that old Variable value stays in Memory But What is the Solution to reset the Counter in this kinda Problem??

答:
That's because your variable counter has global scope.

Just reset it inside the success callback function of ajax call.

```<code>var counter = 1;
$("#loadContent").on("click", function(){

    $.ajax({
            url: "remote.html",
            type: "GET",
            success: function(data){
                      counter = 1;
                      $("#ajaxContent").html(data);
            }
    })
});

$("#ajaxContent").on("click", ".counterPlus", function(){
    console.log(counter);
    counter = counter + 1;
    $("#counter").text(counter);
});
</code>```

Body:
Sorry If this Question is Trivial!! Well, I've a Page where I'm loading contents with AJAX.

Main Page (index.html):

Load Remote Page

//Loads AJAX contents Here!!

Remote Page (remote.html):

<button class="counterPlus" type="button">++</button>

jQuery (script.js):

$("#loadContent").on("click", function(){

        $.ajax({
                url: "remote.html",
                type: "GET",
                success: function(data){
                          $("#ajaxContent").html(data);
                }
        })

});

var counter = 1;
$("#ajaxContent").on("click", ".counterPlus", function(){
    console.log(counter);
    counter = counter + 1;
    $("#counter").text(counter);
});

On clicking the link in the Loaded page, I can see incremented value but the problem is Counter is not resetting After a fresh AJAX load (Click on the Link). I'm aware that old Variable value stays in Memory But What is the Solution to reset the Counter in this kinda Problem??

Body:
That's because your variable counter has global scope.

Just reset it inside the success callback function of ajax call.

var counter = 1;
$("#loadContent").on("click", function(){

    $.ajax({
            url: "remote.html",
            type: "GET",
            success: function(data){
                      counter = 1;
                      $("#ajaxContent").html(data);
            }
    })
});

$("#ajaxContent").on("click", ".counterPlus", function(){
    console.log(counter);
    counter = counter + 1;
    $("#counter").text(counter);
});


答:
Dictionaries are unordered data structures, and dict.keys() returns a View object, not a list so a simple comparison of the keys against a list won't work. Fortunately, the View object is set-like, and you can use set operations on it. For example,

```<code>loc = {
    'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206,
    'name': "SNU",  'keywords':["school, hard"],
}

print(loc.keys() == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'})
</code>```

output

```<code>True
</code>```

In CPython 3.6+ dicts do retain insertion order, but that's currently an implementation detail, and we aren't supposed to rely on it. But apart from that, the dict's items may have been inserted in any order, so it's not a good idea to assume that the keys will be in a particular order.

Title: How to check identical of dictionary key values?

Body:
Dictionaries are unordered data structures, and dict.keys() returns a View object, not a list so a simple comparison of the keys against a list won't work. Fortunately, the View object is set-like, and you can use set operations on it. For example,

loc = {
    'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206,
    'name': "SNU",  'keywords':["school, hard"],
}

print(loc.keys() == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'})

output

True

In CPython 3.6+ dicts do retain insertion order, but that's currently an implementation detail, and we aren't supposed to rely on it. But apart from that, the dict's items may have been inserted in any order, so it's not a good idea to assume that the keys will be in a particular order.


答:
In Python 3, .keys returns a view that behaves just like a set. You just need to change 2 characters - the brackets - to make your list literal into a set literal:

```<code>>>> loc = {'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206,
'name': "SNU",  'keywords':["school, hard"],}
>>> loc.keys() == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'}
True
</code>```

IF you want to ensure that the dictionary has at least these keys, use .issubset / .issuperset. Unfortunately the key view does not have these method so you need to use it on the set. For example

```<code>>>> {'latitude', 'longitude'}.issubset(loc.keys())
True
>>> {'latitude', 'foobar'}.issubset(loc.keys())
False
</code>```

Note that you don't even need to use .keys() in this case:

```<code>>>> {'latitude', 'longitude'}.issubset(loc)
True
</code>```

Body:
Hi I am trying to do simple task of Python whether the dictionary's keys are equal or not.
here is my example code

loc = {'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206, 'name': "SNU",  'keywords':["school, hard"],}

This is my example data. And if I print out the loc's key values, then I got...

print(loc.keys())

Print: dict_keys(['latitude', 'longitude', 'timestamp', 'name', 'keywords'])

So what I wanted to do is checking whether the data is same as dictionary's key or not. I use this but it does not work at all....

print(loc.keys() == ['latitude', 'longitude', 'timestamp', 'name', 'keywords'])

This still gets me False. Is there any other way that I can make this into false?

Body:
In Python 3, .keys returns a view that behaves just like a set. You just need to change 2 characters - the brackets - to make your list literal into a set literal:

>>> loc = {'latitude' :-90.0, 'longitude' : -180.0, 'timestamp': 1512531206,
'name': "SNU",  'keywords':["school, hard"],}
>>> loc.keys() == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'}
True

IF you want to ensure that the dictionary has at least these keys, use .issubset / .issuperset. Unfortunately the key view does not have these method so you need to use it on the set. For example

>>> {'latitude', 'longitude'}.issubset(loc.keys())
True
>>> {'latitude', 'foobar'}.issubset(loc.keys())
False

Note that you don't even need to use .keys() in this case:

>>> {'latitude', 'longitude'}.issubset(loc)
True


问:
sql server 2012 offset return same record
I have a strange problem with SQL Server 2012.

I use a query like this

```<code>SELECT * FROM table ORDER BY field OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY
</code>```

Every time I use this query from 0 to 25, 25 to 50, 50 to 75, 75 to 100, it returns the same 25 records.

When I use it with 100 to 125, it returns the original 25 to 50 etc...

My table contains only 197 records and this happens only with one table of my database. All other tables work correctly.

This also happens when I use the query via code (ASP.NET C#) and from SQL Management Studio directly.

答:
I had the same issue: the query always returned the same rows independently on the Offset value (30):

```<code>OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY
</code>```

For me this comment by veljasije is the correct answer:

Weird, maybe your column in ORDER BY is not deterministic, and make
problem. Can field column can contain duplicates? If so, add primary
key column in ORDER BY clause, after field column.

I solved this issue by adding [ID] column into Order By:

```<code>ORDER BY [Status], [ID] ASC
</code>```

Body:
I have a strange problem with SQL Server 2012.

I use a query like this

SELECT * FROM table ORDER BY field OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY

Every time I use this query from 0 to 25, 25 to 50, 50 to 75, 75 to 100, it returns the same 25 records.

When I use it with 100 to 125, it returns the original 25 to 50 etc...

My table contains only 197 records and this happens only with one table of my database. All other tables work correctly.

This also happens when I use the query via code (ASP.NET C#) and from SQL Management Studio directly.

Body:
I had the same issue: the query always returned the same rows independently on the Offset value (30):

OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY

For me this comment by veljasije is the correct answer:

Weird, maybe your column in ORDER BY is not deterministic, and make
problem. Can field column can contain duplicates? If so, add primary
key column in ORDER BY clause, after field column.

I solved this issue by adding [ID] column into Order By:

ORDER BY [Status], [ID] ASC

ContentLicense: CC BY-SA 4.0


问:
Pop the Proxy Authentication dialog when a proxy challenge provides a 407 response with a Proxy-Authenticate header
In my App I've configured a proxy for the NSURLSessionConfiguration object so the App can use the proxy. When the proxy requires authentication, the App will ask for username and password via the delegate method "URLSession:task:didReceiveChallenge:completionHandler:" and makes sure that the request can continue.

Normal in HTTP requests, but the HTTPS requests popup a dialog stating the  proxy authentication is required and gives the user the choice to do this "later" or directly go to the system settings.

In addition, the dialog pops up even before the delegate method "didReceiveChallenge" of the NSUrlSession above, the application does not get an opportunity to provide credentials before iOS displays it.

Does anyone else seeing this and knows how to fix this?

proxy server response header:

HTTP/1.1 407 Proxy Authentication Required

Content-Type: text/html

X-Squid-Error: ERR_CACHE_ACCESS_DENIED 0

Proxy-Authenticate: Basic realm="Basic"

Proxy-Authenticate: Digest realm="Digest",
nonce="xxxxxxxxxxxxxxxxxxxxxxxxxxx", qop="auth", stale=false

X-Cache: MISS from proxy.xxxx.com

Via: 1.1 proxy.xxxx.com

my demo code:

```<code>    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.connectionProxyDictionary = @{
                                     @"HTTPEnable" : @(1),
                                     (NSString *)kCFStreamPropertyHTTPProxyHost  : @"proxy.xxxx.com",
                                     (NSString *)kCFStreamPropertyHTTPProxyPort  : @(1234),
                                     @"HTTPSEnable": @(1),
                                     (NSString *)kCFStreamPropertyHTTPSProxyHost :@"proxy.xxxx.com",
                                     (NSString *)kCFStreamPropertyHTTPSProxyPort : @(4321)
                                    };

self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.xxxxx.com"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
NSURLSessionTask  *task =  [self.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSLog(@"result:%@  error: %@",data, error.description);
}];
[task resume];
</code>```

#pragma mark - NSURLSessionTaskDelegate

```<code>- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)taskdidReceiveChallenge:(NSURLAuthenticationChallenge *)challengecompletionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
NSLog(@"task:%@",challenge.protectionSpace.authenticationMethod);
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest) {
    NSURLCredential *cren = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
    if (completionHandler) {
        completionHandler(NSURLSessionAuthChallengeUseCredential,cren);
    }
}
</code>```

}

答:
I found the solution here.It seems like such problems are bugs.Instead of using the URLSession:task:didReceiveChallenge:completionHandler: delegate, a good workaround is to add a "Proxy-Authorization" header to the NSURLSessionConfiguration.Here is the code based on here:</p>

```<code>// 1 - define credentials as a string with format:
//    "username:password"
//
NSString *username = @"USERID";
NSString *password = @"SECRET";
NSString *authString = [NSString stringWithFormat:@"%@:%@",
                        username,
                        password];

// 2 - convert authString to an NSData instance
NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding];

// 3 - build the header string with base64 encoded data
NSString *authHeader = [NSString stringWithFormat: @"Basic %@",
                        [authData base64EncodedStringWithOptions:0]];

// 4 - create an NSURLSessionConfiguration instance
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];

// 5 - add custom headers, including the Authorization header
[configuration setHTTPAdditionalHeaders:@{
                                          @"Proxy-Authorization": authHeader
                                          }
 ];

// 6 - set proxy dictionary
NSDictionary *proxyDict = @{
                            @"HTTPEnable"  : @1,
                            (NSString *)kCFStreamPropertyHTTPProxyHost  : @"ip",
                            (NSString *)kCFStreamPropertyHTTPProxyPort  : proxyPortNumber,

                            @"HTTPSEnable" : @1,
                            (NSString *)kCFStreamPropertyHTTPSProxyHost : @"ip",
                            (NSString *)kCFStreamPropertyHTTPSProxyPort : proxyPortNumber,

                            };
configuration.connectionProxyDictionary = proxyDict;

// 7 - create an NSURLSession instance
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:operationQueue];
</code>```

Body:
In my App I've configured a proxy for the NSURLSessionConfiguration object so the App can use the proxy. When the proxy requires authentication, the App will ask for username and password via the delegate method "URLSession:task:didReceiveChallenge:completionHandler:" and makes sure that the request can continue.

Normal in HTTP requests, but the HTTPS requests popup a dialog stating the  proxy authentication is required and gives the user the choice to do this "later" or directly go to the system settings.

In addition, the dialog pops up even before the delegate method "didReceiveChallenge" of the NSUrlSession above, the application does not get an opportunity to provide credentials before iOS displays it.

Does anyone else seeing this and knows how to fix this?

proxy server response header:

HTTP/1.1 407 Proxy Authentication Required

Content-Type: text/html

X-Squid-Error: ERR_CACHE_ACCESS_DENIED 0

Proxy-Authenticate: Basic realm="Basic"

Proxy-Authenticate: Digest realm="Digest",
nonce="xxxxxxxxxxxxxxxxxxxxxxxxxxx", qop="auth", stale=false

X-Cache: MISS from proxy.xxxx.com

Via: 1.1 proxy.xxxx.com

my demo code:

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.connectionProxyDictionary = @{
                                     @"HTTPEnable" : @(1),
                                     (NSString *)kCFStreamPropertyHTTPProxyHost  : @"proxy.xxxx.com",
                                     (NSString *)kCFStreamPropertyHTTPProxyPort  : @(1234),
                                     @"HTTPSEnable": @(1),
                                     (NSString *)kCFStreamPropertyHTTPSProxyHost :@"proxy.xxxx.com",
                                     (NSString *)kCFStreamPropertyHTTPSProxyPort : @(4321)
                                    };

self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.xxxxx.com"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
NSURLSessionTask  *task =  [self.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSLog(@"result:%@  error: %@",data, error.description);
}];
[task resume];

#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)taskdidReceiveChallenge:(NSURLAuthenticationChallenge *)challengecompletionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
NSLog(@"task:%@",challenge.protectionSpace.authenticationMethod);
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest) {
    NSURLCredential *cren = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
    if (completionHandler) {
        completionHandler(NSURLSessionAuthChallengeUseCredential,cren);
    }
}

}

Body:
I found the solution here.It seems like such problems are bugs.Instead of using the URLSession:task:didReceiveChallenge:completionHandler: delegate, a good workaround is to add a "Proxy-Authorization" header to the NSURLSessionConfiguration.Here is the code based on here:

// 1 - define credentials as a string with format:
//    "username:password"
//
NSString *username = @"USERID";
NSString *password = @"SECRET";
NSString *authString = [NSString stringWithFormat:@"%@:%@",
                        username,
                        password];

// 2 - convert authString to an NSData instance
NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding];

// 3 - build the header string with base64 encoded data
NSString *authHeader = [NSString stringWithFormat: @"Basic %@",
                        [authData base64EncodedStringWithOptions:0]];

// 4 - create an NSURLSessionConfiguration instance
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];

// 5 - add custom headers, including the Authorization header
[configuration setHTTPAdditionalHeaders:@{
                                          @"Proxy-Authorization": authHeader
                                          }
 ];

// 6 - set proxy dictionary
NSDictionary *proxyDict = @{
                            @"HTTPEnable"  : @1,
                            (NSString *)kCFStreamPropertyHTTPProxyHost  : @"ip",
                            (NSString *)kCFStreamPropertyHTTPProxyPort  : proxyPortNumber,

                            @"HTTPSEnable" : @1,
                            (NSString *)kCFStreamPropertyHTTPSProxyHost : @"ip",
                            (NSString *)kCFStreamPropertyHTTPSProxyPort : proxyPortNumber,

                            };
configuration.connectionProxyDictionary = proxyDict;

// 7 - create an NSURLSession instance
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:operationQueue];


问:
question on tomcat for serving of webapps and web-inf

There is a project deployed in Tomcat.

The web-app of course in is webapps of tomcat and the structure is as follows:

```<code>tomcat-home
|--webapps
       |
        -MyProject
                 |
                  -WEB-INF
                  -startingPoint.js
                  -client
                  -other dirs etc
</code>```

Now startingPoint.js is a javascript file that essentially loads an applet in the browser and is similar to this:

```<code>document.write('<OBJECT ');
document.write('  codebase = "jre.exe" WIDTH = "100%" HEIGHT = "100%" MAYSCRIPT > ');
document.write('  <PARAM NAME = CODE VALUE = "com/AnApplet.class" > ');
document.write('  <PARAM NAME = CODEBASE VALUE = "/MyProject/client/classes" >');
document.write('  <PARAM NAME = ARCHIVE VALUE = "/MyProject/client/lib/Appletclient.jar"> ');
document.write('  <PARAM NAME = "type" VALUE = "application/x-java-applet;version=1.6"> ');
document.write('  <PARAM NAME = "MAYSCRIPT" VALUE="true"> ');
etc.
</code>```

If I write in the IE url bar the url:

http://ip:port/MyProject  (tomcat is running of course) the applet is loaded in my browser but I can not understand how.

I mean from web.xml I can not see something that would serve the javascript file.

If a js file is in the roor directory of my project, does it get automatically served?

I feel I am missing something here.

Could someone please advice, what is it here I should be looking for?

Thanks

答:
The index.jsp (or any file configured in the <welcome-file-list> located in the root of the web application is served by default.

If you don't have such a file, it depends on another settings whether to show a listing of the directory, or deny access.

Body:
There is a project deployed in Tomcat.

The web-app of course in is webapps of tomcat and the structure is as follows:

tomcat-home
|--webapps
       |
        -MyProject
                 |
                  -WEB-INF
                  -startingPoint.js
                  -client
                  -other dirs etc

Now startingPoint.js is a javascript file that essentially loads an applet in the browser and is similar to this:

document.write('<OBJECT ');
document.write('  codebase = "jre.exe" WIDTH = "100%" HEIGHT = "100%" MAYSCRIPT > ');
document.write('  <PARAM NAME = CODE VALUE = "com/AnApplet.class" > ');
document.write('  <PARAM NAME = CODEBASE VALUE = "/MyProject/client/classes" >');
document.write('  <PARAM NAME = ARCHIVE VALUE = "/MyProject/client/lib/Appletclient.jar"> ');
document.write('  <PARAM NAME = "type" VALUE = "application/x-java-applet;version=1.6"> ');
document.write('  <PARAM NAME = "MAYSCRIPT" VALUE="true"> ');
etc.

If I write in the IE url bar the url:

http://ip:port/MyProject  (tomcat is running of course) the applet is loaded in my browser but I can not understand how.

I mean from web.xml I can not see something that would serve the javascript file.

If a js file is in the roor directory of my project, does it get automatically served?

I feel I am missing something here.

Could someone please advice, what is it here I should be looking for?

Thanks


问:
How define style in App.xaml Xamarin Forms for CustomButton?
How I can define style in App.xaml for CustomButton?

App.xaml

```<code> <Style x:Key="CustomButtonSmall" TargetType="CustomButton">
     <Setter Property="FontSize" Value="14" />
 </Style>
</code>```

MyPage.xaml

```<code><local:CustomButton Text="{i18n:Translate CreateAccountButton}"
      Grid.Column="0" Command="{Binding CreateAccountCommand}"
      Type="Normal" Style="{StaticResource CustomButtonSmall}" />
</code>```

答:
In App.xaml

Give CustomButton whole path like TargetType="Control:CustomButton"
and define Control at the top like

```<code> xmlns:Control="clr-namespace:xyz"

 <Style x:Key="CustomButtonSmall" TargetType="Control:CustomButton">
            <Setter Property="FontSize" Value="14" />
        </Style>
</code>```

Body:
How I can define style in App.xaml for CustomButton?

App.xaml

MyPage.xaml

<local:CustomButton Text="{i18n:Translate CreateAccountButton}"
      Grid.Column="0" Command="{Binding CreateAccountCommand}"
      Type="Normal" Style="{StaticResource CustomButtonSmall}" />

Body:
In App.xaml

Give CustomButton whole path like TargetType="Control:CustomButton"
and define Control at the top like

 xmlns:Control="clr-namespace:xyz"

 <Style x:Key="CustomButtonSmall" TargetType="Control:CustomButton">
            <Setter Property="FontSize" Value="14" />
        </Style>


问:
On click function in vue-tables-2 throwing fns.apply is not a function
I'm currently implementing vue-tables-2 (first time) and I've set up a template to show an icon that will fire an event when clicked. However, I'm getting an error that I'm not sure where it's deriving from. The error is the following.

```<code>Uncaught TypeError: fns.apply is not a function
at HTMLAnchorElement.invoker (vue.esm.js:1821)

templates: {
      edit: function (h, row) {
        return <a href='javascript:void(0);' on-click='$parent.editSchedulesBtn(${row.id})' ><i class='fa fa-pencil-square fa-2x' aria-hidden="true"></i></a>
      }
</code>```

The function code itself is as follows.

```<code>editSchedulesBtn: function (rowId) {
  console.log(rowId)
}
</code>```

I have found this stackoverflow question have tried implementing it, but no success --> How to bind vue click event with vue tables 2 (JSX)?

Thanks for all assistance in advance.

答:
I see a few problems:

A syntax error:

Instead of

```<code> edit: function (h, row) {
        return <a href='javascript:void(0);' on-click='$parent.editSchedulesBtn(${row.id})' ><i class='fa fa-pencil-square fa-2x' aria-hidden="true"></i></a>
      }
</code>```

Should be:

```<code> edit: function (h, row) {
        return <a href='javascript:void(0);' on-click={this.$parent.editSchedulesBtn(row.id)}><i class='fa fa-pencil-square fa-2x' aria-hidden="true"></i></a>
      }
</code>```

Secondly, the this context inside the function refers to the root vue instance, as stated in the docs:

In addition a this context will be available, which refers to the root
  vue instance.

So the $parent is obsolete. You might even have to use $children or $refs, depending on your app structure (Explore the tree using the chrome dev tools and you will find the exact "address").

Thirdly, when binding an event with jsx you should not call the method directly, but use the bind method instead (As explained in the answer you have attached):

```<code>on-click={this.editSchedulesBtn.bind(this, row.id)} // See the aforementioned answer for ES6 syntax
</code>```

As an aside, since Vue introduced scoped slots in v2.1, it is best to use those rather than jsx, which requires compilation, and is generally more cumbersome to deal with.

Body:
I'm currently implementing vue-tables-2 (first time) and I've set up a template to show an icon that will fire an event when clicked. However, I'm getting an error that I'm not sure where it's deriving from. The error is the following.

Uncaught TypeError: fns.apply is not a function
at HTMLAnchorElement.invoker (vue.esm.js:1821)

templates: {
      edit: function (h, row) {
        return
      }

The function code itself is as follows.

editSchedulesBtn: function (rowId) {
  console.log(rowId)
}

I have found this stackoverflow question have tried implementing it, but no success --> How to bind vue click event with vue tables 2 (JSX)?

Thanks for all assistance in advance.

Body:
I see a few problems:

A syntax error:

Instead of

 edit: function (h, row) {
        return <a href='javascript:void(0);' on-click='$parent.editSchedulesBtn(${row.id})' ><i class='fa fa-pencil-square fa-2x' aria-hidden="true"></i></a>
      }

Should be:

 edit: function (h, row) {
        return <a href='javascript:void(0);' on-click={this.$parent.editSchedulesBtn(row.id)}><i class='fa fa-pencil-square fa-2x' aria-hidden="true"></i></a>
      }

Secondly, the this context inside the function refers to the root vue instance, as stated in the docs:

In addition a this context will be available, which refers to the root
  vue instance.

So the $parent is obsolete. You might even have to use $children or $refs, depending on your app structure (Explore the tree using the chrome dev tools and you will find the exact "address").

Thirdly, when binding an event with jsx you should not call the method directly, but use the bind method instead (As explained in the answer you have attached):

on-click={this.editSchedulesBtn.bind(this, row.id)} // See the aforementioned answer for ES6 syntax

As an aside, since Vue introduced scoped slots in v2.1, it is best to use those rather than jsx, which requires compilation, and is generally more cumbersome to deal with.


问:
Extends Session Token ExpiresAt
I wanted to create a cloud code function that help me change the date of the ExpiresAt Field value of Session Token in Parse Server. Is there any way for doing this? or any API that I can refer to?

Thank you.

答:
Ends up I answer my own question. After sometimes, I found that I can create a CloudCode Function as below for extending Session Token, HOpe this helps others.

```<code>Parse.Cloud.define("extendSessionToken", function(request, response)
{
    req({
        method: 'GET',
        url: process.env.SERVER_URL + "/sessions/me",
        headers:
        {
            'X-Parse-Application-Id': process.env.APP_ID,
            'X-Parse-REST-API-Key': process.env.REST_API_KEY,
            'X-Parse-Session-Token': request.headers["x-parse-session-token"],
            'X-Parse-Master-Key' : process.env.MASTER_KEY
        }
    }, function (error, httpResponse, body)
    {
        var jsonBody = JSON.parse(body);
        DLog.info(JSON.stringify(jsonBody));
        if(error)
        {
            handleResponseReturn(response, 1, error);
        }
        else if(jsonBody.error)
        {
            handleResponseReturn(response, 1, jsonBody.error);
        }
        else
        {
            var newSessionYear = new Date();
            newSessionYear.setFullYear(newSessionYear.getFullYear() + 1);
            var newSessionBody = {
                'expiresAt': Parse._encode(newSessionYear)
            }

            DLog.info("New ExpiresAt: " + JSON.stringify(newSessionBody));
            req({
                    method: 'PUT',
                    url: process.env.SERVER_URL + "/sessions/" + jsonBody.objectId,
                    headers:
                    {
                        'X-Parse-Application-Id': process.env.APP_ID,
                        'X-Parse-REST-API-Key': process.env.REST_API_KEY,
                        'Content-Type': 'application/json;charset=utf-8',
                        'X-Parse-Session-Token': request.headers["x-parse-session-token"],
                        'X-Parse-Master-Key' : process.env.MASTER_KEY
                    },
                    body:  JSON.stringify(newSessionBody)
                }, function (error, httpResponse, body)
                {
                    var jsonResult = JSON.parse(body);
                    if(error)
                        handleResponseReturn(response, 1, error);
                    else if(jsonBody.error)
                        handleResponseReturn(response, 1, jsonBody.error);
                    else
                        handleResponseReturn(response, 0, body);
                });
        }
    });
});
</code>```

Hope this helps those who are facing the same problems. Feel free to take this and modify as you like.

Title: Extends Session Token ExpiresAt

Body:
Ends up I answer my own question. After sometimes, I found that I can create a CloudCode Function as below for extending Session Token, HOpe this helps others.

Parse.Cloud.define("extendSessionToken", function(request, response)
{
    req({
        method: 'GET',
        url: process.env.SERVER_URL + "/sessions/me",
        headers:
        {
            'X-Parse-Application-Id': process.env.APP_ID,
            'X-Parse-REST-API-Key': process.env.REST_API_KEY,
            'X-Parse-Session-Token': request.headers["x-parse-session-token"],
            'X-Parse-Master-Key' : process.env.MASTER_KEY
        }
    }, function (error, httpResponse, body)
    {
        var jsonBody = JSON.parse(body);
        DLog.info(JSON.stringify(jsonBody));
        if(error)
        {
            handleResponseReturn(response, 1, error);
        }
        else if(jsonBody.error)
        {
            handleResponseReturn(response, 1, jsonBody.error);
        }
        else
        {
            var newSessionYear = new Date();
            newSessionYear.setFullYear(newSessionYear.getFullYear() + 1);
            var newSessionBody = {
                'expiresAt': Parse._encode(newSessionYear)
            }

            DLog.info("New ExpiresAt: " + JSON.stringify(newSessionBody));
            req({
                    method: 'PUT',
                    url: process.env.SERVER_URL + "/sessions/" + jsonBody.objectId,
                    headers:
                    {
                        'X-Parse-Application-Id': process.env.APP_ID,
                        'X-Parse-REST-API-Key': process.env.REST_API_KEY,
                        'Content-Type': 'application/json;charset=utf-8',
                        'X-Parse-Session-Token': request.headers["x-parse-session-token"],
                        'X-Parse-Master-Key' : process.env.MASTER_KEY
                    },
                    body:  JSON.stringify(newSessionBody)
                }, function (error, httpResponse, body)
                {
                    var jsonResult = JSON.parse(body);
                    if(error)
                        handleResponseReturn(response, 1, error);
                    else if(jsonBody.error)
                        handleResponseReturn(response, 1, jsonBody.error);
                    else
                        handleResponseReturn(response, 0, body);
                });
        }
    });
});

Hope this helps those who are facing the same problems. Feel free to take this and modify as you like.


问:
Does assembler code compiled on a 32bit machine differ from code compiled with "gcc -m32"?
I'm learnin about assembler language right now. The code examples in the book I'm learning from are all compiled on a x86 32bit machine (i think) with gcc. To match my outputs with the one from the book i compiled my simple helloworld.c with "gcc -m32".

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

int main(){
    int i;
    for(i=0;i<10;i++){
      printf("Hello World!\n");
    }
    return 0;
}
</code>```

The output i get from running "objdump -D a32.out | grep -A20 main.:" looks like this:

```<code>0000051d <main>:
51d:    8d 4c 24 04             lea    0x4(%esp),%ecx
521:    83 e4 f0                and    $0xfffffff0,%esp
524:    ff 71 fc                pushl  -0x4(%ecx)
527:    55                      push   %ebp
528:    89 e5                   mov    %esp,%ebp
52a:    53                      push   %ebx
52b:    51                      push   %ecx
52c:    83 ec 10                sub    $0x10,%esp
52f:    e8 ec fe ff ff          call   420 <__x86.get_pc_thunk.bx>
534:    81 c3 cc 1a 00 00       add    $0x1acc,%ebx
53a:    c7 45 f4 00 00 00 00    movl   $0x0,-0xc(%ebp)
541:    eb 16                   jmp    559 <main+0x3c>
543:    83 ec 0c                sub    $0xc,%esp
546:    8d 83 f0 e5 ff ff       lea    -0x1a10(%ebx),%eax
54c:    50                      push   %eax
54d:    e8 5e fe ff ff          call   3b0 <puts@plt>
552:    83 c4 10                add    $0x10,%esp
555:    83 45 f4 01             addl   $0x1,-0xc(%ebp)
559:    83 7d f4 09             cmpl   $0x9,-0xc(%ebp)
55d:    7e e4                   jle    543 <main+0x26>
</code>```

But in the book it looks like this:

It misses the first three lines from the output I get and doesn't look anything like it except for the next two lines. Why is that ? And how can i change my compiler/disassembly settings to make it look alike ?

答:
The same version of gcc configured the same way, running with gcc -m32, should be the same whether it's running on an x86-64 host or an i386 host.  Or cross-compiling from an ARM host!

The difference is gcc version and default settings.  (@Employed Russian points out that the major one is that -fpie is on by default in your gcc.  Related: 32-bit absolute addresses no longer allowed in x86-64 Linux?)  It's kinda bad that PIE is on by default for 32-bit code, too, not just 64, because the extra overhead is much more significant in 32-bit mode (no RIP-relative addressing.)

Besides config stuff like -fno-pie, different versions of gcc produce different code.

Anyway, if you really want to match what's in the book, try the same version of gcc they used.  (Hopefully they mention that?  If not, look at the year it was published for a rough hint).  You can try every gcc version back as far as 4.4 on http://gcc.godbolt.org/.

Here's a link to your sample code on Godbolt with compiler asm output and disassembly of the binary in two separate output panes, both with optimization disabled.

Note that Matt Godbolt configures gcc without the default-pie config, but you could use -fpie to get asm like you get on your desktop.

Note that with un-optimized code, it's more dependent on gcc's internals than if you'd enabled optimization.  i.e. -O0 kind of gives you a peek under the hood of how gcc "thinks about" your program, because it doesn't even try to optimize.  (Plus it spills/reloads between every statement to support changing variables with a debugger; this is part of why it's so slow: it's purposely strapping a ball and chain to your code.  All this extra storing / reloading makes it harder to read; I usually look at -O2 or -O3 output.  See also How to remove "noise" from GCC/clang assembly output?)

Body:
I'm learnin about assembler language right now. The code examples in the book I'm learning from are all compiled on a x86 32bit machine (i think) with gcc. To match my outputs with the one from the book i compiled my simple helloworld.c with "gcc -m32".

#include <stdio.h>

int main(){
    int i;
    for(i=0;i<10;i++){
      printf("Hello World!\n");
    }
    return 0;
}

The output i get from running "objdump -D a32.out | grep -A20 main.:" looks like this:

0000051d :
51d:    8d 4c 24 04             lea    0x4(%esp),%ecx
521:    83 e4 f0                and    $0xfffffff0,%esp
524:    ff 71 fc                pushl  -0x4(%ecx)
527:    55                      push   %ebp
528:    89 e5                   mov    %esp,%ebp
52a:    53                      push   %ebx
52b:    51                      push   %ecx
52c:    83 ec 10                sub    $0x10,%esp
52f:    e8 ec fe ff ff          call   420 <__x86.get_pc_thunk.bx>
534:    81 c3 cc 1a 00 00       add    $0x1acc,%ebx
53a:    c7 45 f4 00 00 00 00    movl   $0x0,-0xc(%ebp)
541:    eb 16                   jmp    559
543:    83 ec 0c                sub    $0xc,%esp
546:    8d 83 f0 e5 ff ff       lea    -0x1a10(%ebx),%eax
54c:    50                      push   %eax
54d:    e8 5e fe ff ff          call   3b0 <puts@plt>
552:    83 c4 10                add    $0x10,%esp
555:    83 45 f4 01             addl   $0x1,-0xc(%ebp)
559:    83 7d f4 09             cmpl   $0x9,-0xc(%ebp)
55d:    7e e4                   jle    543

But in the book it looks like this:

It misses the first three lines from the output I get and doesn't look anything like it except for the next two lines. Why is that ? And how can i change my compiler/disassembly settings to make it look alike ?

Body:
The same version of gcc configured the same way, running with gcc -m32, should be the same whether it's running on an x86-64 host or an i386 host.  Or cross-compiling from an ARM host!

The difference is gcc version and default settings.  (@Employed Russian points out that the major one is that -fpie is on by default in your gcc.  Related: 32-bit absolute addresses no longer allowed in x86-64 Linux?)  It's kinda bad that PIE is on by default for 32-bit code, too, not just 64, because the extra overhead is much more significant in 32-bit mode (no RIP-relative addressing.)

Besides config stuff like -fno-pie, different versions of gcc produce different code.

Anyway, if you really want to match what's in the book, try the same version of gcc they used.  (Hopefully they mention that?  If not, look at the year it was published for a rough hint).  You can try every gcc version back as far as 4.4 on http://gcc.godbolt.org/.

Here's <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Cstdio.h%3E%0A%0Aint+main()%7B%0A++++int+i%3B%0A++++for(i%3D0%3Bi%3C10%3Bi%2B%2B)%7B%0A++++++printf(%22Hello+World!!%5Cn%22)%3B%0A++++%7D%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:30.082742316784874,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((g:!((g:!((h:compiler,i:(compiler:g447,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'1'),fontScale:0.8957951999999999,libs:!(),options:'-O0+-m32+-fverbose-asm',source:1),l:'5',n:'0',o:'x86-64+gcc+4.4.7+(Editor+%231,+Compiler+%231)',t:'0')),k:50,l:'4',m:74.75247524752476,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1),l:'5',n:'0',o:'%231+with+x86-64+gcc+4.4.7',t:'0')),header:(),l:'4',m:25.247524752475247,n:'0',o:'',s:0,t:'0')),k:50,l:'3',n:'0',o:'',t:'0'),(g:!((h:compiler,i:(compiler:g447,filters:(b:'0',binary:'0',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'1'),fontScale:0.8957951999999999,libs:!(),options:'-O0+-m32+-fverbose-asm',source:1),l:'5',n:'0',o:'x86-64+gcc+4.4.7+(Editor+%231,+Compiler+%232)',t:'0')),header:(),k:50,l:'4',n:'0',o:'',s:0,t:'0')),k:69.91725768321513,l:'2',m:100,n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">a link to your sample code on Godbolt with compiler asm output and disassembly of the binary in two separate output panes, both with optimization disabled.

Note that Matt Godbolt configures gcc without the default-pie config, but you could use -fpie to get asm like you get on your desktop.

Note that with un-optimized code, it's more dependent on gcc's internals than if you'd enabled optimization.  i.e. -O0 kind of gives you a peek under the hood of how gcc "thinks about" your program, because it doesn't even try to optimize.  (Plus it spills/reloads between every statement to support changing variables with a debugger; this is part of why it's so slow: it's purposely strapping a ball and chain to your code.  All this extra storing / reloading makes it harder to read; I usually look at -O2 or -O3 output.  See also How to remove "noise" from GCC/clang assembly output?)


问:
How to use tensorflow dataset zip and string split function to get the same result?
How can i modify the code to make v1's structure the same as structure of v2?

```<code>import tensorflow as tf

a1_a2_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a\ta b", "f e a g\tc c", "d\t", "c a\tb c"]))
label_reason_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a\ta b", "f e a g\tc c", "d\t", "c a\tb c"]))
a1_a2_dataset = a1_a2_dataset.map(
    lambda src: (tf.string_split([src], delimiter='\t').values[0],
                 tf.string_split([src], delimiter='\t').values[1]))
label_reason_dataset = label_reason_dataset.map(
    lambda src: (tf.string_split([src], delimiter='\t').values[0],
                 tf.string_split([src], delimiter='\t').values[1]))

target_dataset = tf.data.Dataset.zip((a1_a2_dataset, label_reason_dataset))
sess = tf.InteractiveSession()
table_initializer = tf.tables_initializer()
sess.run(table_initializer)
value = target_dataset.make_one_shot_iterator().get_next()
v1 = sess.run(value)
print("v1 = ", type(v1), v1)

a1_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a", "f e a g", "d", "c a"]))
a2_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["a b", "c c", "", "b c"]))
label_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a", "f e a g", "d", "c a"]))
reason_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["a b", "c c", "", "b c"]))
target_dataset = tf.data.Dataset.zip((a1_dataset, a2_dataset, label_dataset, reason_dataset))
sess = tf.InteractiveSession()
table_initializer = tf.tables_initializer()
sess.run(table_initializer)
value = target_dataset.make_one_shot_iterator().get_next()
v2 = sess.run(value)
print("v2 = ", type(v2), v2)
</code>```

For now, the test code above gives the following results:

```<code>v1 =  <class 'tuple'> ((b'c c a', b'a b'), (b'c c a', b'a b'))
v2 =  <class 'tuple'> (b'c c a', b'a b', b'c c a', b'a b')
</code>```

But structure of v1 needs to be like v2.
Thank you very much!

答:
I came up with a solution, but I am not quite into this one.

```<code>target_dataset = target_dataset.map(lambda a, b: (a[0], a[1], b[0], b[1]))
</code>```

But if anybody has a better one, that will be so great!

Body:
How can i modify the code to make v1's structure the same as structure of v2?

import tensorflow as tf

a1_a2_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a\ta b", "f e a g\tc c", "d\t", "c a\tb c"]))
label_reason_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a\ta b", "f e a g\tc c", "d\t", "c a\tb c"]))
a1_a2_dataset = a1_a2_dataset.map(
    lambda src: (tf.string_split([src], delimiter='\t').values[0],
                 tf.string_split([src], delimiter='\t').values[1]))
label_reason_dataset = label_reason_dataset.map(
    lambda src: (tf.string_split([src], delimiter='\t').values[0],
                 tf.string_split([src], delimiter='\t').values[1]))

target_dataset = tf.data.Dataset.zip((a1_a2_dataset, label_reason_dataset))
sess = tf.InteractiveSession()
table_initializer = tf.tables_initializer()
sess.run(table_initializer)
value = target_dataset.make_one_shot_iterator().get_next()
v1 = sess.run(value)
print("v1 = ", type(v1), v1)

a1_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a", "f e a g", "d", "c a"]))
a2_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["a b", "c c", "", "b c"]))
label_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["c c a", "f e a g", "d", "c a"]))
reason_dataset = tf.data.Dataset.from_tensor_slices(
    tf.constant(["a b", "c c", "", "b c"]))
target_dataset = tf.data.Dataset.zip((a1_dataset, a2_dataset, label_dataset, reason_dataset))
sess = tf.InteractiveSession()
table_initializer = tf.tables_initializer()
sess.run(table_initializer)
value = target_dataset.make_one_shot_iterator().get_next()
v2 = sess.run(value)
print("v2 = ", type(v2), v2)

For now, the test code above gives the following results:

v1 =  <class 'tuple'> ((b'c c a', b'a b'), (b'c c a', b'a b'))
v2 =  <class 'tuple'> (b'c c a', b'a b', b'c c a', b'a b')

But structure of v1 needs to be like v2.
Thank you very much!

Body:
I came up with a solution, but I am not quite into this one.

target_dataset = target_dataset.map(lambda a, b: (a[0], a[1], b[0], b[1]))

But if anybody has a better one, that will be so great!