问:
ngFor cannot find a differ supporting object ... using BehaviorSubject
Getting back to learning Angular and extending the Tour of Heroes tutorial. I have a shared data service that loads data into a BehaviorSubject. The issue is that when I try to iterate the data with *ngFor, I get the "cannot find a differ supporting object" error. From all the other questions, I get that it is trying to bind to an object and not an Array, but for the life of me I cannot figure out why. Or what object needs to get converted into an Array.

I am using Angular 5.0.5. Interestingly enough, this was working with Angular 4 but apparently I have broken something in the upgrade.

Any thoughts on what I did wrong? Besides everything. :D lol

This is my service

```<code>import { Injectable, EventEmitter } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import { Hero } from '../models/hero';

@Injectable()
export class HeroService {

    private heroesUrl = 'api/heroes';
    private headers = new HttpHeaders({'Content-Type': 'application/json'});

    private loadingSubject = new BehaviorSubject<boolean>(false);
    private dataSubject = new BehaviorSubject<Hero[]>([]);

    private http: HttpClient;

    constructor(http: HttpClient) {
        this.http = http;
    }

    public getLoadingStream(): Observable<boolean> {
        return this.loadingSubject.asObservable();
    }
    public getDataStream(): Observable<Hero[]> {
        return this.dataSubject.asObservable();
    }

    public load(): void {
        this.loadingSubject.next(true);
        this.http.get<Hero[]>(this.heroesUrl).subscribe(data => {
            this.dataSubject.next(data);
            this.loadingSubject.next(false);
        });
    }

    public search(term: string): void {
        this.loadingSubject.next(true);
        this.http
            .get<Hero[]>(`${this.heroesUrl}/?name=${term}`)
            .subscribe(data => {
                this.dataSubject.next(data);
                this.loadingSubject.next(false);
        });
    }
}
</code>```

List Component

```<code>import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

import { HeroService } from '../../services/hero.service';
import { Hero } from '../../models/hero';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

  private dataSubscription: Subscription;
  private loadingSubscription: Subscription;

  private heroService: HeroService;

  heroes: Hero[] = [];
  isLoading: boolean;

  @Output()
  public onHeroSelected = new EventEmitter<Hero>();

  constructor(heroService: HeroService) {
    this.heroService = heroService;
  }

  ngOnInit() {
    this.loadingSubscription = this.heroService.getLoadingStream()
        .subscribe(loading => {
            this.isLoading = loading;
        });

    this.dataSubscription = this.heroService.getDataStream()
        .subscribe(data => {
            this.heroes = data;
        });
  }

  ngOnDestory() {
    this.dataSubscription.unsubscribe();
    this.loadingSubscription.unsubscribe();
  }

  onSelect(hero: Hero) {
    this.onHeroSelected.emit(hero);
  }
}
</code>```

List template

```<code><div *ngIf="isLoading">Loading ...</div>

<div *ngIf="!isLoading" class="ui relaxed divided list">
  <div *ngFor="let hero of heroes"  class="item" (click)="onSelect(hero)">
    <span class="ui blue circular label">{{ hero.id }}</span>
    <div class="content">
      <a class="header">{{ hero.name }}</a>
      <div class="description">...</div>
    </div>
  </div>
</div>
</code>```

答:
Ugh, I hate answering my own questions, but this was a big "d'oh".

The root cause of the issue was that I was using a the In-Memory-Web-API and did not realize that it was encapsulating the response in a data object.

So the error message was correct, it was trying to iterate over an object {data: [] } instead of an array.

Upgrading the In-Memory-Web-API and putting false in the data encapsulation

```<code>    HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {dataEncapsulation: false})
</code>```

resolved the issue.

Huge thanks to JB Nizet for pointing me in the right direction!

Body:
Getting back to learning Angular and extending the Tour of Heroes tutorial. I have a shared data service that loads data into a BehaviorSubject. The issue is that when I try to iterate the data with *ngFor, I get the "cannot find a differ supporting object" error. From all the other questions, I get that it is trying to bind to an object and not an Array, but for the life of me I cannot figure out why. Or what object needs to get converted into an Array.

I am using Angular 5.0.5. Interestingly enough, this was working with Angular 4 but apparently I have broken something in the upgrade.

Any thoughts on what I did wrong? Besides everything. :D lol

This is my service

import { Injectable, EventEmitter } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import { Hero } from '../models/hero';

@Injectable()
export class HeroService {

    private heroesUrl = 'api/heroes';
    private headers = new HttpHeaders({'Content-Type': 'application/json'});

    private loadingSubject = new BehaviorSubject<boolean>(false);
    private dataSubject = new BehaviorSubject<Hero[]>([]);

    private http: HttpClient;

    constructor(http: HttpClient) {
        this.http = http;
    }

    public getLoadingStream(): Observable<boolean> {
        return this.loadingSubject.asObservable();
    }
    public getDataStream(): Observable<Hero[]> {
        return this.dataSubject.asObservable();
    }

    public load(): void {
        this.loadingSubject.next(true);
        this.http.get<Hero[]>(this.heroesUrl).subscribe(data => {
            this.dataSubject.next(data);
            this.loadingSubject.next(false);
        });
    }

    public search(term: string): void {
        this.loadingSubject.next(true);
        this.http
            .get<Hero[]>(`${this.heroesUrl}/?name=${term}`)
            .subscribe(data => {
                this.dataSubject.next(data);
                this.loadingSubject.next(false);
        });
    }
}

List Component

import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

import { HeroService } from '../../services/hero.service';
import { Hero } from '../../models/hero';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

  private dataSubscription: Subscription;
  private loadingSubscription: Subscription;

  private heroService: HeroService;

  heroes: Hero[] = [];
  isLoading: boolean;

  @Output()
  public onHeroSelected = new EventEmitter<Hero>();

  constructor(heroService: HeroService) {
    this.heroService = heroService;
  }

  ngOnInit() {
    this.loadingSubscription = this.heroService.getLoadingStream()
        .subscribe(loading => {
            this.isLoading = loading;
        });

    this.dataSubscription = this.heroService.getDataStream()
        .subscribe(data => {
            this.heroes = data;
        });
  }

  ngOnDestory() {
    this.dataSubscription.unsubscribe();
    this.loadingSubscription.unsubscribe();
  }

  onSelect(hero: Hero) {
    this.onHeroSelected.emit(hero);
  }
}

List template

Loading ...

    {{ hero.id }}

      {{ hero.name }}

...

Body:
Ugh, I hate answering my own questions, but this was a big "d'oh".

The root cause of the issue was that I was using a the In-Memory-Web-API and did not realize that it was encapsulating the response in a data object.

So the error message was correct, it was trying to iterate over an object {data: [] } instead of an array.

Upgrading the In-Memory-Web-API and putting false in the data encapsulation

    HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {dataEncapsulation: false})

resolved the issue.

Huge thanks to JB Nizet for pointing me in the right direction!


来源: stackexchange

问:
How do i use a ng-repeat with different classes with each index
I am building a timeline and i want to invert every other index in the ng-repeat. I used ng-repeat-start and ng-repeat-end on two separate divs but all they do is just repeat the same array twice.

```<code><ul class="timeline">
    <li ng-repeat-start="t in vm.patientTimeLine">
        <div class="timeline-badge" style="background-color:#f9f9f9!important;"><i class="fa fa-phone hg-blue" aria-hidden="true"></i></div>
            <div class="card-block">
                 <h4 class="card-title"> {{t.FirstName}}'s reply was: <b ng-if="t.ReplyMessage !== null" class="stop">{{t.ReplyMessage}}</b></h4>
            </div>
     </li>

     <li class="timeline-inverted" ng-repeat-end>
        <div class="timeline-badge" style="background-color:#f9f9f9!important;"><i class="fa fa-phone hg-blue" aria-hidden="true"></i></div>
           <div class="card-block">
               <h4 class="card-title"> {{t.FirstName}}'s reply was: <b ng-if="t.ReplyMessage !== null" class="stop">{{t.ReplyMessage}}</b></h4>
           </div>
     </li>
</ul>
</code>```

I expect it to show the same list once but with the different css classes (timeline and timeline-inverted).

I thank you guys in advance.

答:
If you want to lets say, make timeline-inverted every other row, you can always use the varaibles ngRepeat provides.
For example:

```<code>$even   boolean     true if the iterator position $index is even (otherwise false).
</code>```

List of variables can be found here:
https://docs.angularjs.org/api/ng/directive/ngRepeat

ContentLicense: CC BY-SA 3.0

Body:
I am building a timeline and i want to invert every other index in the ng-repeat. I used ng-repeat-start and ng-repeat-end on two separate divs but all they do is just repeat the same array twice.

 {{t.FirstName}}'s reply was: {{t.ReplyMessage}}

 {{t.FirstName}}'s reply was: {{t.ReplyMessage}}

I expect it to show the same list once but with the different css classes (timeline and timeline-inverted).

I thank you guys in advance.

Body:
If you want to lets say, make timeline-inverted every other row, you can always use the varaibles ngRepeat provides.
For example:

$even   boolean     true if the iterator position $index is even (otherwise false).

List of variables can be found here:
https://docs.angularjs.org/api/ng/directive/ngRepeat


问:
POST data is not being passed to other view controller
I am running into a small problem with my project. I am new to iOS development, and I am running into a slight problem trying to pass some data that I have pulled out of a response body in JSON format. I am able to print out the correct data from the server right after I assign it to a variable in the class, but once I prepare and perform a segue, it doesn't seem to pass over. Here is my first viewController:

