问:
angular4 viewchild not working on dom element
i want to know how to fetch the dom element from a components template :

Component

```<code>export class JokeListComponent implements OnInit, AfterViewInit {

  jokes: Joke[];
  constructor() { }
  @ViewChild('.myclass') el:  ElementRef;

  ngOnInit() {

    this.jokes = [
      new Joke('joke1', 'content1'),
      new Joke('Joke2', 'content2'),
      new Joke(),
    ];

  }

  ngAfterViewInit(): void {
    console.log(this.el);
  }
}
</code>```

View

```<code><div class="card">
    <div class="card-block">
        <h4 class="card-title"> New Joke Form </h4>

        <div class="myclass">

        </div>

        <div class="form-group">
            <label for="jokeHeader">Joke Header</label>
            <input type="text" id="jokeHeader" class="form-control" placeholder="Joke Head" #jokeHead>
        </div>

        <div class="form-group">
            <label for="jokeContent">Joke Header</label>
            <input type="text" id="jokeContent" class="form-control" placeholder="Joke Content" #jokeContent>
        </div>

        <button class="btn btn-primary" (click)="addJoke(jokeHead.value, jokeContent.value)"> Validate </button>

    </div>
</div>

<hr>

<joke *ngFor="let joke of jokes" [joke]="joke" (deleteEvt)="deleteJoke($event)"></joke>
</code>```

the problem is that this.el is always undefined, i dont know why.

PS: i'm using the last version of angular 4

答:
You cannot use the class name for the @ViewChild, you will need a local variable:</p>

```<code>@Component({
      template: `
      <div><span #myVar>xxx</span><div>`
    })
    class MyComponent {
      @ViewChild('myVar') myVar:ElementRef;

      ngAfterViewInit() {
        console.log(this.myVar.nativeElement);
      }
    }
</code>```

Body:
i want to know how to fetch the dom element from a components template :

Component

export class JokeListComponent implements OnInit, AfterViewInit {

  jokes: Joke[];
  constructor() { }
  @ViewChild('.myclass') el:  ElementRef;

  ngOnInit() {

    this.jokes = [
      new Joke('joke1', 'content1'),
      new Joke('Joke2', 'content2'),
      new Joke(),
    ];

  }

  ngAfterViewInit(): void {
    console.log(this.el);
  }
}

View

 New Joke Form

            Joke Header
            <input type="text" id="jokeHeader" class="form-control" placeholder="Joke Head" #jokeHead>

            Joke Header
            <input type="text" id="jokeContent" class="form-control" placeholder="Joke Content" #jokeContent>

        <button class="btn btn-primary" (click)="addJoke(jokeHead.value, jokeContent.value)"> Validate </button>

<joke *ngFor="let joke of jokes" [joke]="joke" (deleteEvt)="deleteJoke($event)"></joke>

the problem is that this.el is always undefined, i dont know why.

PS: i'm using the last version of angular 4

Body:
You cannot use the class name for the @ViewChild, you will need a local variable:

@Component({
      template: `
      <div><span #myVar>xxx</span><div>`
    })
    class MyComponent {
      @ViewChild('myVar') myVar:ElementRef;

      ngAfterViewInit() {
        console.log(this.myVar.nativeElement);
      }
    }


来源: stackexchange

问:
how to start stop tomcat server using CMD?
I set the path for the tomcat and set all variables like

JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_22

CATALINA_HOME=G:\springwork\server\apache-tomcat-6.0.29

CLASSPATH=G:\springwork\server\apache-tomcat-6.0.29\lib\servlet-api.jar;G:\springwork\server\apache-tomcat-6.0.29\lib\jsp-api.jar;.;

When I go to bin folder and double click on startup.bat then my tomcat starts and when I double click on shutdown.bat tomcat stops.

But I want using CMD start and stop the tomcat.
And in any folder I write command startup.bat the server will start and when I write shutdown.bat the server will stop.

答:
Add %CATALINA_HOME%/bin to path system variable.

Go to Environment Variables screen under System Variables there will be a Path variable edit the variable and add ;%CATALINA_HOME%\bin to the variable then click OK to save the changes. Close all opened command prompts then open a new command prompt and try to use the command startup.bat.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
GetComponent returning "null" instead of null
I'm confused about the return value of GetComponent if the requested component is not attached to the object.  According to the Unity documentation, GetComponent should return null.  However, what appears to be happening is that GetComponent is returning a "null" object of the requested type, rather than the value null.

In this example, my game object does not have a CircleCollider2D attached to it.  When I set a breakpoint on the line CircleCollider2D x = GetComponent<CircleCollider2D>();, I get this result

Why is the returned value not null?

EDIT:

Here's a full screenshot of the code and the values in the debugger.

ANOTHER EDIT:

Could it be that Unity has overloaded the == operator so that GetComponent always returns a object, but the object can have an internal "null" state which returns true when compared to null?  I can see the following declarations in the UnityEngine namespace

```<code>public static bool operator ==(Object x, Object y);
public static bool operator !=(Object x, Object y);
</code>```

答: GetComponent is expected to return object of type 'Component. Hence it is not expected to return "null" rather ~null is expected value. Perhaps this strange behavior should be reported to unity3d,

Body:
I'm confused about the return value of GetComponent if the requested component is not attached to the object.  According to the Unity documentation, GetComponent should return null.  However, what appears to be happening is that GetComponent is returning a "null" object of the requested type, rather than the value null.

In this example, my game object does not have a CircleCollider2D attached to it.  When I set a breakpoint on the line CircleCollider2D x = GetComponent<CircleCollider2D>();, I get this result

Why is the returned value not null?

EDIT:

Here's a full screenshot of the code and the values in the debugger.

ANOTHER EDIT:

Could it be that Unity has overloaded the == operator so that GetComponent always returns a object, but the object can have an internal "null" state which returns true when compared to null?  I can see the following declarations in the UnityEngine namespace

public static bool operator ==(Object x, Object y);
public static bool operator !=(Object x, Object y);


问:
Pydot & Graphviz setup
I am trying to plot some a decision tree using graphviz and pydot using SKLearn in python.
From the python code:

```<code>import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris(
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
test_idx=[0,50,100]

tree.export_graphviz(clf,
        out_file='tree.dot')#gives text file
print iris.feature_names
print iris.target_names
from sklearn.externals.six import StringIO
import pydot
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[0].write_pdf("iris.pdf")
</code>```

I get the error:

```<code>Traceback (most recent call last):
  File "/Users/student/Desktop/Data Structures/decision_tree_visualization.py", line 18, in <module>
    graph[0].write_pdf("iris.pdf")
  File "build/bdist.macosx-10.6-intel/egg/pydot.py", line 1691, in <lambda>
    self.write(path, format=f, prog=prog))
  File "build/bdist.macosx-10.6-intel/egg/pydot.py", line 1774, in write
    s = self.create(prog, format)
  File "build/bdist.macosx-10.6-intel/egg/pydot.py", line 1883, in create
    prog=prog))
Exception: "dot" not found in path.
</code>```

I have tried reinstalling pydot and graphviz to no avail. Any help?

答:
It sounds like graphviz has not been added to the system path. See this Stack Overflow questionand this more detailed explanation.

Not every method of installed sets the path correctly (especially pip install).

Title: Pydot & Graphviz setup

Body:
I am trying to plot some a decision tree using graphviz and pydot using SKLearn in python.
From the python code:

import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris(
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
test_idx=[0,50,100]

tree.export_graphviz(clf,
        out_file='tree.dot')#gives text file
print iris.feature_names
print iris.target_names
from sklearn.externals.six import StringIO
import pydot
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[0].write_pdf("iris.pdf")

I get the error:

Traceback (most recent call last):
  File "/Users/student/Desktop/Data Structures/decision_tree_visualization.py", line 18, in <module>
    graph[0].write_pdf("iris.pdf")
  File "build/bdist.macosx-10.6-intel/egg/pydot.py", line 1691, in <lambda>
    self.write(path, format=f, prog=prog))
  File "build/bdist.macosx-10.6-intel/egg/pydot.py", line 1774, in write
    s = self.create(prog, format)
  File "build/bdist.macosx-10.6-intel/egg/pydot.py", line 1883, in create
    prog=prog))
Exception: "dot" not found in path.

I have tried reinstalling pydot and graphviz to no avail. Any help?


问:
Pythonic way to merge keys with common values for a single dictionary
How do I merge the keys of a dictionary with common values into a tuple. For example:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}
</code>```

My attempt:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)
</code>```

This prints:

```<code>OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}
</code>```

答:
Here's what I worked up using comprehensions. Only requires two intermediate steps and only uses built-in data types.</p>

```<code># get unique values from original dict
targ_values = set([tuple(v) for v in A.values()])

# build lists of original keys that match the temp_keys
targ_values = {targ_value:[orig_key for orig_key, orig_value in A.items() if tuple(orig_value) == targ_value] for targ_value in targ_values}

# reverse the order of keys & values and convert types to get desired output
output = {tuple(v):set(k) for k, v in targ_values.items()}
</code>```

