问:
Get foreign key in external content type to show up in list view
I have come across blogs about how to setup an external content type (e.g. http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2010/02/02/it-s-easy-to-configure-an-external-list-with-business-connectivity-services-bcs-in-sharepoint-foundation-2010.aspx) but I have not seen any examples of what to do when your external SQL DB has foreign keys.

For example.  I have a database that has orders and customers.  An order has one and only one customer and a customer can have many orders.  How can I setup external content types in such a way that when in the list view of these external content types, I can jump between and possible lookup values to that other type?

答:
I have written this blog post which shows how to do what you are after:

In Visual Studio

http://www.lightningtools.com/blog/archive/2011/01/10/sharepoint-external-listndash-using-the-picker-for-foreign-keys.aspx

In SharePoint Designer

http://lightningtools.com/blog/archive/2010/06/14/lookup-foreign-key-values-in-external-lists.aspx

Hope these help


来源: stackexchange

问:
Angular - detecting when two subscriptions have updated
In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

Thanks,

Component.TS

```<code>ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) =>
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) =>
 {
   this.dataB= dataBJSON
 }
</code>```

DataService

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}
</code>```

答:
You can use Observable#forkJoin function on the Observables. It emits the last value from each when all observables complete,

```<code>Observable.forkJoin(this.dataService.dataA(), this.dataService.dataB())
          .subscribe(val => /* val is an array */)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

Thanks,

Component.TS

ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) =>
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) =>
 {
   this.dataB= dataBJSON
 }

DataService

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}

Body:
You can use Observable#forkJoin function on the Observables. It emits the last value from each when all observables complete,

Observable.forkJoin(this.dataService.dataA(), this.dataService.dataB())
          .subscribe(val => /* val is an array */)


问:
Application user and relation between other tables (entities)
I'm trying to associate Application user with UserTask application table. But I get the bellow error

InvalidOperationException: Unable to determine the relationship represented by navigation property 'ApplicationUser.UserTask' of type 'UserTask'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

I use NetCore 2.0.3

```<code>public class UserTask
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserTaskID { get; set; }

        public string Description { get; set; }

        [ForeignKey("OwnerUserID")]
        public string TaskOwnerId { get; set; }

        [ForeignKey("ExecutorUserID")]
        public string TaskExecutorId { get; set; }

        public virtual ApplicationUser OwnerUserID { get; set; }
        public virtual ApplicationUser ExecutorUserID { get; set; }
    }

 public class ApplicationUser : IdentityUser
    {
       [ForeignKey("UserTaskID")]
       public int UserTaskID { get; set; }

       public UserTask UserTask { get; set; }
    }
</code>```

controler

```<code>public IActionResult Create()
        {
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            return View();
        }

        // POST: UserTasks/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("UserTaskID,Description,TaskOwnerId,TaskExecutorId")] UserTask userTask)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userTask);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskOwnerId);

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskExecutorId);

            return View(userTask);
        }
</code>```

and the view

```<code><div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TaskOwnerId" class="control-label"></label>
                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>
            </div>
            <div class="form-group">
                <label asp-for="TaskExecutorId" class="control-label"></label>
                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TaskOwnerId" class="control-label"></label>
                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>
            </div>
            <div class="form-group">
                <label asp-for="TaskExecutorId" class="control-label"></label>
                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>
</code>```

Could you help me?

答:
Your problem here is two-fold:

You only have one navigation property for UserTask on ApplicationUser. There's two different navigation properties for ApplicationUser on UserTask, EF cannot map both relationships to just one foreign key on the other side, so if you have two navigation properties on one side, you need two on the other as well. For example:

```<code>public UserTask OwnedUserTask { get; set; }
public UserTask ExecutedUserTask { get; set; }
</code>```

Given that there's two relationships to the same entity, EF doesn't know which one on UserTask to map to which one on ApplicationUser, so you'll have to configure this:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ApplicationUser>()
        .HasOne(x => x.OwnedUserTask)
        .WithOne(x => x.OwnerUser);

    modelBuilder.Entity<ApplicationUser>()
        .HasOne(x => x.ExecutedUserTask)
        .WithOne(x => x.ExecutorUser);
}
</code>```

That said, this being a one-to-one doesn't really make sense. Tasks are something you generally have multiple of (If only I had only just one task to perform ever!). As a result, this should likely be a one-to-many, which would then require you to change ApplicationUser to something like:

```<code>public class ApplicationUser : IdentityUser
{
   public ICollection<UserTask> OwnedUserTasks { get; set; }
   public ICollection<UserTask> ExecutedUserTasks { get; set; }
}
</code>```

Even with that change, the same problem as before exists: you have two relationships to the same entity, so you must add configuration to tell EF how to handle that. Only, now, you'll use HasMany instead of HasOne:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ApplicationUser>()
        .HasMany(x => x.OwnedUserTasks)
        .WithOne(x => x.OwnerUser);

    modelBuilder.Entity<ApplicationUser>()
        .HasMany(x => x.ExecutedUserTasks)
        .WithOne(x => x.ExecutorUser);
}
</code>```

Finally, it's worth mentioning that you can configure this on either side of the relationship. In other words, you could do Entity<UserTask> and then HasOne(x => x.OwnerUser).WithMany(x => x.OwnedUserTasks). It's entirely up to you which way you go.

Body:
I'm trying to associate Application user with UserTask application table. But I get the bellow error

InvalidOperationException: Unable to determine the relationship represented by navigation property 'ApplicationUser.UserTask' of type 'UserTask'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

I use NetCore 2.0.3

public class UserTask
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserTaskID { get; set; }

        public string Description { get; set; }

        [ForeignKey("OwnerUserID")]
        public string TaskOwnerId { get; set; }

        [ForeignKey("ExecutorUserID")]
        public string TaskExecutorId { get; set; }

        public virtual ApplicationUser OwnerUserID { get; set; }
        public virtual ApplicationUser ExecutorUserID { get; set; }
    }

 public class ApplicationUser : IdentityUser
    {
       [ForeignKey("UserTaskID")]
       public int UserTaskID { get; set; }

       public UserTask UserTask { get; set; }
    }

controler

public IActionResult Create()
        {
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            return View();
        }

        // POST: UserTasks/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("UserTaskID,Description,TaskOwnerId,TaskExecutorId")] UserTask userTask)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userTask);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskOwnerId);

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskExecutorId);

            return View(userTask);
        }

and the view

        <form asp-action="Create">

                <input asp-for="Description" class="form-control" />

                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>

                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

        <form asp-action="Create">

                <input asp-for="Description" class="form-control" />

                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>

                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

Could you help me?

Body:
Your problem here is two-fold:

You only have one navigation property for UserTask on ApplicationUser. There's two different navigation properties for ApplicationUser on UserTask, EF cannot map both relationships to just one foreign key on the other side, so if you have two navigation properties on one side, you need two on the other as well. For example:

public UserTask OwnedUserTask { get; set; }
public UserTask ExecutedUserTask { get; set; }

Given that there's two relationships to the same entity, EF doesn't know which one on UserTask to map to which one on ApplicationUser, so you'll have to configure this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ApplicationUser>()
        .HasOne(x => x.OwnedUserTask)
        .WithOne(x => x.OwnerUser);

    modelBuilder.Entity<ApplicationUser>()
        .HasOne(x => x.ExecutedUserTask)
        .WithOne(x => x.ExecutorUser);
}

That said, this being a one-to-one doesn't really make sense. Tasks are something you generally have multiple of (If only I had only just one task to perform ever!). As a result, this should likely be a one-to-many, which would then require you to change ApplicationUser to something like:

public class ApplicationUser : IdentityUser
{
   public ICollection<UserTask> OwnedUserTasks { get; set; }
   public ICollection<UserTask> ExecutedUserTasks { get; set; }
}

Even with that change, the same problem as before exists: you have two relationships to the same entity, so you must add configuration to tell EF how to handle that. Only, now, you'll use HasMany instead of HasOne:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ApplicationUser>()
        .HasMany(x => x.OwnedUserTasks)
        .WithOne(x => x.OwnerUser);

    modelBuilder.Entity<ApplicationUser>()
        .HasMany(x => x.ExecutedUserTasks)
        .WithOne(x => x.ExecutorUser);
}

Finally, it's worth mentioning that you can configure this on either side of the relationship. In other words, you could do Entity<UserTask> and then HasOne(x => x.OwnerUser).WithMany(x => x.OwnedUserTasks). It's entirely up to you which way you go.


问:
CSS position: Static is default but left/right/bottom/up attributes still works
I'm reading about CSS Position on Mozilla CSS

Definition for static

static

The element is positioned according to the normal flow of the document. The top, right, bottom, left, and z-index properties
  have no effect. This is the default value.

Definition for relative:

relative

The element is positioned according to the normal flow of the
  document, and then offset relative to itself based on the values of
  top, right, bottom, and left.