```<code>import UIKit
import SwiftyJSON

class ViewController: UIViewController {
    @IBOutlet weak var emailAddress: UITextField!
    @IBOutlet weak var userPassword: UITextField!
    var returned_email: String!
    var returned_pass: String!
    var current_exp: Int!
    var needed_exp: Int!

    @IBAction func getUserDataBtn(_ sender: Any) {
        if emailAddress.text != "" && userPassword.text != ""
        {
            let session = URLSession.shared
            let parameters = ["nameValuePairs":["username": emailAddress.text, "password": userPassword.text]]
            guard let myURL = URL(string: "<protected url>") else {return}
            var request = URLRequest(url: myURL, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 300.0)

            request.httpMethod = "POST"
            guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
            request.httpBody = httpBody
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            session.dataTask(with: request, completionHandler: { (data, response, error) in
                if let myData = data{
                    do{
                        let json = try JSONSerialization.jsonObject(with: myData, options: .mutableContainers) as! [String:Any]
                        self.returned_email = json["username"] as! String
                        self.returned_pass = json["password"] as! String
                        self.current_exp = json["curr_exp"] as! Int
                        self.needed_exp = json["needed_exp"] as! Int
                    }
                    catch{
                        print(error)
                    }
                    self.performSegue(withIdentifier: "GetUserDataSegue", sender: self)
                }
            }).resume()
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if(segue.identifier == "GetUserDataSegue"){
            guard let viewController = segue.destination as? UserDataController else {return}
            viewController.myUN = returned_email
            viewController.myPW = returned_pass
            viewController.myCurrExp = current_exp
            viewController.myNeedExp = needed_exp
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        }
}
</code>```

Here is my other viewcontroller:

```<code>import UIKit

class UserDataController: UIViewController {
    var myUN: String!
    var myPW: String!
    var myCurrExp: Int!
    var myNeedExp: Int!

    @IBOutlet weak var password: UILabel!
    @IBOutlet weak var username: UILabel!
    @IBOutlet weak var current_exp: UILabel!
    @IBOutlet weak var needed_exp: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        username.text = myUN
        password.text = myPW
        current_exp.text = String(describing: myCurrExp)
        needed_exp.text = String(describing: myNeedExp)
        // Do any additional setup after loading the view.
    }
}
</code>```

What I am trying to accomplish with this test project is to have a person enter in their username and password, hit "get user data" button, be taken to the second viewcontroller with all of their information displayed in the provided labels. I am able to get the correct data from the database on the server, and I am able to receive it and save it to the local variables in the first viewcontroller. Any help would be appreciated! I am using Swift 4 and Xcode 9, if that has any impact on answers.

Thank you for your time!

答:
After doing some more research on how to get my dataTask to run before my prepare was started, I found this little thing that helped me get it working:

```<code>DispatchQueue.main.async {
                        self.returned_email = json["username"] as! String
                        self.returned_pass = json["password"] as! String
                        self.current_exp = json["curr_exp"] as! Int
                        self.needed_exp = json["needed_exp"] as! Int
                        self.performSegue(withIdentifier: "GetUserDataSegue", sender: self)
                    }
</code>```

By wrapping the DispatchQueue.main.async around the setting of my class variables, and then calling the performSegue, I was able to have prepare get called after the dataTask, and allowing my class variables to be sent to the second view.

Another thing that helped me was to change where my segue would happen. Instead of having it come from the button, I had it come from the viewcontroller, and perform that segue when the button was clicked and my data was returned and set from the server.

Thank you to all for your help, it has helped me understand this topic a lot more!

Body:
I am running into a small problem with my project. I am new to iOS development, and I am running into a slight problem trying to pass some data that I have pulled out of a response body in JSON format. I am able to print out the correct data from the server right after I assign it to a variable in the class, but once I prepare and perform a segue, it doesn't seem to pass over. Here is my first viewController:

import UIKit
import SwiftyJSON

class ViewController: UIViewController {
    @IBOutlet weak var emailAddress: UITextField!
    @IBOutlet weak var userPassword: UITextField!
    var returned_email: String!
    var returned_pass: String!
    var current_exp: Int!
    var needed_exp: Int!

    @IBAction func getUserDataBtn(_ sender: Any) {
        if emailAddress.text != "" && userPassword.text != ""
        {
            let session = URLSession.shared
            let parameters = ["nameValuePairs":["username": emailAddress.text, "password": userPassword.text]]
            guard let myURL = URL(string: "<protected url>") else {return}
            var request = URLRequest(url: myURL, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 300.0)

            request.httpMethod = "POST"
            guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
            request.httpBody = httpBody
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            session.dataTask(with: request, completionHandler: { (data, response, error) in
                if let myData = data{
                    do{
                        let json = try JSONSerialization.jsonObject(with: myData, options: .mutableContainers) as! [String:Any]
                        self.returned_email = json["username"] as! String
                        self.returned_pass = json["password"] as! String
                        self.current_exp = json["curr_exp"] as! Int
                        self.needed_exp = json["needed_exp"] as! Int
                    }
                    catch{
                        print(error)
                    }
                    self.performSegue(withIdentifier: "GetUserDataSegue", sender: self)
                }
            }).resume()
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if(segue.identifier == "GetUserDataSegue"){
            guard let viewController = segue.destination as? UserDataController else {return}
            viewController.myUN = returned_email
            viewController.myPW = returned_pass
            viewController.myCurrExp = current_exp
            viewController.myNeedExp = needed_exp
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        }
}

Here is my other viewcontroller:

import UIKit

class UserDataController: UIViewController {
    var myUN: String!
    var myPW: String!
    var myCurrExp: Int!
    var myNeedExp: Int!

    @IBOutlet weak var password: UILabel!
    @IBOutlet weak var username: UILabel!
    @IBOutlet weak var current_exp: UILabel!
    @IBOutlet weak var needed_exp: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        username.text = myUN
        password.text = myPW
        current_exp.text = String(describing: myCurrExp)
        needed_exp.text = String(describing: myNeedExp)
        // Do any additional setup after loading the view.
    }
}

What I am trying to accomplish with this test project is to have a person enter in their username and password, hit "get user data" button, be taken to the second viewcontroller with all of their information displayed in the provided labels. I am able to get the correct data from the database on the server, and I am able to receive it and save it to the local variables in the first viewcontroller. Any help would be appreciated! I am using Swift 4 and Xcode 9, if that has any impact on answers.

Thank you for your time!

Body:
After doing some more research on how to get my dataTask to run before my prepare was started, I found this little thing that helped me get it working:

DispatchQueue.main.async {
                        self.returned_email = json["username"] as! String
                        self.returned_pass = json["password"] as! String
                        self.current_exp = json["curr_exp"] as! Int
                        self.needed_exp = json["needed_exp"] as! Int
                        self.performSegue(withIdentifier: "GetUserDataSegue", sender: self)
                    }

By wrapping the DispatchQueue.main.async around the setting of my class variables, and then calling the performSegue, I was able to have prepare get called after the dataTask, and allowing my class variables to be sent to the second view.

Another thing that helped me was to change where my segue would happen. Instead of having it come from the button, I had it come from the viewcontroller, and perform that segue when the button was clicked and my data was returned and set from the server.

Thank you to all for your help, it has helped me understand this topic a lot more!


问:
How to dynamically remove a input form created in html using javascript
I'm currently stuck and I don't know what to do. The solution may be simple but since I'm new to the JavaScript environment I am kind of lost.

I created a check option that when pressed, it generates a input form to be filled with a "Add new" button to generate another input form.

In my code, when the button "Add new" is pressed, it already creates a dynamic input form with a "Delete" button BUT, I can't seem to make this "delete" ban work when pressed.

All help is welcome. I am using html with JavaScript. Ultimately I'll be saving these form values in a sql database using pup as my middle man.

PS: I am working on WordPress as the web development since the page is already created in it and Yes, I know that I should be using JavaScript and CSS apart from the main html page.

Here's the code I have so far:

```<code>    <!DOCTYPE html>
<html>
<style type="text/css">
  label{
    float:left;
    width: 10em;
    text-align: right;
    margin-right: 10px;
  }
</style>

<script type="text\javascript">
  function checkform(form) {
    // get all the inputs within the submitted form
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        // only validate the inputs that have the required attribute
        if(inputs[i].hasAttribute("required")){
            if(inputs[i].value == ""){
                // found an empty field that is required
                alert("Please fill all required fields");
                return false;
            }
        }
    }
    return true;
}
</script>

<script type="text/javascript">

//This function adds another form input when button "Add" is pressed
  var counter = 1;
var limit = 5;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " Co-PI or Co-Investigators");
     }
     else {
          var divName = divName;
          var newDivName = (divName + counter);
          var newdiv = document.createElement('div');
          newdiv.id = "dynamicInput" + counter;
          newdiv.innerHTML = (counter + 1) + ". Co-PI or Co-Investigator Information: <br>" +
          "<label>First Name  : </label><input type='text' name='fname[]' maxlength='35' required><br> " +
           "<label>Last Name  : </label><input type='text' name='lname[]' maxlength='35'><br> " +
           "<label>Degree  : </label><input type='text' name='degree[]' maxlength='10'><br> " +
           "<label>Current Position  : </label><input type='text' name='cPos[]' maxlength='30'><br> " +
           "<label>Institution  : </label><input type='text' name='inst[]' maxlength='40'><br> " +
           "<label>School  : </label><input type='text' name='school[]' maxlength='40'><br> " +
           "<label>Department  : </label><input type='text' name='depart[]' maxlength='40'><br> " +
           "<label>Program  : </label><input type='text' name='program[]' maxlength='40'><br> " +
           "<label>Email  : </label><input type='text' name='email[]' maxlength='255'><br> " +
           "<label>Phone (xxx-xxx-xxxx)  : </label><input type='text' name='phone[]' maxlength='10'> <br><br>"  +
           "<input type='button' value='Delete Previous Form' onClick='removeForm(divName, newDivName);'>  ";

          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

//Delete div form when delete button is pressed
function removeForm(parentDiv, childDiv){
    if(childDiv == parentDiv)
    {
        alert("Cannot delete anymore form entries!");
    }

    else if (document.getElementById(childDiv))
    {
        var child = document.getElementById(childDiv);
        var parent = document.getElementById(parentDiv)
        parent.removeChild(child);
        counter--;
    }

    else
    {
        alert("Form has been removed or does not exist.");
        return false;
    }
}
</script>

<script type="text/javascript">
function aff_div(ladiv) {
  document.getElementById(ladiv).style.display = "inline";
}

function cach_div(ladiv) {
  document.getElementById(ladiv).style.display = "none";
}

function affich_conj() {
  if (document.forms.CoPI_CoInv_Info.yesNoChkbox[0].checked == true) {
    aff_div("dynamicInput");
    aff_divBtn("btn_New_CoPI_Inv");
  }

  if (document.forms.CoPI_CoInv_Info.yesNoChkbox[1].checked == true) {
    cach_div("dynamicInput");
    cach_divBtn("btn_New_CoPI_Inv");
  }
}

function aff_divBtn(BtnDiv) {
  document.getElementById(BtnDiv).style.display = "inline";
}

function cach_divBtn(BtnDiv) {
  document.getElementById(BtnDiv).style.display = "none";
}

</script>

<form id="CoPI_CoInv_Info" onsubmit="return checkform(this)">

<label1>Do you want to add a Co-PI or Co-Investigator? </label1>
  <input type="radio" name="yesNoChkbox" value="yes" onclick="affich_conj();"> yes
  <input type="radio" name="yesNoChkbox" value="no" checked="checked" onclick="affich_conj();"> no
<br><br>

  <div id="dynamicInput">
                 1. Co-PI or Co-Investigator Information: <br>
       <label>First Name  : </label><input type="text" name="fname[]" maxlength="35" required><br>
       <label>Last Name  : </label><input type="text" name="lname[]" maxlength="35"><br>
       <label>Degree  : </label><input type="text" name="degree[]" maxlength="10"><br>
       <label>Current Position  : </label><input type="text" name="cPos[]" maxlength="30"><br>
       <label>Institution  : </label><input type="text" name="inst[]" maxlength="40"><br>
       <label>School  : </label><input type="text" name="school[]" maxlength="40"><br>
       <label>Department  : </label><input type="text" name="depart[]" maxlength="40"><br>
       <label>Program  : </label><input type="text" name="program[]" maxlength="40"><br>
       <label>Email  : </label><input type="text" name="email[]" maxlength="255"><br>
       <label>Phone (xxx-xxx-xxxx)  : </label><input type="text" name="phone[]" maxlength="10"> <br><br>

     </div>
<divBtn id="btn_New_CoPI_Inv">
<input type="button" value="Add New Co-PI or Co-Investigator..." onClick="addInput('dynamicInput');">

</divBtn>
</form>

<script type="text/javascript">
  cach_div("dynamicInput");
  cach_divBtn("btn_New_CoPI_Inv");
</script>
</html>
</code>```

答:
Try pass id of Div you want to  remove:

```<code>newdiv.id = "dynamicInput" + counter;
newdiv.innerHTML = (counter + 1) + "... <input type='button' value='Delete Previous Form' onClick='removeForm(\"dynamicInput\"" + counter");'>";
</code>```

Then, in removeForm():

```<code>function removeForm(id){
  if(document.getElementById(id)) document.getElementById(id).outterHTML ='';
}
</code>```

Body:
I'm currently stuck and I don't know what to do. The solution may be simple but since I'm new to the JavaScript environment I am kind of lost.

I created a check option that when pressed, it generates a input form to be filled with a "Add new" button to generate another input form.

In my code, when the button "Add new" is pressed, it already creates a dynamic input form with a "Delete" button BUT, I can't seem to make this "delete" ban work when pressed.

All help is welcome. I am using html with JavaScript. Ultimately I'll be saving these form values in a sql database using pup as my middle man.

PS: I am working on WordPress as the web development since the page is already created in it and Yes, I know that I should be using JavaScript and CSS apart from the main html page.

Here's the code I have so far:

    <!DOCTYPE html>

<form id="CoPI_CoInv_Info" onsubmit="return checkform(this)">

<label1>Do you want to add a Co-PI or Co-Investigator? </label1>
  <input type="radio" name="yesNoChkbox" value="yes" onclick="affich_conj();"> yes
  <input type="radio" name="yesNoChkbox" value="no" checked="checked" onclick="affich_conj();"> no

                 1. Co-PI or Co-Investigator Information:

       First Name  : <input type="text" name="fname[]" maxlength="35" required>

       Last Name  : <input type="text" name="lname[]" maxlength="35">

       Degree  : <input type="text" name="degree[]" maxlength="10">

       Current Position  : <input type="text" name="cPos[]" maxlength="30">

       Institution  : <input type="text" name="inst[]" maxlength="40">

       School  : <input type="text" name="school[]" maxlength="40">

       Department  : <input type="text" name="depart[]" maxlength="40">

       Program  : <input type="text" name="program[]" maxlength="40">

       Email  : <input type="text" name="email[]" maxlength="255">

       Phone (xxx-xxx-xxxx)  : <input type="text" name="phone[]" maxlength="10">

<divBtn id="btn_New_CoPI_Inv">
<input type="button" value="Add New Co-PI or Co-Investigator..." onClick="addInput('dynamicInput');">

</divBtn>
</form>

Body:
Try pass id of Div you want to  remove:

newdiv.id = "dynamicInput" + counter;
newdiv.innerHTML = (counter + 1) + "... <input type='button' value='Delete Previous Form' onClick='removeForm(\"dynamicInput\"" + counter");'>";

Then, in removeForm():

function removeForm(id){
  if(document.getElementById(id)) document.getElementById(id).outterHTML ='';
}


问:
Using directory as input for tf-idf with python `textblob`
I am trying to adapt this code (source found here)to iterate through a directory of files, instead of having the input hard-coded.

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals
import math
from textblob import TextBlob as tb

def tf(word, blob):
    return blob.words.count(word) / len(blob.words)

def n_containing(word, bloblist):
    return sum(1 for blob in bloblist if word in blob)

def idf(word, bloblist):
    return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
    return tf(word, blob) * idf(word, bloblist)

document1 = tb("""Today, the weather is 30 degrees in Celcius. It is really hot""")

document2 = tb("""I can't believe the traffic headed to the beach. It is really a circus out there.'""")

document3 = tb("""There are so many tolls on this road. I recommend taking the interstate.""")

bloblist = [document1, document2, document3]
for i, blob in enumerate(bloblist):
    print("Document {}".format(i + 1))
    scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    for word, score in sorted_words:
        score_weight = score * 100
        print("\t{}, {}".format(word, round(score_weight, 5)))
</code>```

I would like to use an an input txt files in a directory, rather than each hard-coded document.

For instance, imagine I had a directory foo which contains three files file1, file2, file3.

File 1 contains the contents that document1 contains, i.e.

file1:

```<code>Today, the weather is 30 degrees in Celcius. It is really hot
</code>```

File 2 contains the contents that document2 contains, i.e.

```<code>I can't believe the traffic headed to the beach. It is really a circus out there.
</code>```

File 3 contains the contents that document3 contains, i.e.

```<code>There are so many tolls on this road. I recommend taking the interstate.
</code>```

I have though to use glob to achieve my desired result, and I have come up with the following code adapation, which correctly identifies the files, but does not process them individually, as the original code does:

```<code>file_names = glob.glob("/path/to/foo/*")
files =  map(open,file_names)
documents = [file.read() for file in files]
[file.close() for file in files]

bloblist = [documents]
for i, blob in enumerate(bloblist):
    print("Document {}".format(i + 1))
    scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    for word, score in sorted_words:
        score_weight = score * 100
        print("\t{}, {}".format(word, round(score_weight, 5)))
</code>```

How can I maintain the scores for each individual file using glob?

The desired result after using the files in a directory as input would be the same as the original code [results truncuated to top 3 for space]:

```<code>Document 1
    Celcius, 3.37888
    30, 3.37888
    hot, 3.37888
Document 2
    there, 2.38509
    out, 2.38509
    headed, 2.38509
Document 3
    on, 3.11896
    this, 3.11896
    many, 3.11896
</code>```

A similar question here did not fully solve the problem. I was wondering how I can call the files to calculate the idf but maintain them separately for calculate the full tf-idf?

答:
@AnnaBonazzi provides a code snippet here, https://gist.github.com/sloria/6407257,

```<code>import os, glob
folder = "/path/to/folder/"
os.chdir(folder)
files = glob.glob("*.txt") # Makes a list of all files in folder
bloblist = []
for file1 in files:
    with open (file1, 'r') as f:
        data = f.read() # Reads document content into a string
        document = tb(data.decode("utf-8")) # Makes TextBlob object
        bloblist.append(document)
</code>```

I modified it for my use (Python 3):

```<code>import os, glob
bloblist = []

def make_corpus(input_dir):
    """ Based on code snippet from https://gist.github.com/sloria/6407257 """

    global doc                              ## used outside this method
    input_folder = "input"
    os.chdir(input_folder)
    files = glob.glob("*.*")                ## or "*.txt", etc.
    for doc in files:
        # print('doc:', doc)                ## prints filename (doc)
        with open (doc, 'r') as f:
            data = f.read()                 ## read document content into a string
            document = tb(data)             ## make TextBlob object
            bloblist.append(document)
    # print('bloblist:\n', bloblist)        ## copious output ...
    print('len(bloblist):', len(bloblist))

make_corpus('input')                        ## input directory 'input'
</code>```

Update 1:

I personally have nothing but difficulty using the Python glob module, as I often (i) have filenames without extensions (e.g. 01), and (ii) want to recurse over nested directories.

At first glance the "glob" approach appears to be a simple solution.  However, when trying to iterate over the files in that are returned by glob, I often encounter errors (e.g.)

```<code>IsADirectoryError: [Errno 21] Is a directory: ...
</code>```

when the loop encounters a directory (not a file) name that was returned by glob.

In my opinion, with a little added effort, the following approach is far more robust:

```<code>import os
bloblist = []

def make_corpus(input_dir):
    for root, subdirs, files in os.walk(input_dir):
        for filename in files:
            f = os.path.join(root, filename)
            print('file:', f)
            with open(os.path.join(root, filename)) as f:
                for line in f:
                    # print(line, end='')
                    bloblist.append(line)
    # print('bloblist:\n', bloblist)
    print('len(bloblist):', len(bloblist), '\n')

make_corpus('input')       ## 'input' = input dir
</code>```

Update 2:

One last approach (Linux shell find command, adapted for use in Python 3):

```<code>import sh     ## pip install sh

def make_corpus(input_dir):
    '''find (here) matches filenames, excludes directory names'''