Body:
How do I merge the keys of a dictionary with common values into a tuple. For example:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}

My attempt:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)

This prints:

OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}

Body:
Here's what I worked up using comprehensions. Only requires two intermediate steps and only uses built-in data types.

# get unique values from original dict
targ_values = set([tuple(v) for v in A.values()])

# build lists of original keys that match the temp_keys
targ_values = {targ_value:[orig_key for orig_key, orig_value in A.items() if tuple(orig_value) == targ_value] for targ_value in targ_values}

# reverse the order of keys & values and convert types to get desired output
output = {tuple(v):set(k) for k, v in targ_values.items()}


问:
C++ Pointer to different class within another class
I've been searching through documentation and checking the example code given by my class and can't figure out whats wrong here. I'm trying to build a linked list structure and need pointers that can point to nodes, but can't seem to initialize them correctly. The nodes point to each other fine, its the overarching class with first/last/current pointers that is giving me problems.

The following code is giving me a bunch of errors when I try to make pointers of the node class. I get C2238 "unexpected tokens preceding ';'" in line 19, 20, and 21 as well as C2143 "missing ';' before '*'" and C4430 "missing type specifier..." again for lines 19, 20 and 21 (the protected section of linkedList).

```<code>template <class Type>
class linkedList
{
public:
    //constructors
    linkedList();

    //functions
    void insertLast(Type data);             //creates a new node at the end of the list with num as its info
    void print();                           //steps through the list printing info at each node
    int length();                           //returns the number of nodes in the list
    void divideMid(linkedList sublist);     //divides the list in half, storing a pointer to the second half in the private linkedList pointer named sublist

    //deconstuctors
    ~linkedList();
protected:
    node *current;                          //temporary pointer
    node *first;                            //pointer to first node in linked list
    node *last;                             //pointer to last node in linked list
    bool firstCreated;                      //keeps track of whether a first node has been assigned
private:
};

template <class Type>
struct node
{
    Type info;
    node<Type> *next;
};
</code>```

changing the protected section as follows also leaves the C2238 and C4430 error but changes C2143 to "missing ';' before '<'"

```<code>    node<Type> *current;                            //temporary pointer
    node<Type> *first;                              //pointer to first node in linked list
    node<Type> *last;                               //pointer to last node in linked list
</code>```

答:
You need to make a forward declaration for node before linkedList:

```<code>template <class Type>
struct node;
</code>```

See the working version here please.

Body:
I've been searching through documentation and checking the example code given by my class and can't figure out whats wrong here. I'm trying to build a linked list structure and need pointers that can point to nodes, but can't seem to initialize them correctly. The nodes point to each other fine, its the overarching class with first/last/current pointers that is giving me problems.

The following code is giving me a bunch of errors when I try to make pointers of the node class. I get C2238 "unexpected tokens preceding ';'" in line 19, 20, and 21 as well as C2143 "missing ';' before '*'" and C4430 "missing type specifier..." again for lines 19, 20 and 21 (the protected section of linkedList).

template <class Type>
class linkedList
{
public:
    //constructors
    linkedList();

    //functions
    void insertLast(Type data);             //creates a new node at the end of the list with num as its info
    void print();                           //steps through the list printing info at each node
    int length();                           //returns the number of nodes in the list
    void divideMid(linkedList sublist);     //divides the list in half, storing a pointer to the second half in the private linkedList pointer named sublist

    //deconstuctors
    ~linkedList();
protected:
    node *current;                          //temporary pointer
    node *first;                            //pointer to first node in linked list
    node *last;                             //pointer to last node in linked list
    bool firstCreated;                      //keeps track of whether a first node has been assigned
private:
};

template <class Type>
struct node
{
    Type info;
    node<Type> *next;
};

changing the protected section as follows also leaves the C2238 and C4430 error but changes C2143 to "missing ';' before '<'"

    node<Type> *current;                            //temporary pointer
    node<Type> *first;                              //pointer to first node in linked list
    node<Type> *last;                               //pointer to last node in linked list

Body:
You need to make a forward declaration for node before linkedList:

template <class Type>
struct node;

See the working version here please.


问:
How to validate that a user owns the requested resource through Rails API when using devise_token_auth
I am building an API-only (for now) Rails app to serve as the back end for an Android app I'm building. I was previously using Firebase but wanted to do more processing on application data and I didn't want to bloat the mobile client with all the logic, so I am moving away from Firebase's real-time database and backing the application data using Rails. I was also using Firebase's authentication which is very straightforward. But it seems less complex for the overall system to keep all of this functionality in one place, so I'd like to perform auth and user management in the Rails app as well.

I have installed devise_token_auth (seen here) and finished the basic configuration. The /auth route works correctly if params are provided and creates a user. sign_in and sign_out both successfully create sessions and return some header information. The important parts returned are client, access-token, and uid, which I need to use in future calls to the API. I believe these are invalidated and replaced with each subsequent call. At this part of the flow is where I'm not sure how to proceed. I don't understand how the data in these headers is associated with the user who signed in and how I can validate that they own a resource they request. To summarize the question another way:

How can I sign a user into the API and then validate which user is making subsequent API calls?

My Android app is a task manager, so I need to be able to validate for example that if user 1 requests task 3, that they own that resource. I'm also unsure how to direct index calls using the API. That is, when the index endpoint is hit (/tasks), how can I identify from the data in the API headers which user's tasks I should retrieve.

I haven't been able to find any solid tutorials or samples using devise_token_auth so I'm having trouble stitching together the interaction between the pieces I have now. I know this is a meaty question - thanks in advance for any guidance.

答:
How can I [...] validate which user is making subsequent API calls?

With the current_user method. This is a built-in feature to the devise_token_auth gem.

I need to be able to validate for example that if user 1 requests task 3, that they own that resource

There are many different approaches you could take. You could just write some custom logic in each controller action, using the current_user method (and return 403 forbidden if necessary).

Or, you could use a popular "framework" solution for this such as CanCanCan or Pundit. I, and probably most of the modern community, would recommend Pundit.

I highly advise you to read that library's README, as it's extremely helpful. But for the example above, you could write something like this:

```<code>class TasksController
  def show
    task = Task.find(params[:id])
    authorize(task) # !!!
    render task
  end
end

# app/policies/task_policy.rb
class TaskPolicy
  def show?
    record.user == user
  end
end
</code>```