As I understand: (correct me if I was wrong)

static is default

left/right/bottom/up ... has no effect on static element.

But when I code CSS, I often don't put "position: ..." inside. I also use left/right/bottom/up attributes and I see it works. Is there any wrong with my understanding ?

Thanks

答: Yes, you're correct, positions are usually by default static. Maybe it could be the software changing the default positions of your elements? Try playing around with position : relative or position : absolute and see whether there are any changes, if no changes happen to the elements then that means they might have been given a different default position value</p>


问:
Why can't I iterate and print the contents of vector after using reserve to allocate storage?
Given below is a simple program which takes input into  a vector and trying to print the vector using iterator. Why doesn't it print the vector?? Everything seems to be alright.

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

int main() {
    int n,m,i;
    cin >> n >> m;
    vector<int> v;
    v.reserve(m);
    vector<int>::iterator it;

    for(i=0;i<m;i++)
     cin >> v[i];
   // for(i=0;i<m;i++)
    // cout << v[i];
    for(it = v.begin();it != v.end();it++)
      cout << *(it);
    return 0;
}
</code>```

If I input "4 3 1 2 3" why doesn't the program give any output?

答:
reserve does not do the same thing as resize. reserve is a hint to the allocator to try to "preallocate" the space needed to store a number of elements. As far as the vector is concerned, it's still size 0, which means its iterators will represent a range of 0 elements.

Change v.reserve(m); to v.resize(m);, and your issue should be resolved.

Body:
Given below is a simple program which takes input into  a vector and trying to print the vector using iterator. Why doesn't it print the vector?? Everything seems to be alright.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

int main() {
    int n,m,i;
    cin >> n >> m;
    vector<int> v;
    v.reserve(m);
    vector<int>::iterator it;

    for(i=0;i<m;i++)
     cin >> v[i];
   // for(i=0;i<m;i++)
    // cout << v[i];
    for(it = v.begin();it != v.end();it++)
      cout << *(it);
    return 0;
}

If I input "4 3 1 2 3" why doesn't the program give any output?


问:
unexpected value in my feet to meters converter with pure javascript
//I'm trying to get a result in meters out of an input in feet.

```<code>            <div id="inner-wrapper">
                <label for="feet-input">Enter feet
                </label>
                <input type="number" id="feet-input" placeholder="Feet">

                <label for="result">Result
                </label>
                <div id="result"></div>

                <button id="calculate" onclick="calculate()">Calculate</button>
                <button id="clear" onclick="clear()">Clear</button>
            </div>
</code>```

//For any number I type I get 0 as answer.

```<code>        var feetInput = document.getElementById("feet-input").value;
        var result = document.getElementById("result");
        var total;

        function calculate(){
            total = feetInput * 0.3048;
            result.innerHTML = total;
            return total;

        }

            function clear(){
                feetInput.value = "";
                result.value = "";

            }

    //For any number I type get 0 as result.
</code>```

For any number I type get 0 as answer.

答:
The only issue that you have is that the value from feet-input is ONLY read when the page is loaded.
You'll need to get the value of feet-input before you do the calculation.

Just add var feetInput = document.getElementById("feet-input").value; to the line immediately after function calculate(){

Codepen: https://codepen.io/DeathCamel57/pen/xPPGrp?editors=0010

ContentLicense: CC BY-SA 4.0

Body:
//I'm trying to get a result in meters out of an input in feet.

                Enter feet

                <input type="number" id="feet-input" placeholder="Feet">

                Result

                <button id="calculate" onclick="calculate()">Calculate</button>
                <button id="clear" onclick="clear()">Clear</button>

//For any number I type I get 0 as answer.

        var feetInput = document.getElementById("feet-input").value;
        var result = document.getElementById("result");
        var total;

        function calculate(){
            total = feetInput * 0.3048;
            result.innerHTML = total;
            return total;

        }

            function clear(){
                feetInput.value = "";
                result.value = "";

            }

    //For any number I type get 0 as result.

For any number I type get 0 as answer.


问:
Parse an array response in javascript
im working on an API request where i GET an http.response that is an array with one json object in it. But when i try to parse it or stringify it i with this code:

```<code>  var response = http.response;

try{
    var json = JSON.stringify(response);
    logInfo("status: " + json.status);
  } catch(e) { logInfo(e); }
</code>```

...I get this log anwser: status: undefined

How do I define the value? The Value is taken from a user on my webpage and can change.

This is the response i GET from the request:

```<code>[
{
"status": "DONE",
"plannedDeliveryDate": "2017-06-27",
"orderId": 2112312,
"userId": 123123
}
]
</code>```

This is the rest of my GET code:

```<code>loadLibrary("cus:json3.js");

var query = xtk.queryDef.create(
  <queryDef operation="select" schema={vars.targetSchema}>
    <select>
      <node expr="@userNumber"/>
    </select>
  </queryDef>
);

var res = query.ExecuteQuery();

//Buffer the auth key
var buffer = new MemoryBuffer();
buffer.fromString("username:password", "utf-8");

for each (var line in res) {

  var http = new HttpClientRequest();
  http.header["Authorization"] = "Basic " + buffer.toBase64(); //Basic Auth
  this.baseURL = "https://url..../data?user_id=" + line.@userNumber;
  http.url = this.baseURL;
  http.method = "GET"; //The GET request
  http.execute();

  var response = http.response;

try{
    var json = JSON.parse(response);
    logInfo("status: " + json[0].status);
  } catch(e) { logInfo(e); }
}
</code>```

答:
To parse json you use

```<code>JSON.parse(response);
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

```<code>JSON.stringify() does the opposite, it converts data into json
</code>```

Title: Parse an array response in javascript

Body:
im working on an API request where i GET an http.response that is an array with one json object in it. But when i try to parse it or stringify it i with this code:

  var response = http.response;

try{
    var json = JSON.stringify(response);
    logInfo("status: " + json.status);
  } catch(e) { logInfo(e); }

...I get this log anwser: status: undefined

How do I define the value? The Value is taken from a user on my webpage and can change.

This is the response i GET from the request:

[
{
"status": "DONE",
"plannedDeliveryDate": "2017-06-27",
"orderId": 2112312,
"userId": 123123
}
]

This is the rest of my GET code:

loadLibrary("cus:json3.js");

var query = xtk.queryDef.create(
  <queryDef operation="select" schema={vars.targetSchema}>
    <select>
      <node expr="@userNumber"/>
    </select>
  </queryDef>
);

var res = query.ExecuteQuery();

//Buffer the auth key
var buffer = new MemoryBuffer();
buffer.fromString("username:password", "utf-8");

for each (var line in res) {

  var http = new HttpClientRequest();
  http.header["Authorization"] = "Basic " + buffer.toBase64(); //Basic Auth
  this.baseURL = "https://url..../data?user_id=" + line.@userNumber;
  http.url = this.baseURL;
  http.method = "GET"; //The GET request
  http.execute();

  var response = http.response;

try{
    var json = JSON.parse(response);
    logInfo("status: " + json[0].status);
  } catch(e) { logInfo(e); }
}

Body:
To parse json you use

JSON.parse(response);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

JSON.stringify() does the opposite, it converts data into json


问:
Delete words from text but only those whom contains all the different letters
For example "apple" should be deleted while "dog" shouldn't.

For example: "Dog ate my apple,so i am sad wow."

Result would be: "Dog ate my ,so i am sad."

```<code>char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };

 string[] parts = line.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);
   foreach (string word in parts)
</code>```

答:
Cannot be the smartest way but works:

```<code> using System.Linq;

    string line = "Dog ate my apple,so i am sad wow.";

    char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };

    string[] parts = line.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);

    foreach (string word in parts)
    {

        char[] letters = word.ToCharArray();

        var DisintctLetters = letters.Distinct().ToArray();

        if (letters.Length != DisintctLetters.Length)

        {
            line = line.Replace(word, "");
        }

    }
   Console.WriteLine(line);
</code>```

I assume you had a typo in your post, Apple should be deleted and Dog should be kept, if so:

The output will be:Dog ate my ,so i am sad .

Body:
For example "apple" should be deleted while "dog" shouldn't.

For example: "Dog ate my apple,so i am sad wow."

Result would be: "Dog ate my ,so i am sad."

char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };

 string[] parts = line.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);
   foreach (string word in parts)

Body:
Cannot be the smartest way but works:

 using System.Linq;

    string line = "Dog ate my apple,so i am sad wow.";

    char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };

    string[] parts = line.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);

    foreach (string word in parts)
    {

        char[] letters = word.ToCharArray();

        var DisintctLetters = letters.Distinct().ToArray();

        if (letters.Length != DisintctLetters.Length)

        {
            line = line.Replace(word, "");
        }

    }
   Console.WriteLine(line);

I assume you had a typo in your post, Apple should be deleted and Dog should be kept, if so:

The output will be:Dog ate my ,so i am sad .