    corpus = []
    file_list = []
    #FILES = sh.find(input_dir, '-type', 'f', '-iname', '*.txt')    ## find all .txt files
    FILES = sh.find(input_dir, '-type', 'f', '-iname', '*')         ## find any file
    print('FILES:', FILES)                                          ## caveat: files in FILES are '\n'-terminated ...
    for filename in FILES:
        #print(filename, end='')
        # file_list.append(filename)                                ## when printed, each filename ends with '\n'
        filename = filename.rstrip('\n')                            ## ... this addresses that issue
        file_list.append(filename)
        with open(filename) as f:
            #print('file:', filename)
            # ----------------------------------------
            # for general use:
            #for line in f:
                #print(line)
                #corpus.append(line)
            # ----------------------------------------
            # for this particular example (Question, above):
            data = f.read()
            document = tb(data)
            corpus.append(document)
    print('file_list:', file_list)
    print('corpus length (lines):', len(corpus))

    with open('output/corpus', 'w') as f:                           ## write to file
        for line in corpus:
            f.write(line)
</code>```

Body:
I am trying to adapt this code (source found here)to iterate through a directory of files, instead of having the input hard-coded.

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals
import math
from textblob import TextBlob as tb

def tf(word, blob):
    return blob.words.count(word) / len(blob.words)

def n_containing(word, bloblist):
    return sum(1 for blob in bloblist if word in blob)

def idf(word, bloblist):
    return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
    return tf(word, blob) * idf(word, bloblist)

document1 = tb("""Today, the weather is 30 degrees in Celcius. It is really hot""")

document2 = tb("""I can't believe the traffic headed to the beach. It is really a circus out there.'""")

document3 = tb("""There are so many tolls on this road. I recommend taking the interstate.""")

bloblist = [document1, document2, document3]
for i, blob in enumerate(bloblist):
    print("Document {}".format(i + 1))
    scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    for word, score in sorted_words:
        score_weight = score * 100
        print("\t{}, {}".format(word, round(score_weight, 5)))

I would like to use an an input txt files in a directory, rather than each hard-coded document.

For instance, imagine I had a directory foo which contains three files file1, file2, file3.

File 1 contains the contents that document1 contains, i.e.

file1:

Today, the weather is 30 degrees in Celcius. It is really hot

File 2 contains the contents that document2 contains, i.e.

I can't believe the traffic headed to the beach. It is really a circus out there.

File 3 contains the contents that document3 contains, i.e.

There are so many tolls on this road. I recommend taking the interstate.

I have though to use glob to achieve my desired result, and I have come up with the following code adapation, which correctly identifies the files, but does not process them individually, as the original code does:

file_names = glob.glob("/path/to/foo/*")
files =  map(open,file_names)
documents = [file.read() for file in files]
[file.close() for file in files]

bloblist = [documents]
for i, blob in enumerate(bloblist):
    print("Document {}".format(i + 1))
    scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    for word, score in sorted_words:
        score_weight = score * 100
        print("\t{}, {}".format(word, round(score_weight, 5)))

How can I maintain the scores for each individual file using glob?

The desired result after using the files in a directory as input would be the same as the original code [results truncuated to top 3 for space]:

Document 1
    Celcius, 3.37888
    30, 3.37888
    hot, 3.37888
Document 2
    there, 2.38509
    out, 2.38509
    headed, 2.38509
Document 3
    on, 3.11896
    this, 3.11896
    many, 3.11896

A similar question here did not fully solve the problem. I was wondering how I can call the files to calculate the idf but maintain them separately for calculate the full tf-idf?

Body:
@AnnaBonazzi provides a code snippet here, https://gist.github.com/sloria/6407257,

import os, glob
folder = "/path/to/folder/"
os.chdir(folder)
files = glob.glob("*.txt") # Makes a list of all files in folder
bloblist = []
for file1 in files:
    with open (file1, 'r') as f:
        data = f.read() # Reads document content into a string
        document = tb(data.decode("utf-8")) # Makes TextBlob object
        bloblist.append(document)

I modified it for my use (Python 3):

import os, glob
bloblist = []

def make_corpus(input_dir):
    """ Based on code snippet from https://gist.github.com/sloria/6407257 """

    global doc                              ## used outside this method
    input_folder = "input"
    os.chdir(input_folder)
    files = glob.glob("*.*")                ## or "*.txt", etc.
    for doc in files:
        # print('doc:', doc)                ## prints filename (doc)
        with open (doc, 'r') as f:
            data = f.read()                 ## read document content into a string
            document = tb(data)             ## make TextBlob object
            bloblist.append(document)
    # print('bloblist:\n', bloblist)        ## copious output ...
    print('len(bloblist):', len(bloblist))

make_corpus('input')                        ## input directory 'input'

Update 1:

I personally have nothing but difficulty using the Python glob module, as I often (i) have filenames without extensions (e.g. 01), and (ii) want to recurse over nested directories.

At first glance the "glob" approach appears to be a simple solution.  However, when trying to iterate over the files in that are returned by glob, I often encounter errors (e.g.)

IsADirectoryError: [Errno 21] Is a directory: ...

when the loop encounters a directory (not a file) name that was returned by glob.

In my opinion, with a little added effort, the following approach is far more robust:

import os
bloblist = []

def make_corpus(input_dir):
    for root, subdirs, files in os.walk(input_dir):
        for filename in files:
            f = os.path.join(root, filename)
            print('file:', f)
            with open(os.path.join(root, filename)) as f:
                for line in f:
                    # print(line, end='')
                    bloblist.append(line)
    # print('bloblist:\n', bloblist)
    print('len(bloblist):', len(bloblist), '\n')

make_corpus('input')       ## 'input' = input dir

Update 2:

One last approach (Linux shell find command, adapted for use in Python 3):

import sh     ## pip install sh

def make_corpus(input_dir):
    '''find (here) matches filenames, excludes directory names'''

    corpus = []
    file_list = []
    #FILES = sh.find(input_dir, '-type', 'f', '-iname', '*.txt')    ## find all .txt files
    FILES = sh.find(input_dir, '-type', 'f', '-iname', '*')         ## find any file
    print('FILES:', FILES)                                          ## caveat: files in FILES are '\n'-terminated ...
    for filename in FILES:
        #print(filename, end='')
        # file_list.append(filename)                                ## when printed, each filename ends with '\n'
        filename = filename.rstrip('\n')                            ## ... this addresses that issue
        file_list.append(filename)
        with open(filename) as f:
            #print('file:', filename)
            # ----------------------------------------
            # for general use:
            #for line in f:
                #print(line)
                #corpus.append(line)
            # ----------------------------------------
            # for this particular example (Question, above):
            data = f.read()
            document = tb(data)
            corpus.append(document)
    print('file_list:', file_list)
    print('corpus length (lines):', len(corpus))

    with open('output/corpus', 'w') as f:                           ## write to file
        for line in corpus:
            f.write(line)


问:
Parse JSON from web in SQL Server 2017
Is it possible to consume a JSON response from the web in SQL Server 2017 and then parse. I am interested in getting data from the public Open Sky API.
I tried this but I just get NULL in @ResponseText :

```<code>Declare @Object as Int;
Declare @ResponseText as nvarchar(max);

 Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
 Exec sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false'
 Exec sp_OAMethod @Object, 'send'
 Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

 Select @ResponseText