(Note that by default, the "user" in Pundit policies calls the method: current_user. This is all explained in the project's README.)

when the index endpoint is hit (/tasks), how can I identify from the data in the API headers which user's tasks I should retrieve

Again, this is all handled as part of Pundit's standard features. You just need to define a TaskPolicy::Scope and call policy_scope(Task) in the controller - as explained here.

Body:
How can I [...] validate which user is making subsequent API calls?

With the current_user method. This is a built-in feature to the devise_token_auth gem.

I need to be able to validate for example that if user 1 requests task 3, that they own that resource

There are many different approaches you could take. You could just write some custom logic in each controller action, using the current_user method (and return 403 forbidden if necessary).

Or, you could use a popular "framework" solution for this such as CanCanCan or Pundit. I, and probably most of the modern community, would recommend Pundit.

I highly advise you to read that library's README, as it's extremely helpful. But for the example above, you could write something like this:

class TasksController
  def show
    task = Task.find(params[:id])
    authorize(task) # !!!
    render task
  end
end

# app/policies/task_policy.rb
class TaskPolicy
  def show?
    record.user == user
  end
end

(Note that by default, the "user" in Pundit policies calls the method: current_user. This is all explained in the project's README.)

when the index endpoint is hit (/tasks), how can I identify from the data in the API headers which user's tasks I should retrieve

Again, this is all handled as part of Pundit's standard features. You just need to define a TaskPolicy::Scope and call policy_scope(Task) in the controller - as explained here.


问:
sed command to delete a line with contain more than 10 character which not start with 91
I want sed command to delete a line from which which contain more than 10 number and which are not start with 91

My file content is like this

```<code>919876543210
789876543210
9012345678
12345678901
9865746321
</code>```

And need output like this.

```<code>919876543210
9012345678
9865746321
</code>```

I have tried awk 'length>=4' 1.txt | grep -v ^91

this will show me

```<code>789876543210
12345678901
</code>```

Body:
I want sed command to delete a line from which which contain more than 10 number and which are not start with 91

My file content is like this

919876543210
789876543210
9012345678
12345678901
9865746321

And need output like this.

919876543210
9012345678
9865746321

I have tried awk 'length>=4' 1.txt | grep -v ^91

this will show me

789876543210
12345678901

Body:
Simple, clear, portable, efficient, etc. with awk:

$ awk '/^91/ || length()<11' file
919876543210
9012345678
9865746321


问:
Calling a function at setInterval Jscript
i have a image slider, and i am wanting to call the fader function at the end of the timer, unfortunately, im a complete novice and only seem to be NOT LEARNING from my mistakes... I know im floating in a boat full of the same kind ,So please could a good sailor divert this boat in the right direction for us. We would all be most great-full of your service..

I have code here, If anybody can explain where im going wrong i would be very happy. Thank you

```<code><script>
function fader (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
 element.style.opacity=0;
}
</script>

<script>

(function() {
   'use strict';

   var preloads=[],c,
       d=document,di=d.getElementById('dynamic-image'),
       dh=d.getElementById('dynamic-href'),
       url=[
           'linkmywebsite.ml','chatmagbingo.com','ilkestonwebdesign.com','ipost.com','happypetsuk.com','www.linkmywebsite.co.uk'
          ];

function preload(){
for(c=0;c<arguments.length;c++) {
   preloads[preloads.length]=new Image();
   preloads[preloads.length-1].src=arguments[c];
  }
   c=0;
 }

preload('yournewsite2.png','1ad.jpg','2ad.jpg',
'3ad.jpg','4ad.jpg','5ad.jpg');

setInterval(

function starttimer() {

   dh.href='http://'+url[c];
   di.src=preloads[c].src;
   di.alt=preloads[c].src.substring(preloads[c].src.lastIndexOf('/')+1);
   c++;
if(c==preloads.length) {
   c=0;
  }

 },5000);

}());
</code>```

Not sure where to call the function Fader. thank you....

答:
Here is the answer..... again i figure it out...lol

So heres a image fader for that boatfull of novices...simplified.....

```<code><style type="text/css">

.dynamic-image {
position:absolute;
 left:0%;
 top:0%;
 width:100%;
 height:100%;

</style>

<img id="dynamic-image" class="dynamic-image" src="ebayad.png";>

<script>
function fader (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
 element.style.opacity=4;
}
</script>

<script>
function fader2 (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
 element.style.opacity=0;
}

</script>

<script>

setInterval( fader2, 4000 );

(function() {
   'use strict';

   var preloads=[],c,
      di=document.getElementById('dynamic-image');

function preload(){
for(c=0;c<arguments.length;c++) {
   preloads[preloads.length]=new Image();
   preloads[preloads.length-1].src=arguments[c];
  }
   c=0;
 }

preload('yournewsite2.png','1ad.jpg','2ad.jpg',
'3ad.jpg','4ad.jpg','5ad.jpg');

setInterval( fader, 8000 );

setInterval(

function starttimer() {

   di.src=preloads[c].src;

   c++;
if(c==preloads.length) {
   c=0;
  }

 },8000);

}());

</script>
</code>```

Body:
Here is the answer..... again i figure it out...lol

So heres a image fader for that boatfull of novices...simplified.....

<style type="text/css">

.dynamic-image {
position:absolute;
 left:0%;
 top:0%;
 width:100%;
 height:100%;

</style>

<img id="dynamic-image" class="dynamic-image" src="ebayad.png";>

<script>
function fader (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
 element.style.opacity=4;
}
</script>

<script>
function fader2 (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
 element.style.opacity=0;
}

</script>

<script>

setInterval( fader2, 4000 );

(function() {
   'use strict';

   var preloads=[],c,
      di=document.getElementById('dynamic-image');

function preload(){
for(c=0;c<arguments.length;c++) {
   preloads[preloads.length]=new Image();
   preloads[preloads.length-1].src=arguments[c];
  }
   c=0;
 }

preload('yournewsite2.png','1ad.jpg','2ad.jpg',
'3ad.jpg','4ad.jpg','5ad.jpg');

setInterval( fader, 8000 );

setInterval(

function starttimer() {

   di.src=preloads[c].src;

   c++;
if(c==preloads.length) {
   c=0;
  }

 },8000);

}());

</script>


问:
Show progressbar for ftp upload in python
So I'm writing a script that will search a folder recursively for a .mkv file and upload it to my NAS. I have the script working but I can't see the progress. I imported this progressbar I found on github and was able to use the demo to see it work. It is what I want however the FTP example they included is to retrieve a file from the server. I need to upload.

How do I get the uploaded amount on an interval so I can run an update to the progress bar?

Bellow is the code I have that works for the upload

```<code>import os
import ftplib
import ntpath

ntpath.basename("a/b/c")

def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
    ftp = ftplib.FTP(URL, UserName, Password)   # connect to host, default port
    print URL, UserName, Password
    for file in FileTransferList:
        FileName = path_leaf(file)
        print file
        TheFile = open(file, 'r')
        ftp.storbinary('STOR ' + FileName, TheFile, 1024)
        TheFile.close()
    ftp.quit()
    ftp = None

FTP_GLOB_transfer('<IP>', '<USER>', '<PASSWORD>')
</code>```

答:
I figured it out. I decided to use TQDM as I found some easier to read documentation for it. I was assuming that storbinary() had to have a return or something to tell it's progress, just didn't know I was looking for a callback.

Anyways I added a new import from tqdm import tqdm

I added this filesize = os.path.getsize(file) to get the file size of the file

Then I replaced ftp.storbinary('STOR ' + FileName, TheFile, 1024) with this code

```<code>with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
        ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
</code>```

And overall the new working code looks like

```<code>import os
import ftplib
import ntpath
from tqdm import tqdm

ntpath.basename("a/b/c")

def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
    ftp = ftplib.FTP(URL, UserName, Password)   # connect to host, default port
    print URL, UserName, Password
    for file in FileTransferList:
        FileName = path_leaf(file)
        filesize = os.path.getsize(file)
        print file
        TheFile = open(file, 'r')
        with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
            ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
        TheFile.close()
    ftp.quit()
    ftp = None
</code>```

It now outputs as

```<code>/tmp/rippedMovies/TestMovie.mkv
Uploading......:  51%|████████████████████▉                    | 547M/1.07G
[00:05<00:14, 36.8Mblocks/s]
</code>```

Body:
So I'm writing a script that will search a folder recursively for a .mkv file and upload it to my NAS. I have the script working but I can't see the progress. I imported this progressbar I found on github and was able to use the demo to see it work. It is what I want however the FTP example they included is to retrieve a file from the server. I need to upload.

How do I get the uploaded amount on an interval so I can run an update to the progress bar?

Bellow is the code I have that works for the upload

import os
import ftplib
import ntpath

ntpath.basename("a/b/c")

def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
    ftp = ftplib.FTP(URL, UserName, Password)   # connect to host, default port
    print URL, UserName, Password
    for file in FileTransferList:
        FileName = path_leaf(file)
        print file
        TheFile = open(file, 'r')
        ftp.storbinary('STOR ' + FileName, TheFile, 1024)
        TheFile.close()
    ftp.quit()
    ftp = None

FTP_GLOB_transfer('<IP>', '<USER>', '<PASSWORD>')

Body:
I figured it out. I decided to use TQDM as I found some easier to read documentation for it. I was assuming that storbinary() had to have a return or something to tell it's progress, just didn't know I was looking for a callback.

Anyways I added a new import from tqdm import tqdm

I added this filesize = os.path.getsize(file) to get the file size of the file

Then I replaced ftp.storbinary('STOR ' + FileName, TheFile, 1024) with this code

with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
        ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))

And overall the new working code looks like

import os
import ftplib
import ntpath
from tqdm import tqdm

ntpath.basename("a/b/c")

def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
    ftp = ftplib.FTP(URL, UserName, Password)   # connect to host, default port
    print URL, UserName, Password
    for file in FileTransferList:
        FileName = path_leaf(file)
        filesize = os.path.getsize(file)
        print file
        TheFile = open(file, 'r')
        with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
            ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
        TheFile.close()
    ftp.quit()
    ftp = None

It now outputs as

/tmp/rippedMovies/TestMovie.mkv
Uploading......:  51%|████████████████████▉                    | 547M/1.07G
[00:05<00:14, 36.8Mblocks/s]


问:
Vulkan: update uniform variables without resetting command buffer
As far as I know, when we update the uniform variables through "vkUpdateDescriptorSets", the status of the corresponding command buffer will be invalid. Accordingly, we have to reset the command buffer and re-record it.

Is there a way to update the uniform variables without doing anything to the command buffer?

What's the best way to update the data of uniform variables per frame (in the aspect of performance)?

答:
Descriptors inside the descriptor sets refer to an area in a vkBuffer or vkImage.

You can safely update the contents of buffer or image between renders and keep the descriptors intact.

Make sure there are no read conflicts while the actual update takes place.


问:
Printing without newline (print 'a',) prints a space, how to remove?
I have this code:

```<code>>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a
</code>```

I want to output 'a', without ' ' like this:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

Is it possible?

答:
Python 3.x:

```<code>for i in range(20):
    print('a', end='')
</code>```

Python 2.6 or 2.7:

```<code>from __future__ import print_function
for i in xrange(20):
    print('a', end='')
</code>```

Body:
I have this code:

>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' ' like this:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

Body:
Python 3.x:

for i in range(20):
    print('a', end='')

Python 2.6 or 2.7:

from __future__ import print_function
for i in xrange(20):
    print('a', end='')


问:
beepbeepboopbeep
```<code>import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}
</code>```

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.

答:
If we assume the range of allowed user values are 1..100 only so we may allocate an array of 100 size where an index will be a user value and value will be an incremented counter. In this case we have natural sorting of user values automatically.

Also I reworked to have unlimited user enters (without BOOP limit), enter until 0:

```<code>public class Lab_07_03 {
    private static final int MIN_VALUE = 1;
    private static final int MAX_VALUE = 100;

    public static void main(String args[]) {
        final Scanner scnr = new Scanner(System.in);

        final int[] counters = new int[MAX_VALUE + 1];

        System.out.println("Enter integers between " + MIN_VALUE + " and " + MAX_VALUE + ": ");

        while (scnr.hasNext()) {
            final int userValue = scnr.nextInt();

            if (userValue == 0) {
                break; // 0 signals end of user input
            }

            if (userValue < MIN_VALUE || userValue > MAX_VALUE) {
                continue; // ignore all out of range values
            }

            counters[userValue] += 1;
        }

        for (int i = 0; i < counters.length; i++) {
            final int counter = counters[i];
            if (counter != 0) {
                System.out.println(i + " occurs " + counter + ((counter > 1) ? " times." : " time."));
            }
        }
    }
}
</code>```

An example of input-outputs:

```<code>Enter integers between 1 and 100:
1
2
1
2
100
234
0
1 occurs 2 times.
2 occurs 2 times.
100 occurs 1 time.
</code>```

Title: beepbeepboopbeep

Body:
import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.

Body:
If we assume the range of allowed user values are 1..100 only so we may allocate an array of 100 size where an index will be a user value and value will be an incremented counter. In this case we have natural sorting of user values automatically.

Also I reworked to have unlimited user enters (without BOOP limit), enter until 0:

public class Lab_07_03 {
    private static final int MIN_VALUE = 1;
    private static final int MAX_VALUE = 100;

    public static void main(String args[]) {
        final Scanner scnr = new Scanner(System.in);

        final int[] counters = new int[MAX_VALUE + 1];

        System.out.println("Enter integers between " + MIN_VALUE + " and " + MAX_VALUE + ": ");

        while (scnr.hasNext()) {
            final int userValue = scnr.nextInt();

            if (userValue == 0) {
                break; // 0 signals end of user input
            }

            if (userValue < MIN_VALUE || userValue > MAX_VALUE) {
                continue; // ignore all out of range values
            }

            counters[userValue] += 1;
        }

        for (int i = 0; i < counters.length; i++) {
            final int counter = counters[i];
            if (counter != 0) {
                System.out.println(i + " occurs " + counter + ((counter > 1) ? " times." : " time."));
            }
        }
    }
}

An example of input-outputs:

Enter integers between 1 and 100:
1
2
1
2
100
234
0
1 occurs 2 times.
2 occurs 2 times.
100 occurs 1 time.


问:
Twice clicking is needed to open dropdown menu in IE, working fine in Chrome
I am working with a Drupal 7 site and facing a problem in IE.
For the menu items to open twice clicking is needed (only in IE).
In Chrome, it is opening in one click as needed.

Here is the link of the site: http://gwccgtclone626.bitnamiapp.com
You can try opening it in both IE and Chrome.
Then try to open any menu (e.g. Applications) by clicking on it.

答:
Remove the navigation links from the top level menus.
eg.

change

```<code><a class="active-trail dropdown-toggle disabled" href="/our-alternator-brands">Products<i class="fa fa-caret-down"></i></a>
</code>```

to

```<code><a class="active-trail dropdown-toggle disabled" href="#">Products<i class="fa fa-caret-down"></i></a>
</code>```

The common design pattern for dropdown menus is to expand the child UL on click or hover.. IE is bubbling the click event.

Regards.

Body:
Remove the navigation links from the top level menus.
eg.

change

<a class="active-trail dropdown-toggle disabled" href="/our-alternator-brands">Products<i class="fa fa-caret-down"></i></a>

to

<a class="active-trail dropdown-toggle disabled" href="#">Products<i class="fa fa-caret-down"></i></a>

The common design pattern for dropdown menus is to expand the child UL on click or hover.. IE is bubbling the click event.

Regards.


问:
Determining If the Cell Contents are Equal in Excel
I am trying to see if the numerical values in two cells are equivalent.

My problem is that one cell is text formatted and the number has one decimal precision and the other numerical format with 7 decimals precision.

I want to see if they are both equal to one decimal precision and I can't figure out how to do it.

So, the values in my cells look like this:

```<code>numerical         text
  5.6%             5.6%
</code>```

But the real values are:

```<code>numerical        text
5.56650625%       5.6%
</code>```

How can I test do this?

Thanks in advance.

答:
You can convert text to number with VALUE(text).
You can use ROUND(number, number of digit). There is also CEILING and FLOOR you may want to play around with. But that should point you in the right direction.</p>

Body:
I am trying to see if the numerical values in two cells are equivalent.

My problem is that one cell is text formatted and the number has one decimal precision and the other numerical format with 7 decimals precision.

I want to see if they are both equal to one decimal precision and I can't figure out how to do it.

So, the values in my cells look like this:

numerical         text
  5.6%             5.6%

But the real values are:

numerical        text
5.56650625%       5.6%

How can I test do this?

Thanks in advance.


问:
How do I find the highest count of the same values with Pandas Python?
I am trying finding the most popular major for each university.

Here is a sample of the table:

```<code>Institution   Major_Name  Count  Major
School 1      Art           2    First
School 1      English      12    First
School 1      Math          7    First
School 1      Art           6    Second
School 1      English       4    Second
School 1      Math          3    Second

School 2      Art         9
School 2      English     4
School 2      Math       13
</code>```

I want the final outcome to look like this where the rest of the rows will disappear:

```<code>Institution   Major_Name   Count   Major
School 1      English       12     First
School 1      Art            6     Second
School 2      Math          13
</code>```

Thanks in advance. Very new to using Pandas!

答:
You can do a groupby on Institution and then apply the max function:

```<code>In [547]: df.groupby('Institution', as_index=False).max()
Out[547]:
  Institution  Major  Count
0     School 1  Math     12
1     School 2  Math     13
</code>```

The as_index=False attribute will prevent the resultant GroupBy object from assigning Institution as the new index.

Based on your edit: To group by Institution as well as Major, you can specify multiple columns to group by:

```<code>In [563]: df.fillna('').groupby(['Institution', 'Major'], as_index=False).max()
Out[563]:
  Institution   Major Major_Name  Count
0     School1   First       Math     12
1     School1  Second       Math      6
2     School2               Math     13
</code>```

Body:
I am trying finding the most popular major for each university.

Here is a sample of the table:

Institution   Major_Name  Count  Major
School 1      Art           2    First
School 1      English      12    First
School 1      Math          7    First
School 1      Art           6    Second
School 1      English       4    Second
School 1      Math          3    Second

School 2      Art         9
School 2      English     4
School 2      Math       13

I want the final outcome to look like this where the rest of the rows will disappear:

Institution   Major_Name   Count   Major
School 1      English       12     First
School 1      Art            6     Second
School 2      Math          13

Thanks in advance. Very new to using Pandas!

Body:
You can do a groupby on Institution and then apply the max function:

In [547]: df.groupby('Institution', as_index=False).max()
Out[547]:
  Institution  Major  Count
0     School 1  Math     12
1     School 2  Math     13

The as_index=False attribute will prevent the resultant GroupBy object from assigning Institution as the new index.

Based on your edit: To group by Institution as well as Major, you can specify multiple columns to group by:

In [563]: df.fillna('').groupby(['Institution', 'Major'], as_index=False).max()
Out[563]:
  Institution   Major Major_Name  Count
0     School1   First       Math     12
1     School1  Second       Math      6
2     School2               Math     13


问:
'adb' is not recognized as a command
In my new MacBook, I installed latest Android Studio. Then, in terminal, I created the .bash_profile, and added following lines to the file:

```<code>export ANDROID_HOME=~/Library/Android/sdk

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS
</code>```

After that, I run command source .bash_profile, then I type adb command, but get error that adb is not recognized as a command. Why? I also echo $PATH, I saw the platform_tools directory of Android sdk is there & there is adb file under that directory.

====== UPDATE =====

It is interesting, if I do following, it works:

```<code>export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools
export PATH=$PATH:/Users/myname/Library/Android/sdk/tools
export ANDROID_HOME=/Users/myname/Library/Android/sdk
</code>```

WHY? Isn't ~ above identical to /Users/myname? Why my original script doesn't work but the above one works? I don't understand....Please someone explain to me.

答:
Depending on the shell, export variable definitions can be treated differently than normal assignments — in particular, tilde expansion might not occur at all.

If this is the case, then every unresolved tilde in a variable stays unresolved even if this variable gets expanded somewhere else. According to the docs:

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, <…>

You might want to try this:

```<code>ANDROID_HOME=~/Library/Android/sdk
export ANDROID_HOME

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS
</code>```

If it doesn`t help, you can also try $HOME:

```<code>ANDROID_HOME=$HOME/Library/Android/sdk
export ANDROID_HOME
</code>```

Title: 'adb' is not recognized as a command

Body:
In my new MacBook, I installed latest Android Studio. Then, in terminal, I created the .bash_profile, and added following lines to the file:

export ANDROID_HOME=~/Library/Android/sdk

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS

After that, I run command source .bash_profile, then I type adb command, but get error that adb is not recognized as a command. Why? I also echo $PATH, I saw the platform_tools directory of Android sdk is there & there is adb file under that directory.

====== UPDATE =====

It is interesting, if I do following, it works:

export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools
export PATH=$PATH:/Users/myname/Library/Android/sdk/tools
export ANDROID_HOME=/Users/myname/Library/Android/sdk

WHY? Isn't ~ above identical to /Users/myname? Why my original script doesn't work but the above one works? I don't understand....Please someone explain to me.

Body:
Depending on the shell, export variable definitions can be treated differently than normal assignments — in particular, tilde expansion might not occur at all.

If this is the case, then every unresolved tilde in a variable stays unresolved even if this variable gets expanded somewhere else. According to the docs:

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, <…>

You might want to try this:

ANDROID_HOME=~/Library/Android/sdk
export ANDROID_HOME

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS

If it doesn`t help, you can also try $HOME:

ANDROID_HOME=$HOME/Library/Android/sdk
export ANDROID_HOME


问:
How do I import files in Python?
I'm trying to use pytest to check a function—here is my code:

```<code># src/return_self.py
def return_self(n):
    return n

# tests/return_self_test.py
import pytest

def test_1():
    value = return_self(1)
    assert value == 1
</code>```

How do I require in my src file so that I can test it with pytest? I have tried a few things:

```<code>1. import return_self
2. from src.return_self import *
3. import sys
   sys.path.append('../src')
4. import imp
   return_self = imp.load_source('return_self', '/source/return_self.py')
</code>```

I have also tried them with and without __init__.py files in the root and src directories. But each time, I get some variation on the error E   ModuleNotFoundError: No module named 'return_self'. How can I require in my file?

答:
You can try this approach:</p>

```<code># tests/return_self_test.py

import os
import sys
import pytest

sys.path.insert(1, os.path.join(sys.path[0], '..'))

from src.return_self import return_self

def test_1():
    value = return_self(1)
    assert value == 1
</code>```

Title: How do I import files in Python?

Body:
I'm trying to use pytest to check a function—here is my code:

# src/return_self.py
def return_self(n):
    return n

# tests/return_self_test.py
import pytest

def test_1():
    value = return_self(1)
    assert value == 1

How do I require in my src file so that I can test it with pytest? I have tried a few things:

1. import return_self
2. from src.return_self import *
3. import sys
   sys.path.append('../src')
4. import imp
   return_self = imp.load_source('return_self', '/source/return_self.py')

I have also tried them with and without __init__.py files in the root and src directories. But each time, I get some variation on the error E   ModuleNotFoundError: No module named 'return_self'. How can I require in my file?

Body:
You can try this approach:

# tests/return_self_test.py

import os
import sys
import pytest

sys.path.insert(1, os.path.join(sys.path[0], '..'))

from src.return_self import return_self

def test_1():
    value = return_self(1)
    assert value == 1


问:
Lambda including if...elif...else
I want to apply a lambda function to a DataFrame column using if...elif...else within the lambda function.

The df and the code are something like:

```<code>df=pd.DataFrame({"one":[1,2,3,4,5],"two":[6,7,8,9,10]})

df["one"].apply(lambda x: x*10 if x<2 elif x<4 x**2 else x+10)
</code>```

Obviously, this doesn't work. Is there a way to apply if....elif....else to a lambda?
How can I get the same result with List Comprehension?

答:
Nest if .. elses:

```<code>lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Lambda including if...elif...else

Body:
I want to apply a lambda function to a DataFrame column using if...elif...else within the lambda function.

The df and the code are something like:

df=pd.DataFrame({"one":[1,2,3,4,5],"two":[6,7,8,9,10]})

df["one"].apply(lambda x: x*10 if x<2 elif x<4 x**2 else x+10)

Obviously, this doesn't work. Is there a way to apply if....elif....else to a lambda?
How can I get the same result with List Comprehension?

Body:
Nest if .. elses:

lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)


问:
SQL: simplify and, or query on multiple columns
I have a table named employe with following content

```<code>id A B C D E F G
1  8 4 6 3 2 5 2
1  7 3 1 2 1 3 7
3  9 2 3 3 2 6 1
4  6 1 2 4 5 5 7
4  6 4 6 3 2 5 2
</code>```

I do a query like this

```<code>employe.where(
   A > 7 &
(

 (C<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & F<3)

)
)
</code>```

Is there any way to simplify the above query? Because I have more than 20 columns in my table and I have do the above query for all columns. It looks ugly and same code in every line. Even if I could something like this would look nice

```<code>q1 = [C, D, E, F, G]
q2 = [B, D, E, F, G]
q3 = [B, C, E, F, G]
q4 = [B, C, D, F, G]
q5 = [B, C, D, E, G]
q6 = [B, C, D, E, F]
employe.where(
   A > 7 &
(
  q1<3 | q2<3 | q4<4 | q5<3 | q6<3
)
)
</code>```

答:
If all values (columns) from the list must be less than 3, then the greatest value in this list must be also less than 3, so you can use greatest function, something like:

```<code>Where
  Greatest( c, d, e, f, g ) < 3
  Or
  Greatest( b, d, e, f, g ) < 3
  Or
  Greatest( b, c, d, e, f ) < 3
  Or
  .....
</code>```

Body:
I have a table named employe with following content

id A B C D E F G
1  8 4 6 3 2 5 2
1  7 3 1 2 1 3 7
3  9 2 3 3 2 6 1
4  6 1 2 4 5 5 7
4  6 4 6 3 2 5 2

I do a query like this

employe.where(
   A > 7 &
(

 (C<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & D<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & E<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & F<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & G<3)
|(B<3 & C<3 & D<3 & E<3 & F<3)

)
)

Is there any way to simplify the above query? Because I have more than 20 columns in my table and I have do the above query for all columns. It looks ugly and same code in every line. Even if I could something like this would look nice

q1 = [C, D, E, F, G]
q2 = [B, D, E, F, G]
q3 = [B, C, E, F, G]
q4 = [B, C, D, F, G]
q5 = [B, C, D, E, G]
q6 = [B, C, D, E, F]
employe.where(
   A > 7 &
(
  q1<3 | q2<3 | q4<4 | q5<3 | q6<3
)
)

Body:
If all values (columns) from the list must be less than 3, then the greatest value in this list must be also less than 3, so you can use greatest function, something like:

Where
  Greatest( c, d, e, f, g ) < 3
  Or
  Greatest( b, d, e, f, g ) < 3
  Or
  Greatest( b, c, d, e, f ) < 3
  Or
  .....


问:
Failed to create SipSession; network unavailable and only reboot helps
I am developing a simple application that allows user to initiate call using sip protocol.
The problem is inability to create SipSession in some cases (e.g. deleting application with active sip-session, and installing it again).

In this case, I am getting error:

```<code>android.net.sip.SipException: Failed to create SipSession; network unavailable?
</code>```

And it works only after physical device reboot.

My Sip class:

```<code>public class SipDataManager {

private Context context;
private SipManager sipManager;
private SipProfile sipProfile;
private SipSession sipSession;
private UserProfile userProfile;

public SipDataManager(Context context, UserProfile userProfile) {
    this.context = context;
    this.userProfile = userProfile;
}

public void initialize() throws SipException {
    Log.d("mylog", "initialize manager");
    if (sipManager == null) {
        Log.d("mylog", "sip manager is not null");
        sipManager = SipManager.newInstance(context);
    }
    initializeProfile();
}

private void initializeProfile() throws SipException {
    if (sipManager == null)
        return;
    if (sipProfile != null) {
        close();
    }
    sipProfile = userProfile.build();
    Intent intent = new Intent();
    intent.setAction("ru.tenet.sipclient.INCOMING_CALL");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, Intent.FILL_IN_DATA);
    sipManager.open(sipProfile, pendingIntent, null);
    sipSession = sipManager.createSipSession(sipProfile, new MySipSessionListener());
    sipManager.setRegistrationListener(sipProfile.getUriString(), new MySipRegistrationListener());
}

public void close() {
    try {
        if (sipProfile != null) {
            sipManager.close(sipProfile.getUriString());
        }
    } catch (Exception ee) {
        Log.e("mylog", "Failed to close local profile.", ee);
    }
}
//getters and setters
</code>```

I tried to remove this

```<code>sipSession = sipManager.createSipSession(sipProfile, new MySipSessionListener());
</code>```

In this case I will not get any Exception, but SipRegistrationListener callbacks will not getting call.

And only reboot helps..

Someone faced this problem? I didn't find any correct solution for this..

SOLUTION
The problem is in my device or firmware (Samsung Galaxy s4, Android 5.0.1 official, but some integrated apps were deleted with root).
Checked on Samsung Galaxy s4 with Android 4.3.1 with cyanogen - no problem.

答:
I have the same problem and have not been able to programmatically correct it.  Current solution is to add a delayed handler of 10 seconds to check if the OnRegistrationDone and OnRegistering events have fired during that time.  The following code is placed immediately before the manager.setRegistrationListener method in the initializeLocalProfile function.  When this error condition is detected, the SIP preferences activity is launched and the user notified with SIP Library Error, requesting them to restart the device.  The same handler also detects problems connecting to the defined SIP server with the Server Not Found notification to the user.  Both of these error conditions normally trigger the "registration timed out" error, but you cannot differentiate the two error types in that event, and it takes 30 seconds to time out.</p>

```<code>            if (!manager.isOpened(me.getUriString())) {
                if (me_listener == null) {
                    manager.open(me, pi, null);
                } else {
                    manager.open(me, pi, me_listener);
                }
            }
            // This listener must be added AFTER manager.open is called,
            // Otherwise the methods aren't guaranteed to fire.

            if (me_listener == null) {
                bConnecting = true;
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (sentConnecting == false && bLocalOpen == false) { //never connected or connecting
                            updateStatus("SIP Library Error");
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                            SharedPreferences.Editor editor = prefs.edit();
                            editor.remove("namePref");
                            editor.remove("domainPref");
                            editor.putString("statusPref", "SIP Library Error - Please Restart Device and Try Again");
                            editor.commit();
                            updatePreferences();
                            return;
                        } else if (bConnecting == true && bLocalOpen == false) { //never connected
                            updateStatus("Server Not Found");
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                            SharedPreferences.Editor editor = prefs.edit();
                            editor.remove("namePref");
                            editor.remove("domainPref");
                            editor.putString("statusPref", "Server Not Found, Please Edit and Try Again");
                            editor.commit();
                            updatePreferences();
                            return;
                        }
                    }
                }, 10000);