问:
How to set a background image in Xcode using swift?
How can I set a background image for my main view controller in Xcode 6 using swift? I know that you can do this in the assistant editor as below:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.yellowColor()
}
</code>```

What is the code to set the background to an image I have in my assets folder?

答:
SWIFT 4

```<code>view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage
</code>```

Body:
How can I set a background image for my main view controller in Xcode 6 using swift? I know that you can do this in the assistant editor as below:

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.yellowColor()
}

What is the code to set the background to an image I have in my assets folder?

Body:
SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage


问:
Xero API - Insert unique QR code onto Xero Payslips via API
Can someone from Xero help me with a request, as there are no email addresses on the developer page.

I was wanting to insert a unique QR code with information gathered from an API Post response onto payslips and perhaps invoices.

Is there an API endpoint to do this?

Thanks

Robert

答: Currently there is no way to inject QR codes onto invoices or payslips, you could post this idea to the Payroll API team at Xero here -> https://xero.uservoice.com/forums/250567-xero-payroll-api</p>


问:
What in code defines c++ version?
I am new to C++.  I compiled some code from boost/asio examples using g++.

I was successful only after using -std=c++14 at the g++ command line.
I understood then, and I may be wrong, that the boost/asio library uses C++14.

Then I tried to add code for encoding and decoding base64.

And I received a linker error:

undefined reference to base64_decode(std::__cxx11:basic.....

I understood by the error that I am passing a std:string in C++11 format and the linker does not find a reference in the files of a function that accepts an argument in that format.

But, where in the code can I see which format this method accepts?
If my code boost/asio have a std::string and I passed it to this function:

```<code>std::string base64_decode(std::string const& s)
</code>```

Why does the linker inform me that this parameter is a C++11 std::string?

How does this work?

Where, in the code, is the version of C++ being used?

This is the Base64 file I tried to add:

```<code>#ifndef _BASE64_H_
#define _BASE64_H_
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
#endif
</code>```

And this the cpp file

```<code>#include "base64.h"

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  size_t in_len = encoded_string.size();
  size_t i = 0;
  size_t j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i]));

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j]));

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}
</code>```

答:
To answer the question you asked (but perhaps not the one you intended) ("What in code defines c++ version?
")

Implementations are supposed to define the __cpluplus macro ([cpp.predefined]) which resolves to the following values.

C++03: 199711L

C++11: 201103L

C++14: 201402L

C++17: 201703L

With each new standard, this value is intended to become larger.

That said, when you begin linking, different libraries may or may not be compatible (ABI compatible), even for compiler versions that define the same value for __cplusplus. If you build a C++11 project, you should prefer to link against libraries also compiled with the same compiler for the same platform.

It's more of a case-by-case thing, though. You should consult the documentation for the given library version that you use. Boost in particular talks about compiler compatibility in its release notes. Boost's Windows libraries also list the compiler version (e.g. Boost 1.63 for visual studio 2015 all have vc140 in their name).

Since your error message appears to pertain to std::__cxx11, we can deduce you're using gcc. They have written this helpful page about your exact issue.
Here's the most important line:

If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace [...] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC

And a little more about the _GLIBCXX_USE_CXX11_ABI macro:

In the GCC 5.1 release libstdc++ introduced a new library ABI that includes new implementations of std::string and std::list. These changes were necessary to conform to the 2011 C++ standard which forbids Copy-On-Write strings and requires lists to keep track of their size...

  The _GLIBCXX_USE_CXX11_ABI macro (see Macros) controls whether the declarations in the library headers use the old or new ABI. So the decision of which ABI to use can be made separately for each source file being compiled. Using the default configuration options for GCC the default value of the macro is 1 which causes the new ABI to be active, so to use the old ABI you must explicitly define the macro to 0 before including any library headers.

Title: What in code defines c++ version?

Body:
I am new to C++.  I compiled some code from boost/asio examples using g++.

I was successful only after using -std=c++14 at the g++ command line.
I understood then, and I may be wrong, that the boost/asio library uses C++14.

Then I tried to add code for encoding and decoding base64.

And I received a linker error:

undefined reference to base64_decode(std::__cxx11:basic.....

I understood by the error that I am passing a std:string in C++11 format and the linker does not find a reference in the files of a function that accepts an argument in that format.

But, where in the code can I see which format this method accepts?
If my code boost/asio have a std::string and I passed it to this function:

std::string base64_decode(std::string const& s)

Why does the linker inform me that this parameter is a C++11 std::string?

How does this work?

Where, in the code, is the version of C++ being used?

This is the Base64 file I tried to add:

#ifndef _BASE64_H_
#define _BASE64_H_
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
#endif

And this the cpp file

#include "base64.h"

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  size_t in_len = encoded_string.size();
  size_t i = 0;
  size_t j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i]));

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j]));

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}


问:
how to run GWT web application with google app engine server localy
I have updated eclipse using this Cloud Tools for Eclips and also updated GWT pluings using this GWT Eclipse Plugin

I did all the updation using above links. i did not updated maven integration because mine project is not maven project. now i have created sample GWT web application i can run this using GWT Development mode with jetty then output will come it runs successfully. when i click on run as then i can run this project using development mode and with getty mode and with lagacy mode.
why am i not getting run this project using google app engine server?

how can run gwt sample application with google app enginer server?

Any help

thanks in advance

答: See the instructions in the Cloud Tools for Eclipse → Migrating from the Google Plugin for Eclipse.</p>


问:
How to remove (not to hide) ReplyKeyboardMarkup in Telegram.Bot using C#?
I'm using Telegram.Bot library in C# for developing telegram bots.

I post a text message using SendTextMessageAsync() method and sent a Keyboard with it :

```<code>bot.SendTextMessageAsync(chatId, "sample msg", ParseMode.Default, false, false, 0, new InlineKeyboardMarkup(keyboardData));
</code>```

I want to remove (not to hide) the keyboard, after click of any user on one of the keyboard buttons, so I use this instruction :

```<code>int msgId = bot.SendTextMessageAsync(chatId, "sample msg", ParseMode.Default, false, false, 0, new InlineKeyboardMarkup(keyboardData)).Result;
...
bot.EditMessageReplyMarkupAsync(chatId, msgId, new ReplyKeyboardRemove());
</code>```

But it doesn't work. Please help me about it.

Meanwhile if I set oneTimeKeyboard to true in ReplyKeyboardMarkup, the keyboard will be hide after user click, but it doesn't removed, only it will be hide and user can make it visible using keyboard button of telegram.

答:
I'm afraid, it's too late, but you can use ReplyKeyboardRemove

```<code>var send = new SendMessage(update.Message.Chat.Id, "your_text")
{
    ReplyMarkup = new ReplyKeyboardRemove() { RemoveKeyboard = true }
};
await bot.MakeRequestAsync(send);
</code>```

Body:
I'm using Telegram.Bot library in C# for developing telegram bots.

I post a text message using SendTextMessageAsync() method and sent a Keyboard with it :

bot.SendTextMessageAsync(chatId, "sample msg", ParseMode.Default, false, false, 0, new InlineKeyboardMarkup(keyboardData));

I want to remove (not to hide) the keyboard, after click of any user on one of the keyboard buttons, so I use this instruction :

int msgId = bot.SendTextMessageAsync(chatId, "sample msg", ParseMode.Default, false, false, 0, new InlineKeyboardMarkup(keyboardData)).Result;
...
bot.EditMessageReplyMarkupAsync(chatId, msgId, new ReplyKeyboardRemove());

But it doesn't work. Please help me about it.

Meanwhile if I set oneTimeKeyboard to true in ReplyKeyboardMarkup, the keyboard will be hide after user click, but it doesn't removed, only it will be hide and user can make it visible using keyboard button of telegram.

Body:
I'm afraid, it's too late, but you can use ReplyKeyboardRemove

var send = new SendMessage(update.Message.Chat.Id, "your_text")
{
    ReplyMarkup = new ReplyKeyboardRemove() { RemoveKeyboard = true }
};
await bot.MakeRequestAsync(send);


问:
PHP SoapClient does not add namespace to all elements
I'm using PHP Soap Client with WSDL to send soap requests.
That's the way I initialize the SoapClient:

```<code>$options = [
      "trace" => 1,
      "login" => "Universal API/uAPI3170205802-sdv3r34",
      "password" => "U^#3@$dfw2",
      "classmap" => [
              "BookingDisplayRsp" => "BookingAirSegmentRsp"
      ],
];
$this->soapClient = new \SoapClient("BookingAirPnrElement.wsdl",$options);
$request = [
    "BookingAirPnrElementReq" => [
        "AuthorizedBy" => 'user',
        "SessionKey" => 'e6a30377-0956-4ac4-947d-b4ccb6641629',
        "BillingPointOfSaleInfo" => [
            "OriginApplication" => "uAPI"
        ],
        "AddAirPnrElement" => [
            "LoyaltyCard" => [
                "SupplierCode" => "DL",
                "CardNumber" => "23434523"
            ]
        ],
        "TargetBranch" => "P878183",
    ]
];
</code>```

Doing Soap Request:

```<code> $response = $this->soapClient->__soapCall('service', $request);
</code>```

I receive a Soap Fault:

```<code><SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:Body>
    <SOAP:Fault>
      <faultcode>Server.Data</faultcode>
      <faultstring>Error unmarshalling message body: Expected " {http://www.travelport.com/schema/sharedBooking_v41_0}BookingAirPnrElementReq" end tag, found "AddAirPnrElement" start tag (line 21, col 25, in UTF-8)</faultstring>
     <detail>
        <common_v41_0:ErrorInfo xmlns:common_v41_0="http://www.travelport.com/schema/common_v41_0">
           <common_v41_0:Code>1005</common_v41_0:Code>
           <common_v41_0:Service>WEBSVC</common_v41_0:Service>
           <common_v41_0:Type>Data</common_v41_0:Type>
           <common_v41_0:Description>Unable to parse XML stream</common_v41_0:Description>
           <common_v41_0:TransactionId>C42964360A07425CB318E5F570EEE3DC</common_v41_0:TransactionId>
        </common_v41_0:ErrorInfo>
     </detail>
   </SOAP:Fault>
 </SOAP:Body>