 Exec sp_OADestroy @Object
</code>```

Thanks for your help!

答:
OK, I do have an SQL Server 2008 instance with OLE Automation enabled, so I can help with that but not so much with the JSON parsing.

First, pretty much everybody universally says, "Use SQLCLR to do this and not OLE Automation."  You should look at using SQLCLR for a new project.

Second, here's how I figured it out.  First, all the sp_OA* stored procedures return a result code.  We need to see that:

```<code>Declare @Object as Int;
Declare @ResponseText as nvarchar(max);
Declare @hr int;

Exec @hr = sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
select @hr;
Exec @hr = sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false';
select @hr;
Exec @hr = sp_OAMethod @Object, 'send';
select @hr;
Exec @hr = sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT;
select @hr;
Exec @hr = sp_OADestroy @Object
select @hr
</code>```

Running that returned 0, 0, 0, -2147211494, 0.  So the next to last call is the error.  The number translates to an HRESULT of 0x8004271A (thank you calc.exe, although you can also use PowerShell: '{0:x}' -f -2147211494), but that didn't lead me anywhere. However, it does tell us where to use sp_OAGetErrorInfo:

```<code>Declare @Object as Int;
Declare @ResponseText as nvarchar(max);
Declare @source nvarchar(255), @description nvarchar(255)

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false';
Exec sp_OAMethod @Object, 'send';
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT;

Exec sp_OAGetErrorInfo @Object, @Source OUT, @Description OUT

Select @source, @description;

Exec sp_OADestroy @Object
</code>```

Which returned the error Error in srv_convert..  That error message led me here, which said you had to use a table and not a variable for the output if it was a very long string for some unspecified reason.

That gives me code that works:

```<code>Declare @Object as Int;
Declare @Response table (txt nvarchar(max));

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false';
Exec sp_OAMethod @Object, 'send';

Insert Into @Response (txt)
Exec sp_OAMethod @Object, 'responseText'

Exec sp_OADestroy @Object

Select txt From @Response
</code>```

SQL Server 2016+ comes with JSON parsing functions which have a similar syntax to the older XML functions and are about as easy to use.  (Which is to say: not very easy until you're familiar with them.)

Use the JSON_VALUE function to extract a scalar value from a JSON string.

Use JSON_QUERY to extract an object or an array from a JSON string.

Use the ISJSON function to test whether a string contains valid JSON.

Use the JSON_MODIFY function to change a value in a JSON string.

There's also the OPENJSON rowset function.

Title: Parse JSON from web in SQL Server 2017

Body:
Is it possible to consume a JSON response from the web in SQL Server 2017 and then parse. I am interested in getting data from the public Open Sky API.
I tried this but I just get NULL in @ResponseText :

Declare @Object as Int;
Declare @ResponseText as nvarchar(max);

 Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
 Exec sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false'
 Exec sp_OAMethod @Object, 'send'
 Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

 Select @ResponseText

 Exec sp_OADestroy @Object

Thanks for your help!

Body:
OK, I do have an SQL Server 2008 instance with OLE Automation enabled, so I can help with that but not so much with the JSON parsing.

First, pretty much everybody universally says, "Use SQLCLR to do this and not OLE Automation."  You should look at using SQLCLR for a new project.

Second, here's how I figured it out.  First, all the sp_OA* stored procedures return a result code.  We need to see that:

Declare @Object as Int;
Declare @ResponseText as nvarchar(max);
Declare @hr int;

Exec @hr = sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
select @hr;
Exec @hr = sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false';
select @hr;
Exec @hr = sp_OAMethod @Object, 'send';
select @hr;
Exec @hr = sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT;
select @hr;
Exec @hr = sp_OADestroy @Object
select @hr

Running that returned 0, 0, 0, -2147211494, 0.  So the next to last call is the error.  The number translates to an HRESULT of 0x8004271A (thank you calc.exe, although you can also use PowerShell: '{0:x}' -f -2147211494), but that didn't lead me anywhere. However, it does tell us where to use sp_OAGetErrorInfo:

Declare @Object as Int;
Declare @ResponseText as nvarchar(max);
Declare @source nvarchar(255), @description nvarchar(255)

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false';
Exec sp_OAMethod @Object, 'send';
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT;

Exec sp_OAGetErrorInfo @Object, @Source OUT, @Description OUT

Select @source, @description;

Exec sp_OADestroy @Object

Which returned the error Error in srv_convert..  That error message led me here, which said you had to use a table and not a variable for the output if it was a very long string for some unspecified reason.

That gives me code that works:

Declare @Object as Int;
Declare @Response table (txt nvarchar(max));

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
             'https://opensky-network.org/api/states/all',
             'false';
Exec sp_OAMethod @Object, 'send';

Insert Into @Response (txt)
Exec sp_OAMethod @Object, 'responseText'

Exec sp_OADestroy @Object

Select txt From @Response

SQL Server 2016+ comes with JSON parsing functions which have a similar syntax to the older XML functions and are about as easy to use.  (Which is to say: not very easy until you're familiar with them.)

Use the JSON_VALUE function to extract a scalar value from a JSON string.

Use JSON_QUERY to extract an object or an array from a JSON string.

Use the ISJSON function to test whether a string contains valid JSON.

Use the JSON_MODIFY function to change a value in a JSON string.

There's also the OPENJSON rowset function.


问:
Python: How to create a step plot with offline plotly for a pandas DataFrame?
Lets say we have following DataFrame and corresponding graph generated:

```<code>import pandas as pd
import plotly
from plotly.graph_objs import Scatter

df = pd.DataFrame({"value":[10,7,0,3,8]},
index=pd.to_datetime([
"2015-01-01 00:00",
"2015-01-01 10:00",
"2015-01-01 20:00",
"2015-01-02 22:00",
"2015-01-02 23:00"]))
plotly.offline.plot({"data": [Scatter( x=df.index, y=df["value"] )]})
</code>```

Expected results

If I use below code:

```<code>import matplotlib.pyplot as plt
plt.step(df.index, df["value"],where="post")
plt.show()
</code>```

I get a step graph as below:

Question

How can I get same results as step function but using offline plotly instead?

答:
We can use the line parameter shape option as hv using below code:

```<code>trace1 = {
  "x": df.index,
  "y": df["value"],
  "line": {"shape": 'hv'},
  "mode": 'lines',
  "name": 'value',
  "type": 'scatter'
};

data = [trace1]
plotly.offline.plot({
    "data": data
})
</code>```

Which generates below graph:

Body:
Lets say we have following DataFrame and corresponding graph generated:

import pandas as pd
import plotly
from plotly.graph_objs import Scatter

df = pd.DataFrame({"value":[10,7,0,3,8]},
index=pd.to_datetime([
"2015-01-01 00:00",
"2015-01-01 10:00",
"2015-01-01 20:00",
"2015-01-02 22:00",
"2015-01-02 23:00"]))
plotly.offline.plot({"data": [Scatter( x=df.index, y=df["value"] )]})

Expected results

If I use below code:

import matplotlib.pyplot as plt
plt.step(df.index, df["value"],where="post")
plt.show()

I get a step graph as below:

Question

How can I get same results as step function but using offline plotly instead?

Body:
We can use the line parameter shape option as hv using below code:

trace1 = {
  "x": df.index,
  "y": df["value"],
  "line": {"shape": 'hv'},
  "mode": 'lines',
  "name": 'value',
  "type": 'scatter'
};

data = [trace1]
plotly.offline.plot({
    "data": data
})

Which generates below graph:


问:
Match "any string" in Haskell record in HSpec test
I have a data class Entity which is defined like this:

```<code>data Entity = Entity { id :: String, name :: String }
</code>```

and a function that returns IO Entity:

```<code>newPersistentEntity :: String -> IO Entity
</code>```

And I'd like to write an HSpec test for this:

```<code>spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}
</code>```

The problem is that the id is a UUID generated by the database. I want to assert that the id is a string to make the test pass.

How can I achieve this?

答:
Can you create the record, then use its id value to create the record you're comparing against? Something like:

```<code>new <- newPersistentEntity "myName"
new `shouldBe` Entity { id = (id new), name = "myName" }
</code>```

(Note: don't have enough information to test this code, treat this as somewhat pseudo code).

As a side note, your code doesn't look like normal Persistent code, so I'm assuming you're using a different library.

Body:
I have a data class Entity which is defined like this:

data Entity = Entity { id :: String, name :: String }

and a function that returns IO Entity:

newPersistentEntity :: String -> IO Entity

And I'd like to write an HSpec test for this:

spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}

The problem is that the id is a UUID generated by the database. I want to assert that the id is a string to make the test pass.

How can I achieve this?

Body:
Can you create the record, then use its id value to create the record you're comparing against? Something like:

new <- newPersistentEntity "myName"
new `shouldBe` Entity { id = (id new), name = "myName" }

(Note: don't have enough information to test this code, treat this as somewhat pseudo code).

As a side note, your code doesn't look like normal Persistent code, so I'm assuming you're using a different library.


问:
How to make string as an Array Object in JQuery
I have got below string values in a variable.

```<code>var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"},
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'
</code>```

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below

```<code>$.fn.liveBanner = function(myArryObject,optional_options)
    {
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});
</code>```

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

```<code>             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);
</code>```

the above code is giving below error

```<code>Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'
</code>```

答: Try jQuery.parseJSON.

ContentLicense: CC BY-SA 2.5

Body:
I have got below string values in a variable.

var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"},
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below

$.fn.liveBanner = function(myArryObject,optional_options)
    {
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);

the above code is giving below error

Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'

Body: Try jQuery.parseJSON.


问:
Call Up FileMaker Record Based on Value of Javascript Variable in Web Viewer?
I am working on an app in FileMaker that includes a web map displayed through the web viewer.

I want the user to be able to select a feature within the web map and then call up the corresponding record in FileMaker. The web map features (GeoJSON) and the FileMaker records each have a corresponding ID column.

I already know how to pass the ID of a map feature to a js variable on a click event, but I do not know how to pass the value of this variable to FileMaker. Is this even possible? I hear FileMaker does not play well with others.

I have experience building interactive web maps but am relatively new to FileMaker.

Thanks!

答:
In fact, FileMaker play very well with others. The way to pass the value from the webviewer back to FileMaker is by calling "fmp://" url through JavaScript. You can call a FileMaker Script and pass it a record ID as a parameter, just make sure all script steps in the targetFileMaker script are server compatible.

Here is info on fmp protocol: https://www.filemaker.com/help/14/fmp/en/html/sharing_data.17.6.html


问:
WSO2 Api Manager: how to see the requested URL
WSO2 maps the requested Url called in it to an Url in another server. How can see the mapped URL that WSO2 effectively called?</p>

答:
For debugging, another option you have is enabling wire logs.

1) Uncomment below line in <APIM_HOME>/repository/conf/log4j.properties

```<code>log4j.logger.org.apache.synapse.transport.http.wire=DEBUG
</code>```

2) Restart the Server.

3) Send a request and wire logs can be found in console and <APIM_HOME>/repository/logs/wso2carbon.log file.

Body:
For debugging, another option you have is enabling wire logs.

1) Uncomment below line in <APIM_HOME>/repository/conf/log4j.properties

log4j.logger.org.apache.synapse.transport.http.wire=DEBUG

2) Restart the Server.

3) Send a request and wire logs can be found in console and <APIM_HOME>/repository/logs/wso2carbon.log file.


问:
How to detect in real time a "knee/elbow" (maximal curvature) in a curve
In the following curve (blue line) I'm trying to detect the "knee/elbow" which should be located around x = 2.5

This is the set of values I'm using:

x = {-10, -9, -8, -7, -6, -5, -4, -3, -2 , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

y = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 107, 122, 145, 176, 215, 262, 317, 380, 451, 530, 617}

I have tried the Kneedle algorithm and the formal definition of the curvature of a graph (signed curvature). The problem I have with the Kneedle algorithm is that in the real time application (embedded system) I don't know which will be the maximal value of the y axis, so I can't properly normalize the points nor find a slope value which works for all the cases. When using the formal definition of the curvature of a graph I try to fit the curve with an order 5 polynomial (green line) and then get the values of the derivatives to calculate the curvature. Nevertheless, this method finds the curvature around x = -2 as there is a curvature around that point because of the polynomial.

Could somebody suggest me a way to detect the knee/elbow?

答:
This is not a continuous curve, nor an approximation of a continuous curve, so we don't have to waste time here: you have a simple polygon. The polygon equivalent to "radius of curvature" is the difference in angle of incidence and angle of refraction: the smaller that difference is, the larger the radius of "curvature" is.

Provided you sample your data properly, we can compute the angular difference at each data point:

```<code>for (i=1, i<p.length -1):
  vector1 = p[i] - p[i-1] // assuming your language of choice has points as primitives
  vector2 = p[1+1] - p[i] // if not, you'll have to extract x/y separately.
  p[i].angle = findAngle(vector1,vector2)
</code>```

The findAngle function should be easy enough to implement, there are a million tutorials on how to implement this in your favourite language (it's basic arithemtic in many, and even built-in for some, languages). And that's it, we've turned our 2D data into 3D data with (x,y,z) coordinates in which z represents the local angle in travel across the point.

To then find any "knee", we can look at all sets of three data points (x-1), (x), and (x+1) and consider those x where the local angular difference is larger than the angular differences of its neighbours. The x with the biggest difference is the "winner": you've found your knee. (or really, a knee, since point data makes zero promises not to go up and down many many times, resulting in a polygon with lots of inflections)

```<code>knee = undefined
max_diff = 0;
for (i=1, i<p.length -1):
  a = p[i].angle

  a1 = p[i-1].angle
  d1 = a1-a

  a3 = p[i+1].angle
  d2 = a3-a

  diff = ... // there's a few ways to compute this
  p[i].diff = diff // always useful if we need to do more work later

  if (diff > max_diff):
    max_diff = diff
    knee = p[i]