</code>```

Body:
I am developing a simple application that allows user to initiate call using sip protocol.
The problem is inability to create SipSession in some cases (e.g. deleting application with active sip-session, and installing it again).

In this case, I am getting error:

android.net.sip.SipException: Failed to create SipSession; network unavailable?

And it works only after physical device reboot.

My Sip class:

public class SipDataManager {

private Context context;
private SipManager sipManager;
private SipProfile sipProfile;
private SipSession sipSession;
private UserProfile userProfile;

public SipDataManager(Context context, UserProfile userProfile) {
    this.context = context;
    this.userProfile = userProfile;
}

public void initialize() throws SipException {
    Log.d("mylog", "initialize manager");
    if (sipManager == null) {
        Log.d("mylog", "sip manager is not null");
        sipManager = SipManager.newInstance(context);
    }
    initializeProfile();
}

private void initializeProfile() throws SipException {
    if (sipManager == null)
        return;
    if (sipProfile != null) {
        close();
    }
    sipProfile = userProfile.build();
    Intent intent = new Intent();
    intent.setAction("ru.tenet.sipclient.INCOMING_CALL");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, Intent.FILL_IN_DATA);
    sipManager.open(sipProfile, pendingIntent, null);
    sipSession = sipManager.createSipSession(sipProfile, new MySipSessionListener());
    sipManager.setRegistrationListener(sipProfile.getUriString(), new MySipRegistrationListener());
}

public void close() {
    try {
        if (sipProfile != null) {
            sipManager.close(sipProfile.getUriString());
        }
    } catch (Exception ee) {
        Log.e("mylog", "Failed to close local profile.", ee);
    }
}
//getters and setters

I tried to remove this

sipSession = sipManager.createSipSession(sipProfile, new MySipSessionListener());

In this case I will not get any Exception, but SipRegistrationListener callbacks will not getting call.

And only reboot helps..

Someone faced this problem? I didn't find any correct solution for this..

SOLUTION
The problem is in my device or firmware (Samsung Galaxy s4, Android 5.0.1 official, but some integrated apps were deleted with root).
Checked on Samsung Galaxy s4 with Android 4.3.1 with cyanogen - no problem.

Body:
I have the same problem and have not been able to programmatically correct it.  Current solution is to add a delayed handler of 10 seconds to check if the OnRegistrationDone and OnRegistering events have fired during that time.  The following code is placed immediately before the manager.setRegistrationListener method in the initializeLocalProfile function.  When this error condition is detected, the SIP preferences activity is launched and the user notified with SIP Library Error, requesting them to restart the device.  The same handler also detects problems connecting to the defined SIP server with the Server Not Found notification to the user.  Both of these error conditions normally trigger the "registration timed out" error, but you cannot differentiate the two error types in that event, and it takes 30 seconds to time out.

            if (!manager.isOpened(me.getUriString())) {
                if (me_listener == null) {
                    manager.open(me, pi, null);
                } else {
                    manager.open(me, pi, me_listener);
                }
            }
            // This listener must be added AFTER manager.open is called,
            // Otherwise the methods aren't guaranteed to fire.

            if (me_listener == null) {
                bConnecting = true;
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (sentConnecting == false && bLocalOpen == false) { //never connected or connecting
                            updateStatus("SIP Library Error");
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                            SharedPreferences.Editor editor = prefs.edit();
                            editor.remove("namePref");
                            editor.remove("domainPref");
                            editor.putString("statusPref", "SIP Library Error - Please Restart Device and Try Again");
                            editor.commit();
                            updatePreferences();
                            return;
                        } else if (bConnecting == true && bLocalOpen == false) { //never connected
                            updateStatus("Server Not Found");
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                            SharedPreferences.Editor editor = prefs.edit();
                            editor.remove("namePref");
                            editor.remove("domainPref");
                            editor.putString("statusPref", "Server Not Found, Please Edit and Try Again");
                            editor.commit();
                            updatePreferences();
                            return;
                        }
                    }
                }, 10000);


问:
Reusing Google Api Bearer Token to access user's Drive
I have the following:

```<code>   gapi.auth.authorize(
        { client_id: CLIENT_ID, scope: SCOPES, immediate: false },
        handleAuthResult);