</code>```

The XML request generated by SoapClient:

```<code><?xml version="1.0" encoding="UTF-8"?>
  <SOAP-ENV:Envelope xmlns:SOAP ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.travelport.com/schema/common_v41_0" xmlns:ns2="http://www.travelport.com/schema/sharedBooking_v41_0">
    <SOAP-ENV:Header>
      <h:SessionContext xmlns:h="http://www.travelport.com/soa/common/security/SessionContext_v1" xmlns="http://www.travelport.com/soa/common/security/SessionContext_v1">
        <SessTok id="9444dc84-87c9-4563-80ab-a5f6475bfbe9"/>
      </h:SessionContext>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
      <ns2:BookingAirPnrElementReq AuthorizedBy="user" TargetBranch="P878183" SessionKey="9444dc84-87c9-4563-80ab-a5f6475bfbe9">
        <ns1:BillingPointOfSaleInfo OriginApplication="uAPI"/>
        <AddAirPnrElement>
          <ns1:LoyaltyCard CardNumber="23434523" SupplierCode="DL"/>
        </AddAirPnrElement>
        </ns2:BookingAirPnrElementReq>
    </SOAP-ENV:Body>
  </SOAP-ENV:Envelope>
</code>```

As you can see the AddAirPnrElement element does not have namespace ns2 that corresponds to the xmlns:ns2="http://www.travelport.com/schema/sharedBooking_v41_0"

If I add manually ns2 namespace to that element (AddAirPnrElement) and I send the same XML request in SoapUI, everything is ok.
So the problem is that Soap Client does not set a namespace to that attribute.

Here is the WSDL:

```<code><?xml version="1.0" encoding="UTF-8"?>
<definitions name="SharedBookingService"
         xmlns="http://schemas.xmlsoap.org/wsdl/"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
         xmlns:tns="http://www.travelport.com/service/sharedBooking_v41_0"
         xmlns:ns1="http://www.travelport.com/schema/sharedBooking_v41_0"
   xmlns:sc="http://www.travelport.com/soa/common/security/SessionContext_v1"           targetNamespace="http://www.travelport.com/service/sharedBooking_v41_0">

   <import namespace="http://www.travelport.com/service/sharedBooking_v41_0" location="SharedBookingAbstract.wsdl"/>

   <binding name="BookingAirPnrElementBinding" type="tns:BookingAirPnrElementPortType">
      <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <operation name="service">
        <soap:operation soapAction="https://americas.universal-api.travelport.com/B2BGateway/connect/uAPI/SharedBookingService"/>
        <input>
            <soap:header use="literal" part="sessionContext" message="tns:SessionContext"/>
            <soap:body use="literal"/>
        </input>
        <output>
            <soap:body use="literal"/>
        </output>
        <fault name="ErrorInfoMsg">
            <soap:fault name="ErrorInfoMsg" use="literal"/>
        </fault>
     </operation>
  </binding>

  <service name="SharedBookingService">
    <port name="BookingAirPnrElementPort" binding="tns:BookingAirPnrElementBinding">
        <soap:address location="https://americas.universal-api.travelport.com/B2BGateway/connect/uAPI/SharedBookingService"/>
    </port>
  </service>
</definitions>
</code>```

Can anyone help me understand why Soap Client does not set the namespace?

Thanks a lot.

答:
After analyzing more carefully the XSD file that was imported into WSDL, I noticed that is missing elementFormDefault="qualified" from schema attributes. I added it to the schema

```<code><xs:schema xmlns="http://www.travelport.com/schema/sharedBooking_v41_0"
       xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:common="http://www.travelport.com/schema/common_v41_0"
       xmlns:air="http://www.travelport.com/schema/air_v41_0"
       xmlns:hotel="http://www.travelport.com/schema/hotel_v41_0"
       targetNamespace="http://www.travelport.com/schema/sharedBooking_v41_0"
       elementFormDefault="qualified"
</code>```

and all the namespaces appeared in the XML request.

Body:
I'm using PHP Soap Client with WSDL to send soap requests.
That's the way I initialize the SoapClient:

$options = [
      "trace" => 1,
      "login" => "Universal API/uAPI3170205802-sdv3r34",
      "password" => "U^#3@$dfw2",
      "classmap" => [
              "BookingDisplayRsp" => "BookingAirSegmentRsp"
      ],
];
$this->soapClient = new \SoapClient("BookingAirPnrElement.wsdl",$options);
$request = [
    "BookingAirPnrElementReq" => [
        "AuthorizedBy" => 'user',
        "SessionKey" => 'e6a30377-0956-4ac4-947d-b4ccb6641629',
        "BillingPointOfSaleInfo" => [
            "OriginApplication" => "uAPI"
        ],
        "AddAirPnrElement" => [
            "LoyaltyCard" => [
                "SupplierCode" => "DL",
                "CardNumber" => "23434523"
            ]
        ],
        "TargetBranch" => "P878183",
    ]
];

Doing Soap Request:

 $response = $this->soapClient->__soapCall('service', $request);

I receive a Soap Fault:

<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:Body>
    <SOAP:Fault>
      <faultcode>Server.Data</faultcode>
      <faultstring>Error unmarshalling message body: Expected " {http://www.travelport.com/schema/sharedBooking_v41_0}BookingAirPnrElementReq" end tag, found "AddAirPnrElement" start tag (line 21, col 25, in UTF-8)</faultstring>
     <detail>
        <common_v41_0:ErrorInfo xmlns:common_v41_0="http://www.travelport.com/schema/common_v41_0">
           <common_v41_0:Code>1005</common_v41_0:Code>
           <common_v41_0:Service>WEBSVC</common_v41_0:Service>
           <common_v41_0:Type>Data</common_v41_0:Type>
           <common_v41_0:Description>Unable to parse XML stream</common_v41_0:Description>
           <common_v41_0:TransactionId>C42964360A07425CB318E5F570EEE3DC</common_v41_0:TransactionId>
        </common_v41_0:ErrorInfo>
     </detail>
   </SOAP:Fault>
 </SOAP:Body>

The XML request generated by SoapClient:

<?xml version="1.0" encoding="UTF-8"?>
  <SOAP-ENV:Envelope xmlns:SOAP ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.travelport.com/schema/common_v41_0" xmlns:ns2="http://www.travelport.com/schema/sharedBooking_v41_0">
    <SOAP-ENV:Header>
      <h:SessionContext xmlns:h="http://www.travelport.com/soa/common/security/SessionContext_v1" xmlns="http://www.travelport.com/soa/common/security/SessionContext_v1">
        <SessTok id="9444dc84-87c9-4563-80ab-a5f6475bfbe9"/>
      </h:SessionContext>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
      <ns2:BookingAirPnrElementReq AuthorizedBy="user" TargetBranch="P878183" SessionKey="9444dc84-87c9-4563-80ab-a5f6475bfbe9">
        <ns1:BillingPointOfSaleInfo OriginApplication="uAPI"/>
        <AddAirPnrElement>
          <ns1:LoyaltyCard CardNumber="23434523" SupplierCode="DL"/>
        </AddAirPnrElement>
        </ns2:BookingAirPnrElementReq>
    </SOAP-ENV:Body>
  </SOAP-ENV:Envelope>

As you can see the AddAirPnrElement element does not have namespace ns2 that corresponds to the xmlns:ns2="http://www.travelport.com/schema/sharedBooking_v41_0"

If I add manually ns2 namespace to that element (AddAirPnrElement) and I send the same XML request in SoapUI, everything is ok.
So the problem is that Soap Client does not set a namespace to that attribute.

Here is the WSDL:

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="SharedBookingService"
         xmlns="http://schemas.xmlsoap.org/wsdl/"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
         xmlns:tns="http://www.travelport.com/service/sharedBooking_v41_0"
         xmlns:ns1="http://www.travelport.com/schema/sharedBooking_v41_0"
   xmlns:sc="http://www.travelport.com/soa/common/security/SessionContext_v1"           targetNamespace="http://www.travelport.com/service/sharedBooking_v41_0">

   <import namespace="http://www.travelport.com/service/sharedBooking_v41_0" location="SharedBookingAbstract.wsdl"/>

   <binding name="BookingAirPnrElementBinding" type="tns:BookingAirPnrElementPortType">
      <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <operation name="service">
        <soap:operation soapAction="https://americas.universal-api.travelport.com/B2BGateway/connect/uAPI/SharedBookingService"/>
        <input>
            <soap:header use="literal" part="sessionContext" message="tns:SessionContext"/>
            <soap:body use="literal"/>
        </input>
        <output>
            <soap:body use="literal"/>
        </output>
        <fault name="ErrorInfoMsg">
            <soap:fault name="ErrorInfoMsg" use="literal"/>
        </fault>
     </operation>
  </binding>

  <service name="SharedBookingService">
    <port name="BookingAirPnrElementPort" binding="tns:BookingAirPnrElementBinding">
        <soap:address location="https://americas.universal-api.travelport.com/B2BGateway/connect/uAPI/SharedBookingService"/>
    </port>
  </service>
</definitions>

Can anyone help me understand why Soap Client does not set the namespace?

Thanks a lot.

Body:
After analyzing more carefully the XSD file that was imported into WSDL, I noticed that is missing elementFormDefault="qualified" from schema attributes. I added it to the schema

<xs:schema xmlns="http://www.travelport.com/schema/sharedBooking_v41_0"
       xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:common="http://www.travelport.com/schema/common_v41_0"
       xmlns:air="http://www.travelport.com/schema/air_v41_0"
       xmlns:hotel="http://www.travelport.com/schema/hotel_v41_0"
       targetNamespace="http://www.travelport.com/schema/sharedBooking_v41_0"
       elementFormDefault="qualified"

and all the namespaces appeared in the XML request.


问:
Exception ORA-08103: object no longer exists on using setfetchsize of Hibernate
I'm using Hibernate. I need to fetch around 1000000 records and it will cause timeout exception. So I'm using setfetchsize for 6000 records, so that it will distribute the operation in multiple transactions each of 6000 records.

It will take around 21 hours to fetch all.

But meanwhile retrieving records if somebody deletes one of the record which was to be fetched then I get ORA-08103: object no longer exists.

Now I want to skip that object which is deleted while retrieving. How can I do this?

答:
After Struggling one week finally I fixed the Issue:

Solution: Most likely that a cursor is opened based on a global temporary table(GTT), which had been created with ON COMMIT DELETE ROWS option. And the cause of the ORA-08103: object no longer exists error is commit statement that followed right after the delete statement. DBA team didn't agree to change the GTT as on commit preserve rows so finally I added code base in Java Service Layer[Implementing the Spring - Programmatic Transaction]

```<code>package com.test;