</code>```

I've left the diff computation up to you, because maybe you just want d1+d2, or (d1+d2)/2, or maybe you want to switch based on whether d1 or d2 (but not both) are 0, etc.

The important thing to note here, of course, is that we can do all these things "in one go", as we gather data points, since new points don't affect the position of old points, so at some point n, we already know the angles up to n-1 and we already know the knees up to n-2, so we can compute all these values in a single linear pass. Nice and efficient.

This approach is analogous to finding the root(s) of the  derivative of a data-fitting curve, but when all we have is numerical data, sometimes the most correct approach is to work with that data, not with "a presumed reconstruction of the original thing you derived the data from". In this case, you have no idea what your data source is doing between sample points. Maybe it's well behaved, maybe it's not, but you don't know, so it's well worth not wasting cycles on complicating the problem and instead work directly with the properties you know are true (and of course, what they are true for: these are sensor readings and your sensor can absolutely be noisy or even faulty).

Body:
This is not a continuous curve, nor an approximation of a continuous curve, so we don't have to waste time here: you have a simple polygon. The polygon equivalent to "radius of curvature" is the difference in angle of incidence and angle of refraction: the smaller that difference is, the larger the radius of "curvature" is.

Provided you sample your data properly, we can compute the angular difference at each data point:

for (i=1, i<p.length -1):
  vector1 = p[i] - p[i-1] // assuming your language of choice has points as primitives
  vector2 = p[1+1] - p[i] // if not, you'll have to extract x/y separately.
  p[i].angle = findAngle(vector1,vector2)

The findAngle function should be easy enough to implement, there are a million tutorials on how to implement this in your favourite language (it's basic arithemtic in many, and even built-in for some, languages). And that's it, we've turned our 2D data into 3D data with (x,y,z) coordinates in which z represents the local angle in travel across the point.

To then find any "knee", we can look at all sets of three data points (x-1), (x), and (x+1) and consider those x where the local angular difference is larger than the angular differences of its neighbours. The x with the biggest difference is the "winner": you've found your knee. (or really, a knee, since point data makes zero promises not to go up and down many many times, resulting in a polygon with lots of inflections)

knee = undefined
max_diff = 0;
for (i=1, i<p.length -1):
  a = p[i].angle

  a1 = p[i-1].angle
  d1 = a1-a

  a3 = p[i+1].angle
  d2 = a3-a

  diff = ... // there's a few ways to compute this
  p[i].diff = diff // always useful if we need to do more work later

  if (diff > max_diff):
    max_diff = diff
    knee = p[i]

I've left the diff computation up to you, because maybe you just want d1+d2, or (d1+d2)/2, or maybe you want to switch based on whether d1 or d2 (but not both) are 0, etc.

The important thing to note here, of course, is that we can do all these things "in one go", as we gather data points, since new points don't affect the position of old points, so at some point n, we already know the angles up to n-1 and we already know the knees up to n-2, so we can compute all these values in a single linear pass. Nice and efficient.

This approach is analogous to finding the root(s) of the  derivative of a data-fitting curve, but when all we have is numerical data, sometimes the most correct approach is to work with that data, not with "a presumed reconstruction of the original thing you derived the data from". In this case, you have no idea what your data source is doing between sample points. Maybe it's well behaved, maybe it's not, but you don't know, so it's well worth not wasting cycles on complicating the problem and instead work directly with the properties you know are true (and of course, what they are true for: these are sensor readings and your sensor can absolutely be noisy or even faulty).


问:
Keeping FPS in a certain range with three.js
Having an instance of WebGLRenderer created with antialias = true results in noticeable performance issues as resolution grows, especially on retina displays (window.devicePixelRatio === 2).

Since it's not possible to change the antialiasing mode on the fly, the question is: how to automatically adjust the pixel ratio trying to keep FPS higher than a certain threshold (e.g. 30)?

答:
The idea is to monitor FPS in the rendering loop (by measuring intervals between requestAnimationFrame calls) and decreasing or increasing DPR accordingly.

"Monitoring" means recording those intervals into an array, removing min/max values (to avoid peaks), taking an average and comparing it with predefined thresholds.

const highFrequencyThreshold = 20; // ~50 FPS
const lowFrequencyThreshold = 34;  // ~30 FPS

const minDpr = 0.5;
const maxDpr = window.devicePixelRatio;
const deltaDpr = 0.1;

const relaxPeriod = 4000;
const accumulatorLength = 20;

const frameTimestamp = performance.now();
const frequencyAccumulator = [];
const lastUpdatedAt = null;

const renderer = new WebGLRenderer({
  antialias: true,
});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

animate();

function animate(timestamp: number = performance.now()) {
  requestAnimationFrame(animate);

  monitor(frameTimestamp, timestamp);
  frameTimestamp = timestamp;

  // animation calculations and rendering
  // ...
}

function monitor(frameTimestamp: number, now: number) {
  collectFrequency(now - frameTimestamp);

  // accumulator is not fully filled
  if (frequencyAccumulator.length < accumulatorLength) {
    return;
  }

  // an update happened recently
  if (now - lastUpdatedAt < relaxPeriod) {
    return;
  }

  const dpr = renderer.getPixelRatio();
  const frequencyMedian = median(...frequencyAccumulator);

  if (frequencyMedian > lowFrequencyThreshold && dpr > minDpr) {
    updateDpr(dpr, -deltaDpr, now);
  } else if (frequencyMedian < highFrequencyThreshold && dpr < maxDpr) {
    updateDpr(dpr, deltaDpr, now);
  }
}

function collectFrequency(frequency: number) {
  if (frequency > 0) {
    frequencyAccumulator.push(frequency);
  }

  if (frequencyAccumulator.length > accumulatorLength) {
    frequencyAccumulator.shift();
  }
}

function updateDpr(dpr: number, delta: number, now: number) {
  renderer.setPixelRatio(dpr + delta);
  frequencyAccumulator = [];
  lastUpdatedAt = now;
}

function median(...elements: number[]): number {
  const indexOfMin = elements.indexOf(Math.min(...elements));
  const indexOfMax = elements.indexOf(Math.max(...elements));
  const noMinMax = elements.filter((_, index) => index !== indexOfMin && index !== indexOfMax);

  return average(...noMinMax);
}

function average(...elements: number[]): number {
  return elements.reduce((sum, value) => sum + value, 0) / elements.length;
}
```

Note that updating the DPR could result in short-time animation freezing.

Also, something more clever could be used for balancing the DPR value (rather than calling the updateDpr() with linear step of 0.1), e.g. bisectional search.

Body:
The idea is to monitor FPS in the rendering loop (by measuring intervals between requestAnimationFrame calls) and decreasing or increasing DPR accordingly.

"Monitoring" means recording those intervals into an array, removing min/max values (to avoid peaks), taking an average and comparing it with predefined thresholds.

const highFrequencyThreshold = 20; // ~50 FPS
const lowFrequencyThreshold = 34;  // ~30 FPS

const minDpr = 0.5;
const maxDpr = window.devicePixelRatio;
const deltaDpr = 0.1;

const relaxPeriod = 4000;
const accumulatorLength = 20;

const frameTimestamp = performance.now();
const frequencyAccumulator = [];
const lastUpdatedAt = null;

const renderer = new WebGLRenderer({
  antialias: true,
});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

animate();

function animate(timestamp: number = performance.now()) {
  requestAnimationFrame(animate);

  monitor(frameTimestamp, timestamp);
  frameTimestamp = timestamp;

  // animation calculations and rendering
  // ...
}

function monitor(frameTimestamp: number, now: number) {
  collectFrequency(now - frameTimestamp);

  // accumulator is not fully filled
  if (frequencyAccumulator.length < accumulatorLength) {
    return;
  }

  // an update happened recently
  if (now - lastUpdatedAt < relaxPeriod) {
    return;
  }

  const dpr = renderer.getPixelRatio();
  const frequencyMedian = median(...frequencyAccumulator);

  if (frequencyMedian > lowFrequencyThreshold && dpr > minDpr) {
    updateDpr(dpr, -deltaDpr, now);
  } else if (frequencyMedian < highFrequencyThreshold && dpr < maxDpr) {
    updateDpr(dpr, deltaDpr, now);
  }
}

function collectFrequency(frequency: number) {
  if (frequency > 0) {
    frequencyAccumulator.push(frequency);
  }

  if (frequencyAccumulator.length > accumulatorLength) {
    frequencyAccumulator.shift();
  }
}

function updateDpr(dpr: number, delta: number, now: number) {
  renderer.setPixelRatio(dpr + delta);
  frequencyAccumulator = [];
  lastUpdatedAt = now;
}

function median(...elements: number[]): number {
  const indexOfMin = elements.indexOf(Math.min(...elements));
  const indexOfMax = elements.indexOf(Math.max(...elements));
  const noMinMax = elements.filter((_, index) => index !== indexOfMin && index !== indexOfMax);

  return average(...noMinMax);
}

function average(...elements: number[]): number {
  return elements.reduce((sum, value) => sum + value, 0) / elements.length;
}

Note that updating the DPR could result in short-time animation freezing.

Also, something more clever could be used for balancing the DPR value (rather than calling the updateDpr() with linear step of 0.1), e.g. bisectional search.


问:
My persistenceManager is null
I have Interface which is defined as

```<code>@Local
public interface MyPersistenceManagerLocal {

  public List<PropertyList> getPropertyList(int id);

}
</code>```

and implentaion class for above interface is

```<code>@Stateless
public class MyPersistenceManagerBean implements MyPersistenceManagerLocal {

  @PersistenceContext(unitName = PersistentSettings.PERSIST_NAME)
  private EntityManager entityManager;

  @Override
  public List<PropertyList> getPropertyList(int id) {
    System.out.println("inside MyPersistenceManagerBean.getPropertyList()");
    ......
    ......
    ......
  }
}
</code>```

and i ma calling this in another call