</code>```

Which gives me access to an access_token:

The goal is that a user of this application can grant access to my app to use their google drive to store their content.  I need to be able to use this token to:

Read files

Post files

Over a long period of time without reauthenticating via the google login page.  How can this be achieved?  I'm using C# as a backend.

答:
You will need to switch from doing OAuth in JavaScript in the browser to doing OAuth on your server. It's well documented here https://developers.google.com/identity/protocols/OAuth2WebServer
You have the choice of using the OAuth c# library, or simply calling the REST endpoints.

To achieve access without the user present, you'll need access_type=offline which ...

Set the value to offline if your application needs to refresh access
  tokens when the user is not present at the browser. This is the method
  of refreshing access tokens described later in this document. This
  value instructs the Google authorization server to return a refresh
  token and an access token the first time that your application
  exchanges an authorization code for tokens.

You will then get a Refresh Token on the first time the user grants permission. You will need to save this Refresh Token in some sort of server datastore. You can then use it at any time to request an Access Token.

Body:
I have the following:

   gapi.auth.authorize(
        { client_id: CLIENT_ID, scope: SCOPES, immediate: false },
        handleAuthResult);

Which gives me access to an access_token:

The goal is that a user of this application can grant access to my app to use their google drive to store their content.  I need to be able to use this token to:

Read files

Post files

Over a long period of time without reauthenticating via the google login page.  How can this be achieved?  I'm using C# as a backend.


问:
WPF Charting Toolkit: How to set a fixed X-axis range while adding real time data
I'm doing an application real time data charting basing on WPF Charting Toolkit. I get the datas via serial port.
The code of setting chart is below:

```<code>    <chartingToolkit:Chart  Margin="10,10,10,0" ClipToBounds="True" x:Name="chart1" Title="Chart Title">
        <chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}" DependentValueBinding="{Binding Value2}" ItemsSource="{Binding}" Background="Transparent" Cursor="No">
            <chartingToolkit:LineSeries.DataPointStyle>
                <Style TargetType="{x:Type chartingToolkit:LineDataPoint}">
                    <Setter Property="Height" Value="0"/>
                    <Setter Property="Width" Value="0" />
                    <Setter Property="Background" Value="Green"/>
                </Style>
            </chartingToolkit:LineSeries.DataPointStyle>
        </chartingToolkit:LineSeries>
    </chartingToolkit:Chart>