import java.util.List;
import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void setTransactionManager(PlatformTransactionManager transactionManager) {
      this.transactionManager = transactionManager;
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);

      try {
         String SQL1 = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update( SQL1, name, age);

         // Get the latest student id to be used in Marks table
         String SQL2 = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( SQL2 );

         String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);

         System.out.println("Created Name = " + name + ", Age = " + age);
         transactionManager.commit(status);
      }
      catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         transactionManager.rollback(status);
         throw e;
      }
      return;
   }
   public List<StudentMarks> listStudents() {
      String SQL = "select * from Student, Marks where Student.id=Marks.sid";
      List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,
         new StudentMarksMapper());

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

Body:
After Struggling one week finally I fixed the Issue:

Solution: Most likely that a cursor is opened based on a global temporary table(GTT), which had been created with ON COMMIT DELETE ROWS option. And the cause of the ORA-08103: object no longer exists error is commit statement that followed right after the delete statement. DBA team didn't agree to change the GTT as on commit preserve rows so finally I added code base in Java Service Layer[Implementing the Spring - Programmatic Transaction]

package com.test;

import java.util.List;
import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   private PlatformTransactionManager transactionManager;

   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void setTransactionManager(PlatformTransactionManager transactionManager) {
      this.transactionManager = transactionManager;
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);

      try {
         String SQL1 = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update( SQL1, name, age);

         // Get the latest student id to be used in Marks table
         String SQL2 = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( SQL2 );

         String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);

         System.out.println("Created Name = " + name + ", Age = " + age);
         transactionManager.commit(status);
      }
      catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         transactionManager.rollback(status);
         throw e;
      }
      return;
   }
   public List<StudentMarks> listStudents() {
      String SQL = "select * from Student, Marks where Student.id=Marks.sid";
      List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL,
         new StudentMarksMapper());

      return studentMarks;
   }
}


问:
Boto3: How to check if VPC already exists before creating it
I can create a VPC really quick like this:

```<code>import boto3 as boto

inst = boto.Session(profile_name='myprofile').resource('ec2')

def createVpc(nid,az='us-west-2'):
    '''Create the VPC'''
    vpc = inst.create_vpc(CidrBlock = '10.'+str(nid)+'.0.0/16')
    vpc.create_tags(
        Tags = [ { 'Key': 'Name', 'Value': 'VPC-'+nid }, ]
    )
    vpc.wait_until_available()

createVpc('111')
</code>```

How can I check a VPC with CidrBlock: 10.111.0.0/16 or a Name: VPC-111 already exists before it gets created? I actually wanna do the same check prior to any AWS resource creation but VPC is a start. Best!

EDIT:
found that vpcs.filter can be used to query a given VPC tags; e.g.:

```<code>fltr = [{'Name':'tag:Name', 'Values':['VPC-'+str(nid)]}]
list(inst.vpcs.filter(Filters=fltr))
</code>```

which returns a list object like this: [ec2.Vpc(id='vpc-43e56b3b')]. A list with length 0 (zero) is a good indication of a non-existent VPC but was wondering if there is more boto/aws way of detecting that.

答:
Yes you need to use filters with describe_vpcs API.

The below code will list all VPC's which matches both Name Tag Value and the  CIDR block:

```<code>import boto3

client = boto3.client('ec2',region_name='us-east-1')
response = client.describe_vpcs(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                '<Enter you VPC name here>',
            ]
        },
        {
            'Name': 'cidr-block-association.cidr-block',
            'Values': [
                '10.0.0.0/16', #Enter you cidr block here
            ]
        },
    ]
)
resp = response['Vpcs']
if resp:
    print(resp)
else:
    print('No vpcs found')
</code>```

CIDR block is the primary check for VPC. I would suggest to just use the CIDR Filter alone instead of clubbing with Name Tag as then you can prevent creating VPC with same CIDR Blocks.

Body:
I can create a VPC really quick like this:

import boto3 as boto

inst = boto.Session(profile_name='myprofile').resource('ec2')

def createVpc(nid,az='us-west-2'):
    '''Create the VPC'''
    vpc = inst.create_vpc(CidrBlock = '10.'+str(nid)+'.0.0/16')
    vpc.create_tags(
        Tags = [ { 'Key': 'Name', 'Value': 'VPC-'+nid }, ]
    )
    vpc.wait_until_available()

createVpc('111')

How can I check a VPC with CidrBlock: 10.111.0.0/16 or a Name: VPC-111 already exists before it gets created? I actually wanna do the same check prior to any AWS resource creation but VPC is a start. Best!

EDIT:
found that vpcs.filter can be used to query a given VPC tags; e.g.:

fltr = [{'Name':'tag:Name', 'Values':['VPC-'+str(nid)]}]
list(inst.vpcs.filter(Filters=fltr))

which returns a list object like this: [ec2.Vpc(id='vpc-43e56b3b')]. A list with length 0 (zero) is a good indication of a non-existent VPC but was wondering if there is more boto/aws way of detecting that.

Body:
Yes you need to use filters with describe_vpcs API.

The below code will list all VPC's which matches both Name Tag Value and the  CIDR block:

import boto3

client = boto3.client('ec2',region_name='us-east-1')
response = client.describe_vpcs(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                '<Enter you VPC name here>',
            ]
        },
        {
            'Name': 'cidr-block-association.cidr-block',
            'Values': [
                '10.0.0.0/16', #Enter you cidr block here
            ]
        },
    ]
)
resp = response['Vpcs']
if resp:
    print(resp)
else:
    print('No vpcs found')

CIDR block is the primary check for VPC. I would suggest to just use the CIDR Filter alone instead of clubbing with Name Tag as then you can prevent creating VPC with same CIDR Blocks.