```<code>@Stateless
public class ClientImpl implements Client {

  @EJB
  MyPersistenceManagerLocal persistenceManager;

  final List<PropertyList> dbList = persistenceManager.getPropertyList(id);

}
</code>```

i am getting NullPointerException on

```<code>final List<PropertyList> dbList = persistenceManager.getPropertyList(id);
</code>```

in debug mode i got persistenceManager is null.

i am new in EJB and JPA not able to solve this. any help why i am getting persistenceManager as null

答:
You are getting NPE because container haven't injected the required bean yet.
You need to set it in @PostConstruct method i.e.

```<code>@Stateless public class ClientImpl implements Client {

   @EJB MyPersistenceManagerLocal persistenceManager;

   private List dbList;
   @PostConstruct
   public void init(){
        dblist = persistenceManager.getDbList();
   }
</code>```

}

Title: My persistenceManager is null

Body:
I have Interface which is defined as

@Local
public interface MyPersistenceManagerLocal {

  public List<PropertyList> getPropertyList(int id);

}

and implentaion class for above interface is

@Stateless
public class MyPersistenceManagerBean implements MyPersistenceManagerLocal {

  @PersistenceContext(unitName = PersistentSettings.PERSIST_NAME)
  private EntityManager entityManager;

  @Override
  public List<PropertyList> getPropertyList(int id) {
    System.out.println("inside MyPersistenceManagerBean.getPropertyList()");
    ......
    ......
    ......
  }
}

and i ma calling this in another call

@Stateless
public class ClientImpl implements Client {

  @EJB
  MyPersistenceManagerLocal persistenceManager;

  final List<PropertyList> dbList = persistenceManager.getPropertyList(id);

}

i am getting NullPointerException on

final List<PropertyList> dbList = persistenceManager.getPropertyList(id);

in debug mode i got persistenceManager is null.

i am new in EJB and JPA not able to solve this. any help why i am getting persistenceManager as null

Body:
You are getting NPE because container haven't injected the required bean yet.
You need to set it in @PostConstruct method i.e.

@Stateless public class ClientImpl implements Client {

   @EJB MyPersistenceManagerLocal persistenceManager;

   private List dbList;
   @PostConstruct
   public void init(){
        dblist = persistenceManager.getDbList();
   }

}


问:
Deadlock in Entity Framework
I have a Webservice that receives a couple requests at nearly the same time.

If that happens the Transactions of the two requests deadlock and i have to rollback an rerun on of them.

```<code>        using (var context = new DbContext())
        using (var dbContextTransaction = context.Database.BeginTransaction(IsolationLevel.Serializable))
        {
                var subscription = context.Subscriptions.FirstOrDefault(x => x.Provider == provider);
                if (subscription == null)
                {
                   */Insert*/
                }
                else
                {
                   /*Update*/
                }
                context.SaveInTransaction(null);
                dbContextTransaction.Commit();
                }
</code>```

As i understand both of the Requests enter the Transaction and read the Subscriptions Table. By the time the are ready to commit, they are deadlocked because they can't insert values in a data range read by another transaction (IsolationLevel.Serializable).

If i don't make the TransactionLevel Serializeable, one of the Requests fails to meet the Unique constraints of the Provider Column and gets Rollbacked.

What should i do to prevent deadlocks?

答:
If i don't make the TransactionLevel Serializeable, one of the Requests fails to meet the Unique constraints of the Provider Column and gets Rollbacked.

You can :

1) Handle the PK violation  / Deadlock and proceed to update the existing row.  Note you should use READ COMMITTED and handle the PK violation since you know that the session that gets the failure can proceed to update.  With SERIALIZABLE you can get a deadlock on either the INSERT or the UPDATE.

2) Use raw SQL with a lock hint to make one session wait for the other.

The correct lock hint is (UPDLOCK,SERIALIZABLE).  And the lock hint is still required if you use MERGE.  See https://blogs.msdn.microsoft.com/dbrowne/2013/02/25/why-is-tsql-merge-failing-with-a-primary-key-violation-isnt-it-atomic/

3) Call sp_getapplock at the beginning of the transaction to ensure only one session has the lock.  Note a CLR lock will only work if you have a single instance of your application.  For a client/server app, or a web farm a CLR lock will not work.

You can add a method to your DbContext something like:

```<code>public void GetAppLock(string lockName)
{
    this.Database.ExecuteSqlCommand("exec sp_getapplock @name, 'exclusive'", new System.Data.SqlClient.SqlParameter("@name",lockName));
}
</code>```

Title: Deadlock in Entity Framework

Body:
I have a Webservice that receives a couple requests at nearly the same time.

If that happens the Transactions of the two requests deadlock and i have to rollback an rerun on of them.

        using (var context = new DbContext())
        using (var dbContextTransaction = context.Database.BeginTransaction(IsolationLevel.Serializable))
        {
                var subscription = context.Subscriptions.FirstOrDefault(x => x.Provider == provider);
                if (subscription == null)
                {
                   */Insert*/
                }
                else
                {
                   /*Update*/
                }
                context.SaveInTransaction(null);
                dbContextTransaction.Commit();
                }

As i understand both of the Requests enter the Transaction and read the Subscriptions Table. By the time the are ready to commit, they are deadlocked because they can't insert values in a data range read by another transaction (IsolationLevel.Serializable).

If i don't make the TransactionLevel Serializeable, one of the Requests fails to meet the Unique constraints of the Provider Column and gets Rollbacked.

What should i do to prevent deadlocks?

Body:
If i don't make the TransactionLevel Serializeable, one of the Requests fails to meet the Unique constraints of the Provider Column and gets Rollbacked.

You can :

1) Handle the PK violation  / Deadlock and proceed to update the existing row.  Note you should use READ COMMITTED and handle the PK violation since you know that the session that gets the failure can proceed to update.  With SERIALIZABLE you can get a deadlock on either the INSERT or the UPDATE.

2) Use raw SQL with a lock hint to make one session wait for the other.

The correct lock hint is (UPDLOCK,SERIALIZABLE).  And the lock hint is still required if you use MERGE.  See https://blogs.msdn.microsoft.com/dbrowne/2013/02/25/why-is-tsql-merge-failing-with-a-primary-key-violation-isnt-it-atomic/

3) Call sp_getapplock at the beginning of the transaction to ensure only one session has the lock.  Note a CLR lock will only work if you have a single instance of your application.  For a client/server app, or a web farm a CLR lock will not work.

You can add a method to your DbContext something like:

public void GetAppLock(string lockName)
{
    this.Database.ExecuteSqlCommand("exec sp_getapplock @name, 'exclusive'", new System.Data.SqlClient.SqlParameter("@name",lockName));
}


问:
Not matched rows in B join with some row in A
Example data:

```<code>Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A
</code>```

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

```<code>x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1
</code>```

答:
If my understanding is right, it is not just a left join question, it is something like this:

```<code>-- Creating example
CREATE TABLE #T1 (x int, y char(1) null)
CREATE TABLE #T2 (x int, y char(1) null)

-- Loading tables
INSERT INTO #T1
SELECT 1,'A'
UNION ALL SELECT 1,'B'
UNION ALL SELECT 1,'C'
UNION ALL SELECT 1,null
UNION ALL SELECT 2,'M'
UNION ALL SELECT 2,'N'

INSERT INTO #T2
SELECT 1 ,'A'
UNION ALL SELECT 1 ,'D'
UNION ALL SELECT 2 ,'M'
UNION ALL SELECT 2 ,'N'
UNION ALL SELECT 2 ,'M'
UNION ALL SELECT 1 ,'A'

SELECT t1.x, t1.y, count(t2.y) FROM #T1 t1
LEFT JOIN #T2 t2 on t1.y = t2.y
LEFT JOIN #T2 t22 on t1.Y IS NULL AND  t22.y IS NULL
WHERE t1.y is not null
GROUP BY t1.x, t1.y
UNION ALL
SELECT t.x, t.y, (SELECT count(1) 'count' FROM #T2 t2
LEFT JOIN #T1 t1 on t1.y = t2.y
WHERE t1.y IS NULL
) FROM #T1 t WHERE t.y IS NULL
</code>```

I had to separate the problem in two.

Body:
Example data:

Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1

Body:
If my understanding is right, it is not just a left join question, it is something like this:

-- Creating example
CREATE TABLE #T1 (x int, y char(1) null)
CREATE TABLE #T2 (x int, y char(1) null)

-- Loading tables
INSERT INTO #T1
SELECT 1,'A'
UNION ALL SELECT 1,'B'
UNION ALL SELECT 1,'C'
UNION ALL SELECT 1,null
UNION ALL SELECT 2,'M'
UNION ALL SELECT 2,'N'

INSERT INTO #T2
SELECT 1 ,'A'
UNION ALL SELECT 1 ,'D'
UNION ALL SELECT 2 ,'M'
UNION ALL SELECT 2 ,'N'
UNION ALL SELECT 2 ,'M'
UNION ALL SELECT 1 ,'A'

SELECT t1.x, t1.y, count(t2.y) FROM #T1 t1
LEFT JOIN #T2 t2 on t1.y = t2.y
LEFT JOIN #T2 t22 on t1.Y IS NULL AND  t22.y IS NULL
WHERE t1.y is not null
GROUP BY t1.x, t1.y
UNION ALL
SELECT t.x, t.y, (SELECT count(1) 'count' FROM #T2 t2
LEFT JOIN #T1 t1 on t1.y = t2.y
WHERE t1.y IS NULL
) FROM #T1 t WHERE t.y IS NULL

I had to separate the problem in two.


问:
How to apply FileField Button click in FF?
I have this html code :

```<code>    <form name="form1" id="form1" method="POST" action="">

    <div dir="rtl" style="position:absolute; left: 2px; top: 0px;">
       <input name="fileField2" type="file" class="accountItemFilefield" id="fileField2" />
    </div>
    <div style="position:absolute; z-index:2;">
         <img onclick="$('#fileField2').trigger('click'); " style="cursor:pointer" src="images/browse.png" width="83" height="29" alt="" />
   </div>

    </form>
</code>```

This code is not working in FF and it's working successfully in IE and I don't know what is the problem.

I also tried this code :

```<code>$('#fileField2').click();
</code>```

and this one :