</code>```

It works good but I still need to set maximum and minimum values of X axis.
The X Values (Value1) are as number of received samples and the Y axis values (Value2) are  obviously as concrete values of the received samples.

My question is about the X axis range.

Currently, I'm getting minimum as 0 and maximinum as the highest number of sample which the serial port received in current moment.

But I want to set a permanent range of X axis which I want to see.

For example I want to see on the X axis range of 500 samples.

It means that when the number of samples exceeds 500, the max should be as the highest sample number and the min should be max-500.

The main difficulty is how to set it with real time data in WPF??

Can anyone help me, please??

Updated question

I'm updating my question after @jstreet advise.

I have this method which is running in separate thread within MainWindow class, likes below.

```<code> public partial class MainWindow : Window
  {
 public SerialPort serialPort1 = new SerialPort();
    public string rx_str = "";
    public string rx_str_copy;
    public int a;
    public double x, y;

      ObservableCollection<ChartData> chartData;
    ChartData objChartData;
    Thread myThread;

     public MainWindow()
    {
        InitializeComponent();
        string[] port = SerialPort.GetPortNames();
        foreach (string a in port)
        {
            comboPorts.Items.Add(a);
        }
        Array.Sort(port);
        comboPorts.Text = port[0];

        objChartData = new ChartData();
        chartData.Add(objChartData);
        chart1.DataContext = chartData;
        myThread = new Thread(new ThreadStart(Run));

    }

   public void Run()
       {
        while (true)
        {
            serialPort1.Write("a");
            rx_str = serialPort1.ReadTo("b");
            rx_str_copy = rx_str;
            x = a;
            y = Double.Parse(rx_str_copy,     CultureInfo.InvariantCulture);

            a++;

            Dispatcher.Invoke(new Action(delegate
            {

         chartData.Add(new ChartData() { Value1 = x,
       Value2= y             });
            }));

        }
    }
</code>```

This Run() method is responsible for receiving datas and adding it to the chart.

In another class I have handle of reaction on comming datas and settings  properties Valeu1 and Value2:

```<code>  public class ChartData : INotifyPropertyChanged
   {
    double _Value1;
    double _Value2;

    public double Value1
    {
        get
        {
            return _Value1;
        }
        set
        {
            _Value1 = value;
            OnPropertyChanged("Value1");
        }
    }

    public double Value2
    {
        get
        {
            return _Value2;
        }
        set
        {
            _Value2 = value;
            OnPropertyChanged("Value2");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new
     PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

How can I adapt @jstreet's solution to my behind code example??

答:
Create a MinValue dependency property in your view model and bind it to your axis Minimum property. Take a look:

XAML:

```<code><Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp31"
        xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
        x:Class="WpfApp31.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MyViewModel/>
    </Window.DataContext>
    <Grid>
        <chartingToolkit:Chart  Title="My Sample">
            <chartingToolkit:Chart.Axes>
                <chartingToolkit:LinearAxis Minimum="{Binding MinValue}" Orientation="X"></chartingToolkit:LinearAxis>
            </chartingToolkit:Chart.Axes>
            <chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}"
                                        DependentValueBinding="{Binding Value2}"
                                        ItemsSource="{Binding Data}">
            </chartingToolkit:LineSeries>
        </chartingToolkit:Chart>
    </Grid>
</Window>
</code>```

View Model:

```<code>public class MyViewModel : DependencyObject
{
    public int MinValue
    {
        get { return (int)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MinValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MinValueProperty =
        DependencyProperty.Register("MinValue", typeof(int), typeof(MyViewModel), new PropertyMetadata(default(int)));

    public ObservableCollection<MyDataModel> Data { get; set; }

    private Timer serialPort;
    private Random y;
    private int x;
    private int range;

    public MyViewModel()
    {
        range = 10;
        Data = new ObservableCollection<MyDataModel>();
        y = new Random(DateTime.Now.Millisecond);
        serialPort = new Timer(DataReceived, null, 500, 500);
    }
    private void DataReceived(object state)
    {
        Application.Current.Dispatcher.Invoke(() => {
            Data.Add(new MyDataModel { Value1 = x, Value2 = y.Next(10, 90) });
            MinValue = x < range ? 0 : x - range;
            x++;
        });
    }
}
</code>```

EDIT: For the record, I would probably not write this code quite like below. I'm doing it here just so you can move forward with it.

XAML:

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
    x:Class="WpfApp1.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="10*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <chartingToolkit:Chart Grid.Row="0"  Margin="10,10,10,0" ClipToBounds="True" x:Name="chart1" Title="Chart Title">
        <chartingToolkit:Chart.Axes>
            <chartingToolkit:LinearAxis Minimum="{Binding MinValue}" Orientation="X"></chartingToolkit:LinearAxis>
        </chartingToolkit:Chart.Axes>
        <chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}" DependentValueBinding="{Binding Value2}" ItemsSource="{Binding chartData}" Background="Transparent" Cursor="No">
            <chartingToolkit:LineSeries.DataPointStyle>
                <Style TargetType="{x:Type chartingToolkit:LineDataPoint}">
                    <Setter Property="Height" Value="0"/>
                    <Setter Property="Width" Value="0" />
                    <Setter Property="Background" Value="Green"/>
                </Style>
            </chartingToolkit:LineSeries.DataPointStyle>
        </chartingToolkit:LineSeries>
    </chartingToolkit:Chart>

    <Button Grid.Row="1" x:Name="btn1" Click="btn1_Click">START</Button>

</Grid>
</code>```

CS:

```<code>public partial class MainWindow : Window
{
    public double MinValue
    {
        get { return (double)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MinValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MinValueProperty =
        DependencyProperty.Register("MinValue", typeof(double), typeof(MainWindow), new PropertyMetadata(default(double)));

    //public SerialPort serialPort1 = new SerialPort();
    //public string rx_str = "";
    //public string rx_str_copy;
    //public int a;
    public double x, y;

    public ObservableCollection<ChartData> chartData { get; set; }
    ChartData objChartData;
    Thread myThread;
    Random r;
    int range = 50;

    public MainWindow()
    {
        InitializeComponent();

        r = new Random();

        DataContext = this;

        /*
        string[] port = SerialPort.GetPortNames();

        foreach (string a in port)
        {
            comboPorts.Items.Add(a);
        }

        Array.Sort(port);
        comboPorts.Text = port[0];
        */

        objChartData = new ChartData();
        chartData = new ObservableCollection<ChartData>();
        chartData.Add(objChartData);
        //chart1.DataContext = chartData;
        myThread = new Thread(new ThreadStart(Run));
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        myThread.Start();
    }

    public void Run()
    {
        while (true)
        {
            //serialPort1.Write("a");
            //rx_str = serialPort1.ReadTo("b");
            //rx_str_copy = rx_str;

            //x = a;
            //y = Double.Parse(rx_str_copy, CultureInfo.InvariantCulture);

            //a++;

            Dispatcher.Invoke(new Action(delegate
            {
                chartData.Add(new ChartData()
                {
                    Value1 = x,
                    Value2 = r.NextDouble(),
                    //Value2 = y
                });
                MinValue = x < range ? 0 : x - range;
                x++;
            }));

            Thread.Sleep(50);
        }
    }
}
</code>```

Body:
I'm doing an application real time data charting basing on WPF Charting Toolkit. I get the datas via serial port.
The code of setting chart is below:

    <chartingToolkit:Chart  Margin="10,10,10,0" ClipToBounds="True" x:Name="chart1" Title="Chart Title">
        <chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}" DependentValueBinding="{Binding Value2}" ItemsSource="{Binding}" Background="Transparent" Cursor="No">
            <chartingToolkit:LineSeries.DataPointStyle>

            </chartingToolkit:LineSeries.DataPointStyle>
        </chartingToolkit:LineSeries>
    </chartingToolkit:Chart>

It works good but I still need to set maximum and minimum values of X axis.
The X Values (Value1) are as number of received samples and the Y axis values (Value2) are  obviously as concrete values of the received samples.

My question is about the X axis range.

Currently, I'm getting minimum as 0 and maximinum as the highest number of sample which the serial port received in current moment.

But I want to set a permanent range of X axis which I want to see.

For example I want to see on the X axis range of 500 samples.

It means that when the number of samples exceeds 500, the max should be as the highest sample number and the min should be max-500.

The main difficulty is how to set it with real time data in WPF??

Can anyone help me, please??

Updated question

I'm updating my question after @jstreet advise.

I have this method which is running in separate thread within MainWindow class, likes below.

 public partial class MainWindow : Window
  {
 public SerialPort serialPort1 = new SerialPort();
    public string rx_str = "";
    public string rx_str_copy;
    public int a;
    public double x, y;

      ObservableCollection<ChartData> chartData;
    ChartData objChartData;
    Thread myThread;

     public MainWindow()
    {
        InitializeComponent();
        string[] port = SerialPort.GetPortNames();
        foreach (string a in port)
        {
            comboPorts.Items.Add(a);
        }
        Array.Sort(port);
        comboPorts.Text = port[0];

        objChartData = new ChartData();
        chartData.Add(objChartData);
        chart1.DataContext = chartData;
        myThread = new Thread(new ThreadStart(Run));

    }

   public void Run()
       {
        while (true)
        {
            serialPort1.Write("a");
            rx_str = serialPort1.ReadTo("b");
            rx_str_copy = rx_str;
            x = a;
            y = Double.Parse(rx_str_copy,     CultureInfo.InvariantCulture);

            a++;

            Dispatcher.Invoke(new Action(delegate
            {

         chartData.Add(new ChartData() { Value1 = x,
       Value2= y             });
            }));

        }
    }

This Run() method is responsible for receiving datas and adding it to the chart.

In another class I have handle of reaction on comming datas and settings  properties Valeu1 and Value2:

  public class ChartData : INotifyPropertyChanged
   {
    double _Value1;
    double _Value2;

    public double Value1
    {
        get
        {
            return _Value1;
        }
        set
        {
            _Value1 = value;
            OnPropertyChanged("Value1");
        }
    }

    public double Value2
    {
        get
        {
            return _Value2;
        }
        set
        {
            _Value2 = value;
            OnPropertyChanged("Value2");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new
     PropertyChangedEventArgs(propertyName));
        }
    }
}

How can I adapt @jstreet's solution to my behind code example??

Body:
Create a MinValue dependency property in your view model and bind it to your axis Minimum property. Take a look:

XAML:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp31"
        xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
        x:Class="WpfApp31.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MyViewModel/>
    </Window.DataContext>
    <Grid>
        <chartingToolkit:Chart  Title="My Sample">
            <chartingToolkit:Chart.Axes>
                <chartingToolkit:LinearAxis Minimum="{Binding MinValue}" Orientation="X"></chartingToolkit:LinearAxis>
            </chartingToolkit:Chart.Axes>
            <chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}"
                                        DependentValueBinding="{Binding Value2}"
                                        ItemsSource="{Binding Data}">
            </chartingToolkit:LineSeries>
        </chartingToolkit:Chart>
    </Grid>
</Window>

View Model:

public class MyViewModel : DependencyObject
{
    public int MinValue
    {
        get { return (int)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MinValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MinValueProperty =
        DependencyProperty.Register("MinValue", typeof(int), typeof(MyViewModel), new PropertyMetadata(default(int)));

    public ObservableCollection<MyDataModel> Data { get; set; }

    private Timer serialPort;
    private Random y;
    private int x;
    private int range;

    public MyViewModel()
    {
        range = 10;
        Data = new ObservableCollection<MyDataModel>();
        y = new Random(DateTime.Now.Millisecond);
        serialPort = new Timer(DataReceived, null, 500, 500);
    }
    private void DataReceived(object state)
    {
        Application.Current.Dispatcher.Invoke(() => {
            Data.Add(new MyDataModel { Value1 = x, Value2 = y.Next(10, 90) });
            MinValue = x < range ? 0 : x - range;
            x++;
        });
    }
}

EDIT: For the record, I would probably not write this code quite like below. I'm doing it here just so you can move forward with it.

XAML:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
    x:Class="WpfApp1.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="10*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <chartingToolkit:Chart Grid.Row="0"  Margin="10,10,10,0" ClipToBounds="True" x:Name="chart1" Title="Chart Title">
        <chartingToolkit:Chart.Axes>
            <chartingToolkit:LinearAxis Minimum="{Binding MinValue}" Orientation="X"></chartingToolkit:LinearAxis>
        </chartingToolkit:Chart.Axes>
        <chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}" DependentValueBinding="{Binding Value2}" ItemsSource="{Binding chartData}" Background="Transparent" Cursor="No">
            <chartingToolkit:LineSeries.DataPointStyle>
                <Style TargetType="{x:Type chartingToolkit:LineDataPoint}">
                    <Setter Property="Height" Value="0"/>
                    <Setter Property="Width" Value="0" />
                    <Setter Property="Background" Value="Green"/>
                </Style>
            </chartingToolkit:LineSeries.DataPointStyle>
        </chartingToolkit:LineSeries>
    </chartingToolkit:Chart>

    <Button Grid.Row="1" x:Name="btn1" Click="btn1_Click">START</Button>

</Grid>

CS:

public partial class MainWindow : Window
{
    public double MinValue
    {
        get { return (double)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MinValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MinValueProperty =
        DependencyProperty.Register("MinValue", typeof(double), typeof(MainWindow), new PropertyMetadata(default(double)));

    //public SerialPort serialPort1 = new SerialPort();
    //public string rx_str = "";
    //public string rx_str_copy;
    //public int a;
    public double x, y;

    public ObservableCollection<ChartData> chartData { get; set; }
    ChartData objChartData;
    Thread myThread;
    Random r;
    int range = 50;

    public MainWindow()
    {
        InitializeComponent();

        r = new Random();

        DataContext = this;

        /*
        string[] port = SerialPort.GetPortNames();

        foreach (string a in port)
        {
            comboPorts.Items.Add(a);
        }

        Array.Sort(port);
        comboPorts.Text = port[0];
        */

        objChartData = new ChartData();
        chartData = new ObservableCollection<ChartData>();
        chartData.Add(objChartData);
        //chart1.DataContext = chartData;
        myThread = new Thread(new ThreadStart(Run));
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        myThread.Start();
    }

    public void Run()
    {
        while (true)
        {
            //serialPort1.Write("a");
            //rx_str = serialPort1.ReadTo("b");
            //rx_str_copy = rx_str;

            //x = a;
            //y = Double.Parse(rx_str_copy, CultureInfo.InvariantCulture);

            //a++;

            Dispatcher.Invoke(new Action(delegate
            {
                chartData.Add(new ChartData()
                {
                    Value1 = x,
                    Value2 = r.NextDouble(),
                    //Value2 = y
                });
                MinValue = x < range ? 0 : x - range;
                x++;
            }));

            Thread.Sleep(50);
        }
    }
}


问:
For of and click event in es6
if I use jquery it's working.

```<code>$(document).ready(function() {
   $('btn').click(function() {
       alert('start');
   });
});
</code>```

but I want use native es6

```<code>window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i of btn.length) {
        i.onclick( function () {
            alert( 'start' );
        });
    }
};
</code>```

error btn.length[Symbol.iterator] is not a function

And this doesn't work too.

```<code>window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i=0; i < btn.length; i++) {

        i.onclick = function () {
            alert( 'start' );
        };
    }
};
</code>```

答:
The for of loop will iterate over the elements of a collection that has a [Symbol.iterator] property. In your ES6 snippet you are trying to iterate over the returned HTMLCollection length eg. for (let i of btn.length)....

Here is what you should do instead.

let btns = document.getElementsByClassName( 'btn' );

for ( let btn of btns ) {
  btn.onclick = function() {
    console.clear()
    console.log(this.textContent)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="btn">Btn 1</button>
<button class="btn">Btn 2</button>
<button class="btn">Btn 3</button>
<button class="btn">Btn 4</button></code>```

Title: For of and click event in es6

Body:
if I use jquery it's working.

$(document).ready(function() {
   $('btn').click(function() {
       alert('start');
   });
});

but I want use native es6

window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i of btn.length) {
        i.onclick( function () {
            alert( 'start' );
        });
    }
};