问:
Add Jquery from standard style in wordpress custom theme
I have the used the following code in the front page of Custom theme but want to improve on how to load jquery. Please suggest me with cool answers</p>

/assets/js/jquery.min.js'>

/assets/js/bootstrap.js'>

/assets/js/jquery.mixitup.js'>

/assets/js/custom-scripts.js'>

答:
The best practice to load jQuery is to declare it as a dependency when you enqueue your custom scripts. That way if plugins are using jQuery you wont load it again. Assuming all your plugins follow best practices too.

in your case it would look like:

```<code>//functions.php
function my_theme_scripts(){
  wp_enqueue_script( 'bootstrap', get_template_directory_uri().'/assets/js/bootstrap.js', array('jquery'), '0', true );
  wp_enqueue_script( 'jquery-mixitup', get_template_directory_uri().'/assets/js/jquery.mixitup.js', array('jquery'), '0', true );
  wp_enqueue_script( 'custom-scripts', get_template_directory_uri().'/assets/js/custom-scripts', array('jquery'), '0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
</code>```

Wordpress recognizes the handle 'jquery' and loads the latest stable version in the correct order.

Note: the '0' is the version number and can be any number you choose. Update it at any time ex '0.1' and it will force the user's browser to re-download cached files.

References:
https://developer.wordpress.org/reference/functions/wp_enqueue_script/

Body:
I have the used the following code in the front page of Custom theme but want to improve on how to load jquery. Please suggest me with cool answers

/assets/js/jquery.min.js'>

/assets/js/bootstrap.js'>

/assets/js/jquery.mixitup.js'>

/assets/js/custom-scripts.js'>

Body:
The best practice to load jQuery is to declare it as a dependency when you enqueue your custom scripts. That way if plugins are using jQuery you wont load it again. Assuming all your plugins follow best practices too.

in your case it would look like:

//functions.php
function my_theme_scripts(){
  wp_enqueue_script( 'bootstrap', get_template_directory_uri().'/assets/js/bootstrap.js', array('jquery'), '0', true );
  wp_enqueue_script( 'jquery-mixitup', get_template_directory_uri().'/assets/js/jquery.mixitup.js', array('jquery'), '0', true );
  wp_enqueue_script( 'custom-scripts', get_template_directory_uri().'/assets/js/custom-scripts', array('jquery'), '0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

Wordpress recognizes the handle 'jquery' and loads the latest stable version in the correct order.

Note: the '0' is the version number and can be any number you choose. Update it at any time ex '0.1' and it will force the user's browser to re-download cached files.

References:
https://developer.wordpress.org/reference/functions/wp_enqueue_script/


问:
Robotium. In the suite of tests each next test is affected by the previous test
I have multiple UI tests. When I run a single test, everything is OK. But if I run a batch of them (as a part of CI build) test fail, because tests that go first change the state of the application, and the next tests are affected by  those changes. (Since the app is not getting killed).

I tried getActivity().finish() in tearDown().

Tried solo.finalize() which does the same actually.

Is there a way to have a fresh app at the beginning of each test run? (Using Robotium).

And is there a way to programmatically kill the app at the end of a test?

I'm using ActivityInstrumentationTestCase2 with Robotium

答:
My solution:</p>

```<code>    @Override
    public void tearDown() throws Exception {

        solo.finishOpenedActivities();

        super.tearDown();
    }
</code>```

Body:
My solution:

    @Override
    public void tearDown() throws Exception {

        solo.finishOpenedActivities();

        super.tearDown();
    }


问:
Rails/BootStrap - Make iterated object data appear in columns
I am trying to get my cards to show-up as three in a row and then jump to the next line and put the next three. Right now, it's just putting each card right below the one above it. Can anyone help me out?</p>

```<code><div class="container">
  <div class="row">
    <div class="col-md-6">
      <% @block_busters.each do |movie| %>
      <div class="card" style="width: 20rem;">
        <img class="card-img-top" src="<%= movie.image_url %>" alt="Card image cap">
        <div class="card-body">
          <h4 class="card-title"><%=movie.title%></h4>
          <p class="card-text"><%=movie.description%></p>
        </div>
      </div>
      <%end%>
    </div>
  </div>
</div>
</code>```

答:
You're most likely looking for the 'slice' method, try something like this:</p>

```<code><% @block_busters.each_slice(3) do |slice| %>
  <div class="row">
    <% slice.each do |movie| %>
      <div class="col-md-4"> <!-- 12 cols / 3 cards = 4 -->
        <!-- render your cards here, each will show up in rows of 3 -->
      </div>
    <% end %>
  </div>
<% end %>
</code>```

Body:
I am trying to get my cards to show-up as three in a row and then jump to the next line and put the next three. Right now, it's just putting each card right below the one above it. Can anyone help me out?

      <% @block_busters.each do |movie| %>

        <img class="card-img-top" src="<%= movie.image_url %>" alt="Card image cap">

<%=movie.title%>

<%=movie.description%>

      <%end%>

Body:
You're most likely looking for the 'slice' method, try something like this:

<% @block_busters.each_slice(3) do |slice| %>
  <div class="row">
    <% slice.each do |movie| %>
      <div class="col-md-4"> <!-- 12 cols / 3 cards = 4 -->
        <!-- render your cards here, each will show up in rows of 3 -->
      </div>
    <% end %>
  </div>
<% end %>


问:
What are the differences between Usage Data logging and trace logging in SharePoint2010
Usage Data logging is configured @ Configure Diagnostic Logging
and trace logging is configured @
What are the differences between Usage Data logging and trace logging in SharePoint2010</p>

答:
Trace logs or ULS logs, are the logs sharepoint creates internally for doing things. Timer jobs for example get logged here, as well as everything else to do with the standard web operations. If you need to find out what is wrong with your system look here. Exceptions should be written into these as well.

They can be administered here:

http://centraladmin/_admin/metrics.aspx

And are normally found on the server here with an extension of *.log

%CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\LOGS\

Usage logs are similar to IIS logs. These are the logs for users actually going to the web site and downloading pages or documents.

The Web Analytics Service Application, parses the usage logs to make web reports similar to what Google analytics does.

ContentLicense: CC BY-SA 2.5


问:
pyexcel / openpyxl __init__() got an unexpected keyword argument ERROR
I am receiving the following error stack when attempting to upload files back to our application. The application takes xlsx sheets and is able to parse them and upload the content back up to SalesForce. I did some digging into this issue and it appears it might be something to do with openpyxl in terms of compatibility but I am not 100% sure. It appears others have had this issue as well but It doesn't appear to be any solutions listed. Has anyone else encountered this problem?

load_workbook error for 1707 version excel & pip install/upgrade error openpyxl

```<code>https://bitbucket.org/openpyxl/openpyxl/issues/636/error-when-loading-outlookcom-web-excel

 Traceback (most recent call last):
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1817, in wsgi_app
     response = self.full_dispatch_request()
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1477, in full_dispatch_request
     rv = self.handle_user_exception(e)
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1381, in handle_user_exception
     reraise(exc_type, exc_value, tb)
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1475, in full_dispatch_request
     rv = self.dispatch_request()
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1461, in dispatch_request
     return self.view_functions[rule.endpoint](**req.view_args)
   File "/var/www/html/nurfi/run.py", line 139, in upload_file
     responses = upload_nurfi_files(files_to_upload)
   File "/var/www/html/nurfi/nurfinstein.py", line 134, in upload_nurfi_files
     statuses[filename] = upload_sheet(file_, sf, verbose_mode = False )
   File "/var/www/html/nurfi/nurfi_app/upload/upload_nurfi.py", line 74, in upload_sheet
     book_dict = pyexcel.get_book_dict(file_name = workbook_name)
   File "/usr/lib/python2.6/dist-packages/pyexcel/core.py", line 343, in get_book_dict
     book = get_book(**keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel/core.py", line 118, in get_book
     book_stream = _get_book(**keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel/core.py", line 137, in _get_book
     sheets = source.get_data()
   File "/usr/lib/python2.6/dist-packages/pyexcel/sources/file_source_input.py", line 52, in get_data
     sheets = get_data(self.file_name, streaming=True, **self.keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel_io/io.py", line 31, in get_data
     file_type=file_type, **keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel_io/io.py", line 120, in load_data_new
     reader.open(file_name, **keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel_xlsx/xlsx.py", line 87, in open
     self._load_from_file()
   File "/usr/lib/python2.6/dist-packages/pyexcel_xlsx/xlsx.py", line 127, in _load_from_file
     data_only=True)
   File "/usr/lib/python2.6/dist-packages/openpyxl/reader/excel.py", line 234, in load_workbook
     parser.parse()
   File "/usr/lib/python2.6/dist-packages/openpyxl/reader/worksheet.py", line 106, in parse
     dispatcher[tag_name](element)
   File "/usr/lib/python2.6/dist-packages/openpyxl/reader/worksheet.py", line 295, in parse_data_validation
     dv = DataValidation.from_tree(node)
   File "/usr/lib/python2.6/dist-packages/openpyxl/descriptors/serialisable.py", line 78, in from_tree
     return cls(**attrib)
 TypeError: __init__() got an unexpected keyword argument '{http://schemas.microsoft.com/office/spreadsheetml/2014/revision}uid'
</code>```

答:
So hopefully my time digging through this saves some other people some time. It appears that this issue can be resolved by updating openpyxl and one of its plugin dependents openpyxl_xlsx to the latest build. I would also recommend if you are using pyexcel to update that to the latest package as well as I believe it uses openpyxl as a dependent.

```<code>sudo pip install openpyxl --upgrade
sudo pip install openpyxl_xlsx --upgrade
sudo pip install pyexcel --upgrade
</code>```

Or for specific versions...

```<code>sudo pip install --upgrade 'package-name'==0.0.0 (Version Number)
</code>```

Body:
I am receiving the following error stack when attempting to upload files back to our application. The application takes xlsx sheets and is able to parse them and upload the content back up to SalesForce. I did some digging into this issue and it appears it might be something to do with openpyxl in terms of compatibility but I am not 100% sure. It appears others have had this issue as well but It doesn't appear to be any solutions listed. Has anyone else encountered this problem?

load_workbook error for 1707 version excel & pip install/upgrade error openpyxl

https://bitbucket.org/openpyxl/openpyxl/issues/636/error-when-loading-outlookcom-web-excel

 Traceback (most recent call last):
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1817, in wsgi_app
     response = self.full_dispatch_request()
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1477, in full_dispatch_request
     rv = self.handle_user_exception(e)
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1381, in handle_user_exception
     reraise(exc_type, exc_value, tb)
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1475, in full_dispatch_request
     rv = self.dispatch_request()
   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1461, in dispatch_request
     return self.view_functions[rule.endpoint](**req.view_args)
   File "/var/www/html/nurfi/run.py", line 139, in upload_file
     responses = upload_nurfi_files(files_to_upload)
   File "/var/www/html/nurfi/nurfinstein.py", line 134, in upload_nurfi_files
     statuses[filename] = upload_sheet(file_, sf, verbose_mode = False )
   File "/var/www/html/nurfi/nurfi_app/upload/upload_nurfi.py", line 74, in upload_sheet
     book_dict = pyexcel.get_book_dict(file_name = workbook_name)
   File "/usr/lib/python2.6/dist-packages/pyexcel/core.py", line 343, in get_book_dict
     book = get_book(**keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel/core.py", line 118, in get_book
     book_stream = _get_book(**keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel/core.py", line 137, in _get_book
     sheets = source.get_data()
   File "/usr/lib/python2.6/dist-packages/pyexcel/sources/file_source_input.py", line 52, in get_data
     sheets = get_data(self.file_name, streaming=True, **self.keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel_io/io.py", line 31, in get_data
     file_type=file_type, **keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel_io/io.py", line 120, in load_data_new
     reader.open(file_name, **keywords)
   File "/usr/lib/python2.6/dist-packages/pyexcel_xlsx/xlsx.py", line 87, in open
     self._load_from_file()
   File "/usr/lib/python2.6/dist-packages/pyexcel_xlsx/xlsx.py", line 127, in _load_from_file
     data_only=True)
   File "/usr/lib/python2.6/dist-packages/openpyxl/reader/excel.py", line 234, in load_workbook
     parser.parse()
   File "/usr/lib/python2.6/dist-packages/openpyxl/reader/worksheet.py", line 106, in parse
     dispatcher[tag_name](element)
   File "/usr/lib/python2.6/dist-packages/openpyxl/reader/worksheet.py", line 295, in parse_data_validation
     dv = DataValidation.from_tree(node)
   File "/usr/lib/python2.6/dist-packages/openpyxl/descriptors/serialisable.py", line 78, in from_tree
     return cls(**attrib)
 TypeError: __init__() got an unexpected keyword argument '{http://schemas.microsoft.com/office/spreadsheetml/2014/revision}uid'

Body:
So hopefully my time digging through this saves some other people some time. It appears that this issue can be resolved by updating openpyxl and one of its plugin dependents openpyxl_xlsx to the latest build. I would also recommend if you are using pyexcel to update that to the latest package as well as I believe it uses openpyxl as a dependent.

sudo pip install openpyxl --upgrade
sudo pip install openpyxl_xlsx --upgrade
sudo pip install pyexcel --upgrade

Or for specific versions...

sudo pip install --upgrade 'package-name'==0.0.0 (Version Number)


问:
Most efficient way of combining two big lists
I have two lists that each contain 2500 values.

```<code>List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();
</code>```

I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:

```<code> for (int i = 0; i < headers.size(); i++) {
    for (int in = 0; in < data.size(); in++) {

       }
 }
</code>```

It's critical the index of each list match each other when combining these two lists. So headers.get(9); must match data.get(9);.

I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0); would be paired with data.get(0);.

Any help would be appreciated.

答:
If you need the one list to contain the same pairs that you'd get doing the nested loop, there's nothing you can do.  You're iterating over 2500*2500=6250000 pairs.  Nothing will make that fast.  Iterating over one list instead of the nested for loops will not make a difference.

If you don't want to iterate over every combination of elements from both lists, but iterate over one list once and then iterate over the other list once, then that's equivalent to doing one for loop after the other, not one for loop inside of the other.  And that will be fast whether you combine them into one big list, or iterate over one list and then the other.

Body:
I have two lists that each contain 2500 values.

List<String> headers = new ArrayList<String>();
List<String> data = new ArrayList<String>();

I need to combine these two lists into a two dimensional list or any other appropriate data structure that allows me to only iterate through once rather than doing the operation below which is very slow when dealing with big lists:

 for (int i = 0; i < headers.size(); i++) {
    for (int in = 0; in < data.size(); in++) {

       }
 }

It's critical the index of each list match each other when combining these two lists. So headers.get(9); must match data.get(9);.

I need a new list or other data structure that will allow me to store each value in the two lists as pairs. So headers.get(0); would be paired with data.get(0);.

Any help would be appreciated.


问:
SVG animation resets on hover
I have an svg that I animated,

The animation works smoothly, and I have it set to animation-fill-mode: forwards to that it stays put after it’s done animating.

currently, in the svg html, I have

```<code>stroke="none"
</code>```

and then in the @keyframes css, I have it:

```<code>from{ stroke: none; }
to { stroke: #fff; }
</code>```

once it’s done animating, I want the strokes to change color on :hover, which it does.

but once I move the cursor away, the animation starts over.

how would I go about making the SVG return right back to it’s #FFF stroke without triggering the animation after the hover is complete?

Here is my Codepen

答:
You have used a animation-timing-function: ease, but there is no smooth transition between values none and #fff - one is a keyword, the other a color value. For going from "invisible" to "visible", use the opacity property instead and define fill independent of the animation.

If you do that, you can leave opacity at 1 after the animation and only exchange the fill value for hovering. Do not turn off the animation during hover.

```<code>@keyframes shield {
  from {
    opacity: 0; }
  to {
    opacity: 1; } }
#outer-left, #outer-btm-left, #outer-btm-right, #outer-right, #outer-top {
  animation-name: shield;
  animation-duration: 1s;
  animation-iteration-count: 1;
  animation-timing-function: ease;
  animation-fill-mode: forwards;
  stroke:#fff;
  opacity:0;
  }

#outer-left:hover {
  stroke: red;
}

#outer-btm-left:hover {
  stroke: red;
}
</code>```

Title: SVG animation resets on hover

Body:
I have an svg that I animated,

The animation works smoothly, and I have it set to animation-fill-mode: forwards to that it stays put after it’s done animating.

currently, in the svg html, I have

stroke="none"

and then in the @keyframes css, I have it:

from{ stroke: none; }
to { stroke: #fff; }

once it’s done animating, I want the strokes to change color on :hover, which it does.

but once I move the cursor away, the animation starts over.

how would I go about making the SVG return right back to it’s #FFF stroke without triggering the animation after the hover is complete?

Here is my Codepen

Body:
You have used a animation-timing-function: ease, but there is no smooth transition between values none and #fff - one is a keyword, the other a color value. For going from "invisible" to "visible", use the opacity property instead and define fill independent of the animation.

If you do that, you can leave opacity at 1 after the animation and only exchange the fill value for hovering. Do not turn off the animation during hover.

@keyframes shield {
  from {
    opacity: 0; }
  to {
    opacity: 1; } }
#outer-left, #outer-btm-left, #outer-btm-right, #outer-right, #outer-top {
  animation-name: shield;
  animation-duration: 1s;
  animation-iteration-count: 1;
  animation-timing-function: ease;
  animation-fill-mode: forwards;
  stroke:#fff;
  opacity:0;
  }

#outer-left:hover {
  stroke: red;
}

#outer-btm-left:hover {
  stroke: red;
}


问:
Prevent "Send error report to Microsoft"
I'm working on a rather large project, and its unlikely will catch everything. I've found the event that notifies me of unhandled exceptions, however I haven't found a way to programmatically shut off the windows error dialog. Ideally, if there is an unhandled exception, I would like to have that event fired, provide a dialog box telling the user that there is a problem, and then to close gracefully. Is there any way to do this? I realize I could wrap the highest layer in a try catch, but I was hoping for something a little more elegant. </p>

答:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Though if you're releasing this as a commercial project, I encourage you to register with Microsoft, so that you can actually get the crash dumps and error reporting info that is being sent to MS

OwnerDisplayName: Steve

LastEditorDisplayName: Rich B

OwnerDisplayName: Paul Betts


问:
Wpf 4 TranslateTransform animation is not smooth when some effect applied
We have a kind of Carousel control in our app: bunch of icons are spinning around (TranslateTransform and DoubleAnimation are used to move icons in circle). Icon is just an Image with DropShadowEffect. In .NET 3.5 animation was smooth. I've recently switched to the .NET 4 and icons now "jump", animation is not smooth.

I've tried to remove DropShadowEffect and it solved the problem. Is there a way to smoothly animate elements with Effect? I've tried things like UseLayoutRounding, BitmapScalingMode. May be there is some setting that I do not know of?

Update
It is not a performance problem. Basically, I've added some text above the image (the object to animate is a Grid with TextBlock and Image). After that text moves smoothly, and Image does not. Like it is not moving by one pixel, but by two pixels. Looks like layout works different when there is an Effect applied.

答: DropShadowEffect is quite resource intensive, so it's likely the computer cannot handle it in time to make the animation smooth.  Perhaps you could simulate a drop shadow using a border or something else, instead of using the DropShadowEffect.  See this thread for more information.


问:
Angular - detecting when two subscriptions have updated
In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

Thanks,

Component.TS

```<code>ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) =>
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) =>
 {
   this.dataB= dataBJSON
 }
</code>```

DataService

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}
</code>```

答:
You could use the operator Zip or CombineLatest from rxjs.

See ReactiveX operators

You could do something like this:

```<code>    Observable.zip(
        this.http.get("./assets/dataa.json"),
        this.http.get("./assets/dataa.json")
    .take(1)
    .map(values => [values[0].json(), values[1].json()])
    .subscribe(values => {
        // do something with my values
    });
</code>```

Body:
In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

Thanks,

Component.TS

ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) =>
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) =>
 {
   this.dataB= dataBJSON
 }

DataService

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}

Body:
You could use the operator Zip or CombineLatest from rxjs.

See ReactiveX operators

You could do something like this:

    Observable.zip(
        this.http.get("./assets/dataa.json"),
        this.http.get("./assets/dataa.json")
    .take(1)
    .map(values => [values[0].json(), values[1].json()])
    .subscribe(values => {
        // do something with my values
    });


问:
Can I access the stored favicons for bookmarks using the Firefox extension API?
I'm writing an extension for Firefox 57+ (using the WebExtensions API). Is it possible to access the locally stored favicon for a given URL/bookmark? I'm thinking something like file://{%PROFILE%}/favicons/{% URL %}

答: Bug 1315616 - Give extensions access to cached favicon URLs tracks this feature request.</p>


问:
Conditionally showing a placeholder when there is no value in the data ( ReactJS)
I have a json file that contains images and I am passing them to the front end by mapping the data. When all the items have an image, everything looks great. But if the image is missing, responsiveness breaks and it just doesn't look quite right. So, I would like to display a placeholder in place of "missing photo"

Here's a mini version of my data.json file

```<code>exports.administration = [
    {
        id:'1',
        image: '/assets/images/media/christopher-walken.jpg',
        name: "Christopher Walken",
    },
    {
        id:'2',
        image: '',
        name: "Jane Doe",
    },
    {
        id:'3',
        image: '/assets/images/media/keanu-reeves.jpg',
        name: "Keanu Reeves",
    },
];
</code>```

And here is my JSX file

```<code>class Administration extends Component {
    constructor(props) {
       super(props);
       this.state = {
            //showImage: true,
       };
    }

    handleImage = () => this.setState({
       //if there is no image in the data, show the placeholder.png
    });

    render() {
        return (
            <div>
                {administrationData.map((row, index) => (
                    <Card className="custom-card">
                        <CardText>
                            <Row>
                                <Col xs={12} sm={3}>
                                    { //this the condition I looking for// this.state.showImage
                                    ?
                                        <img style={styles.image} src={row.image} alt={row.name} />
                                    :
                                        <img src='/assets/images/placeholder.png' alt="Not Available" />
                                    }
                                </Col>
                            </Row>
                        </CardText>
                    </Card>
                ))}
            </div>
        );
    }
}

export default Administration;
</code>```

Kind of a newbie in reactJS.

Thank you in advance guys.

答:
You don't really need the state for the ternary here because you already have a field that tells you if the image is there or not.

I would just do something like:

```<code>{(row.image !== '') ? Image : Placeholder}
</code>```

Body:
I have a json file that contains images and I am passing them to the front end by mapping the data. When all the items have an image, everything looks great. But if the image is missing, responsiveness breaks and it just doesn't look quite right. So, I would like to display a placeholder in place of "missing photo"

Here's a mini version of my data.json file

exports.administration = [
    {
        id:'1',
        image: '/assets/images/media/christopher-walken.jpg',
        name: "Christopher Walken",
    },
    {
        id:'2',
        image: '',
        name: "Jane Doe",
    },
    {
        id:'3',
        image: '/assets/images/media/keanu-reeves.jpg',
        name: "Keanu Reeves",
    },
];

And here is my JSX file

class Administration extends Component {
    constructor(props) {
       super(props);
       this.state = {
            //showImage: true,
       };
    }

    handleImage = () => this.setState({
       //if there is no image in the data, show the placeholder.png
    });

    render() {
        return (

                {administrationData.map((row, index) => (
                    <Card className="custom-card">
                        <CardText>
                            <Row>
                                <Col xs={12} sm={3}>
                                    { //this the condition I looking for// this.state.showImage
                                    ?

                                    :

                                    }
                                </Col>
                            </Row>
                        </CardText>
                    </Card>
                ))}

        );
    }
}

export default Administration;

Kind of a newbie in reactJS.

Thank you in advance guys.

Body:
You don't really need the state for the ternary here because you already have a field that tells you if the image is there or not.

I would just do something like:

{(row.image !== '') ? Image : Placeholder}


问:
Duplication of data on oracle sql report
I am printing tablespace names in oracle but am facing duplicate data issue on the sqlplus console. Please share your thoughts if you know how to avoid this issue.

```<code>set heading on
set echo off
set feedback off trimspool on verify off
set lines 120
set pages 2000
prompt DATE
select sysdate from dual;
/
prompt
prompt
prompt =====================================
prompt            Tablespaces
prompt =====================================
break on report
select name from v$tablespace ;
/

clear break
clear compute
</code>```

答:
And as the docs say about "slash": https://docs.oracle.com/cd/E18283_01/server.112/e16604/ch_twelve004.htm

Executes the most recently executed SQL command or PL/SQL block which
  is stored in the SQL buffer.

So select name from v$tablespace ;is executed twice in your case

Body:
I am printing tablespace names in oracle but am facing duplicate data issue on the sqlplus console. Please share your thoughts if you know how to avoid this issue.

set heading on
set echo off
set feedback off trimspool on verify off
set lines 120
set pages 2000
prompt DATE
select sysdate from dual;
/
prompt
prompt
prompt =====================================
prompt            Tablespaces
prompt =====================================
break on report
select name from v$tablespace ;
/

clear break
clear compute


答:
You could You can use concat to combine the observables and return a single observable.

Subscribe to observables in order as previous completes, emit values

changed service code

```<code>import 'rxjs/add/operator/concat';

export class PMDataService
{
  data(){
    return this.dataA().concat(this.dataB());
  }
  // methods dataA and dataB are unchanged, some of the constructor
}
</code>```

Component code

```<code>ngOnInit(){
  this.dataService.data().subscribe((dataJSON) =>
     {
       this.dataA= dataAJSON[0];
       this.dataB= dataAJSON[1];
     }
}
</code>```

Title: Angular - detecting when two subscriptions have updated

Body:
You could You can use concat to combine the observables and return a single observable.

Subscribe to observables in order as previous completes, emit values

changed service code

import 'rxjs/add/operator/concat';

export class PMDataService
{
  data(){
    return this.dataA().concat(this.dataB());
  }
  // methods dataA and dataB are unchanged, some of the constructor
}

Component code

ngOnInit(){
  this.dataService.data().subscribe((dataJSON) =>
     {
       this.dataA= dataAJSON[0];
       this.dataB= dataAJSON[1];
     }
}