```<code>document.getElementById('fileField2').click();
</code>```

all of them are working in IE bur not in FF.

How I can solve the problem?

Thanks in advance.

答:
This is a security restriction to prevent malicious sites from unexpectedly showing the file upload dialog. </p>

<p>I don't think there is a way around this. In fact, I'm surprised that IE still allows it.  </p>

Body:
I have this html code :

    <form name="form1" id="form1" method="POST" action="">

       <input name="fileField2" type="file" class="accountItemFilefield" id="fileField2" />

    </form>

This code is not working in FF and it's working successfully in IE and I don't know what is the problem.

I also tried this code :

$('#fileField2').click();

and this one :

document.getElementById('fileField2').click();

all of them are working in IE bur not in FF.

How I can solve the problem?

Thanks in advance.

Body:
This is a security restriction to prevent malicious sites from unexpectedly showing the file upload dialog.

I don't think there is a way around this. In fact, I'm surprised that IE still allows it.


问:
Excel VBA: cell referencing
I have a problem with cell referencing and I don't know if a solution exists.

Using VBA code I'm writing into a cell the reference to a different cell using the syntax:

```<code>activecell.formula = "=" & Cells(A1).address
</code>```

Now I need to copy this formula for thousands of cells. Each cell should refer to a sequential cell (A1,A2,A3....A120..).

The problem I have is that using

Cells(A1).address

it fixes the Cells(A1). When I use the autofill function, I have thousands of cells all referencing the same cells(A1), while I would need the reference to be dynamic and every time referencing the next cell (A2,A3,A4..). And I need to use the autofill function because if I write the formula on each cell using a loop and fixed reference, it would take hours for the code to run (there are thousands of cells as explained before)

I should then use the relative reference format:

```<code>activecell.formulaR1C1 = ...
</code>```

but the cells(A1)  are not always at the same distance from my activecell.

via VBA I can calculate how far each time it is from my activecell, but how can I use this data with R1C1 notation?

so, lets say that using

```<code>row.count
</code>```

function I can calculate the first cell to which I want to refer to,(this time) is on row 100 and column 3. So, I have: lastrow = 100, column = 3. Please note, the row 100 vary every time I run the macro. My activecell is cells(5,5)

this is what I would like to use:

```<code>Sub problemsolved ()

Dim lastrow as string
Dim RowL as string
Dim CoL as string

lastrow = activesheet.cells(rows.count, 1).End(xlUp).row

cells(5,5).select

Rol = lastrow - 5
Col = 3 -5

activecell.formulaR1C1 = "=R[Rol]C[Col]"

selection.autofill Destination:=Range(cells(5, 5), cells(10005, 5))

end sub
</code>```

assuming lastrow is = 100
I need to have the following result:

```<code>cell(5,5): =cells(100,3)
cell(6,5): =cells(101,3)
cell(7,5): = cells(102,3)
.....
cell(10005,5): = cells(10100,3)
</code>```

of course, I've tried the syntax:

```<code>activecell.formulaR1C1 = "=R[lastrow]C[3]"
</code>```

but it doesn't work, so how can I do it?
anybody has an idea?

thanks

答:
Use:

```<code>With ActiveSheet
    .Range(.Cells(5,5),.Cells(10005,5)).FormulaR1C1 = "=R[" & RowL & "]C[" & col & "]"
End With
</code>```

no need for autofill

So

```<code>Sub problemsolved ()

Dim lastrow as Long
Dim RowL as Long
Dim CoL as Long

lastrow = activesheet.cells(rows.count, 1).End(xlUp).row

Rowl = lastrow - 5
Col = 3 -5

With ActiveSheet
    .Range(.Cells(5,5),.Cells(10005,5)).FormulaR1C1 = "=R[" & RowL & "]C[" & col & "]"
End With

end sub
</code>```

Title: Excel VBA: cell referencing

Body:
I have a problem with cell referencing and I don't know if a solution exists.

Using VBA code I'm writing into a cell the reference to a different cell using the syntax:

activecell.formula = "=" & Cells(A1).address

Now I need to copy this formula for thousands of cells. Each cell should refer to a sequential cell (A1,A2,A3....A120..).

The problem I have is that using

Cells(A1).address

it fixes the Cells(A1). When I use the autofill function, I have thousands of cells all referencing the same cells(A1), while I would need the reference to be dynamic and every time referencing the next cell (A2,A3,A4..). And I need to use the autofill function because if I write the formula on each cell using a loop and fixed reference, it would take hours for the code to run (there are thousands of cells as explained before)

I should then use the relative reference format:

activecell.formulaR1C1 = ...

but the cells(A1)  are not always at the same distance from my activecell.

via VBA I can calculate how far each time it is from my activecell, but how can I use this data with R1C1 notation?

so, lets say that using

row.count

function I can calculate the first cell to which I want to refer to,(this time) is on row 100 and column 3. So, I have: lastrow = 100, column = 3. Please note, the row 100 vary every time I run the macro. My activecell is cells(5,5)

this is what I would like to use:

Sub problemsolved ()

Dim lastrow as string
Dim RowL as string
Dim CoL as string

lastrow = activesheet.cells(rows.count, 1).End(xlUp).row

cells(5,5).select

Rol = lastrow - 5
Col = 3 -5

activecell.formulaR1C1 = "=R[Rol]C[Col]"

selection.autofill Destination:=Range(cells(5, 5), cells(10005, 5))

end sub

assuming lastrow is = 100
I need to have the following result:

cell(5,5): =cells(100,3)
cell(6,5): =cells(101,3)
cell(7,5): = cells(102,3)
.....
cell(10005,5): = cells(10100,3)

of course, I've tried the syntax:

activecell.formulaR1C1 = "=R[lastrow]C[3]"

but it doesn't work, so how can I do it?
anybody has an idea?

thanks

Body:
Use:

With ActiveSheet
    .Range(.Cells(5,5),.Cells(10005,5)).FormulaR1C1 = "=R[" & RowL & "]C[" & col & "]"
End With

no need for autofill

So

Sub problemsolved ()

Dim lastrow as Long
Dim RowL as Long
Dim CoL as Long

lastrow = activesheet.cells(rows.count, 1).End(xlUp).row

Rowl = lastrow - 5
Col = 3 -5

With ActiveSheet
    .Range(.Cells(5,5),.Cells(10005,5)).FormulaR1C1 = "=R[" & RowL & "]C[" & col & "]"
End With

end sub


问:
Using DNS to redirect to another URL with a path
I'm trying to redirect a domain to another via DNS.

I know that using IN CNAME it's posible.

```<code>www.proof.com IN CNAME www.proof-two.com.
</code>```

What i need is a redirection with a path. When someone types www.proof.com, it should take them to to www.proof-two.com/path/index.htm

I know it can be done using Web Server facilities, but I need DNS redirection.

Is this possible?

答: You can use htaccess rewrite mod, rewrite to the subfolder if the user is requesting one specific domain not the other.</p>

Body:
I'm trying to redirect a domain to another via DNS.

I know that using IN CNAME it's posible.

www.proof.com IN CNAME www.proof-two.com.

What i need is a redirection with a path. When someone types www.proof.com, it should take them to to www.proof-two.com/path/index.htm

I know it can be done using Web Server facilities, but I need DNS redirection.

Is this possible?


问:
Java get class constant for closed generic type (instance of Class<T1<T2>>)
I come from a C# background and am having trouble with Java generics. I am trying to call a generic method that requires an instance of Class<T> as a param. Normally this is a matter of passing SimpleType.class. In this case though, the type I need is not a simple type, but has its own type parameter that needs to be included in the Class instance (i.e. I need a Class<OuterType<InnerType>>). How do I get this?

Note: To make things a bit more complicated, this is taking place within another generic method. So while the "outer" type is known at compile type, the inner is known only through its own Class instance. See the code:

```<code>public <T> T deserialize(InputStream stream, Class<T> clazz) {
    com.fasterxml.jackson.databind.ObjectMapper mapper = getJsonMapper();
    //Need an instance of Class<MessageWrapper<T>>
    MessageWrapper<T> wrapper = mapper.readValue(stream, MessageWrapper.class);
    return wrapper.message;
}

private class MessageWrapper<T> {
    public T message;
}
</code>```

答:
What you can try is this:

```<code>public <T> T deserialize(InputStream stream, Class<T> clazz) {
    com.fasterxml.jackson.databind.ObjectMapper mapper = getJsonMapper();
    //Need an instance of Class<MessageWrapper<T>>
    MessageWrapper<T> wrapper =mapper.readValue(jsonString, new TypeReference<MessageWrapper<T>>() {});
    return wrapper.message;
}
</code>```

As well, the class should be or static, or public within its own file:

```<code>public class MessageWrapper<T> {
    public T message;
}
</code>```

Or:

```<code>private static class MessageWrapper<T> {
    public T message;
}
</code>```

Body:
I come from a C# background and am having trouble with Java generics. I am trying to call a generic method that requires an instance of Class<T> as a param. Normally this is a matter of passing SimpleType.class. In this case though, the type I need is not a simple type, but has its own type parameter that needs to be included in the Class instance (i.e. I need a Class<OuterType<InnerType>>). How do I get this?

Note: To make things a bit more complicated, this is taking place within another generic method. So while the "outer" type is known at compile type, the inner is known only through its own Class instance. See the code:

public <T> T deserialize(InputStream stream, Class<T> clazz) {
    com.fasterxml.jackson.databind.ObjectMapper mapper = getJsonMapper();
    //Need an instance of Class<MessageWrapper<T>>
    MessageWrapper<T> wrapper = mapper.readValue(stream, MessageWrapper.class);
    return wrapper.message;
}

private class MessageWrapper<T> {
    public T message;
}

Body:
What you can try is this:

public <T> T deserialize(InputStream stream, Class<T> clazz) {
    com.fasterxml.jackson.databind.ObjectMapper mapper = getJsonMapper();
    //Need an instance of Class<MessageWrapper<T>>
    MessageWrapper<T> wrapper =mapper.readValue(jsonString, new TypeReference<MessageWrapper<T>>() {});
    return wrapper.message;
}

As well, the class should be or static, or public within its own file:

public class MessageWrapper<T> {
    public T message;
}

Or:

private static class MessageWrapper<T> {
    public T message;
}