error btn.length[Symbol.iterator] is not a function

And this doesn't work too.

window.onload = function() {
    let btn = document.getElementsByClassName( 'btn' );
    for (let i=0; i < btn.length; i++) {

        i.onclick = function () {
            alert( 'start' );
        };
    }
};

Body:
The for of loop will iterate over the elements of a collection that has a [Symbol.iterator] property. In your ES6 snippet you are trying to iterate over the returned HTMLCollection length eg. for (let i of btn.length)....

Here is what you should do instead.

let btns = document.getElementsByClassName( 'btn' );

for ( let btn of btns ) {
  btn.onclick = function() {
    console.clear()
    console.log(this.textContent)
  }
}

<button class="btn">Btn 1</button>
<button class="btn">Btn 2</button>
<button class="btn">Btn 3</button>
<button class="btn">Btn 4</button>


问:
directory listing denied
Whenever I click on a hyperlink, I get an error that says "Directory Listing Denied". What should I do?</p>

答: You have to turn on a feature in iis that enables directory listing. Check if this works http://technet.microsoft.com/en-us/library/cc731109(WS.10).aspx</p>

Title: directory listing denied


问:
How to keep Microsoft Edge from reloading my page as soon as memory hits the 4GB mark?
I'm in the process of refactoring a demo where +70,000 flight trajectories with approximately 3,500,000 recorded positions are loaded into a map with live 2D to 3D switching.

As you can imagine, this consumes quite a lot of memory. In fact, I'm currently hitting peaks of up to 4,25GB memory consumption in Chrome :

Unfortunately, memory consumption in Edge is even worse! Edge doesn't even get below 3,2GB after loading the data, and on average it seems to consume about 1GB more of memory in Chrome.

To make things worse, Edge can't handle 4GB of memory for one page. As soon as my memory consumption his the 4GB mark, it kills the process and starts reloading the page :

Can anyone help me come up with a way to overcome this problem in Edge without reducing the amount of data that's being loaded into the browser?

For example, is there a way to change the memory limits for Edge so it can handle pages of 4GB and up? Or what do you suggest I could try to prevent the used memory of my page from reaching the 4GB mark?

答: I faced similar problems with IE and Silverlight in which the application was rendering maps, lines with animations etc. IE could not render/load/animate when the memory exceeds 1.5gb. No matter what the version of IE or Windows, the problem could not be resolved so the related bug had been marked as a COTS issue. I don't know if there is an exact memory limits (there is no related documation) but I know you cannot tune memory constraints for IE. So, you should handle this issue in your application code logics. You should figure out in what situations the problem occurs because the problem may not be the exact memory size. The problem may still exists even if you handle the issue for 4Gb limitations. By the way, the demo application you submitted does not support neither IE or Edge which may be due to the issues above.</p>