问:
Installing the Python3 bindings for libtorrent on Ubuntu
I'm trying to install libtorrent for Python3. It's a wrapper for a C++ library. However, I can't seem to get it to work.

I've tried:

```<code>$ sudo apt-get install python-libtorrent

$ sudo apt-get install python3-libtorrent

$ sudo apt-get install libtorrent-rasterbar-dev

$ sudo apt-get install libtorrent-rasterbar-dev
</code>```

The PyPi page doesn't have a download link, and as a result it doesn't seem to be installable via pip. Interestingly, it seems to work in Python2, but unfortunately, the rest of the project is in Python3.

答:
On Non-Windows System:

The setup.py is generated by running ./configure --enable-python-binding.

Choose the Python version you want to install with.

To build the Python bindings do:

Run:

```<code>python setup.py build
</code>```

As root, run:

```<code>python setup.py install
</code>```

For detailed Information see: http://www.libtorrent.org/python_binding.html

Body:
I'm trying to install libtorrent for Python3. It's a wrapper for a C++ library. However, I can't seem to get it to work.

I've tried:

$ sudo apt-get install python-libtorrent

$ sudo apt-get install python3-libtorrent

$ sudo apt-get install libtorrent-rasterbar-dev

$ sudo apt-get install libtorrent-rasterbar-dev

The PyPi page doesn't have a download link, and as a result it doesn't seem to be installable via pip. Interestingly, it seems to work in Python2, but unfortunately, the rest of the project is in Python3.

Body:
On Non-Windows System:

The setup.py is generated by running ./configure --enable-python-binding.

Choose the Python version you want to install with.

To build the Python bindings do:

Run:

python setup.py build

As root, run:

python setup.py install

For detailed Information see: http://www.libtorrent.org/python_binding.html


来源: stackexchange

问:
Find the value property of an object that is inside of a linked list, using recursive function
This is a JavaScript practice exercise.

Suppose I have a linked list object as follow:

```<code>   var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}
</code>```

I need to write a recursive method to find the value of a certain sub-listed object.

For example, the method "nth":

```<code>   console.log(nth(list, 1));
</code>```

Should return value 20.

This is easy to accomplish if I change it to an array first.

However, I cannot change it to an array, the method "nth" has to be recursive.

If my method has to eventually return the value property, how do I make it recursive to the next sub-list? Doesn't the method has to return the next linked list in order to get to the object I desire?

Here's a hint that the question gave:

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the Nth element of the list that’s in this list’s rest property.

答:
Try it:

```<code>var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}};

      var  i  = 0
    recurs = function(obj,x){

      if(x===i){
        return obj.value
      }else{
       i++;
        return recurs(obj.rest,x);
      }

    };
    console.log(recurs(list,1));

var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}};
</code>```

or

```<code>recurs = function(obj,x,i = 0 ){

  if(x===i){
    return obj.value
  }else{
   i++;
    return recurs(obj.rest,x,i);
  }

};
console.log(recurs(list,1));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is a JavaScript practice exercise.

Suppose I have a linked list object as follow:

   var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}

I need to write a recursive method to find the value of a certain sub-listed object.

For example, the method "nth":

   console.log(nth(list, 1));

Should return value 20.

This is easy to accomplish if I change it to an array first.

However, I cannot change it to an array, the method "nth" has to be recursive.

If my method has to eventually return the value property, how do I make it recursive to the next sub-list? Doesn't the method has to return the next linked list in order to get to the object I desire?

Here's a hint that the question gave:

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the Nth element of the list that’s in this list’s rest property.

Body:
Try it:

var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}};

      var  i  = 0
    recurs = function(obj,x){

      if(x===i){
        return obj.value
      }else{
       i++;
        return recurs(obj.rest,x);
      }

    };
    console.log(recurs(list,1));

var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}};

or

recurs = function(obj,x,i = 0 ){

  if(x===i){
    return obj.value
  }else{
   i++;
    return recurs(obj.rest,x,i);
  }

};
console.log(recurs(list,1));


问:
incresing counter in a recursive function
I have a question about the functionality of increasing values within a recursive function.

When I use:

counter++ does not work

But when i use counter + 1 It works correctly.

I also found another way for it to work: ++counter, but I really could not understand what a difference it is to use the ++ before the counter.

Example:

```<code>printEachName = (companyNames, newPeople, counter, callback) => {
  if (companyNames.length === newPeople.length) {
    return callback(false, companyNames);
  }
  console.log('counter >>> ', counter);
  let newP = newPeople[counter];

  companyNames.push(newP.name);
  printEachName(companyNames, newPeople, counter + 1, callback);
}

printEachName([], newPeople, 0, (errorPrinting, response) => {
  if (errorPrinting) {
    //res.send()
    return;
  }

  console.log('response is >>> ', response);
});
</code>```

答:
++ before variable is pre-increment operator,whereas ++ after variable is post-increment operator.

In

```<code>printEachName(companyNames, newPeople, counter++, callback);
</code>```

counter's value is updated after the printEachName() is executed.

whereas in

```<code>printEachName(companyNames, newPeople, ++counter, callback);
</code>```

counter's value is updated instantly i.e. even before the printEachName() is actually executed.

But when you use

```<code>printEachName(companyNames, newPeople, counter + 1, callback);
</code>```

then counter's value isn't updated at all.But counter+1 is passed as parameter to the function.

Body:
I have a question about the functionality of increasing values within a recursive function.

When I use:

counter++ does not work

But when i use counter + 1 It works correctly.

I also found another way for it to work: ++counter, but I really could not understand what a difference it is to use the ++ before the counter.

Example:

printEachName = (companyNames, newPeople, counter, callback) => {
  if (companyNames.length === newPeople.length) {
    return callback(false, companyNames);
  }
  console.log('counter >>> ', counter);
  let newP = newPeople[counter];

  companyNames.push(newP.name);
  printEachName(companyNames, newPeople, counter + 1, callback);
}

printEachName([], newPeople, 0, (errorPrinting, response) => {
  if (errorPrinting) {
    //res.send()
    return;
  }

  console.log('response is >>> ', response);
});

Body:
++ before variable is pre-increment operator,whereas ++ after variable is post-increment operator.

In

printEachName(companyNames, newPeople, counter++, callback);

counter's value is updated after the printEachName() is executed.

whereas in

printEachName(companyNames, newPeople, ++counter, callback);

counter's value is updated instantly i.e. even before the printEachName() is actually executed.

But when you use

printEachName(companyNames, newPeople, counter + 1, callback);

then counter's value isn't updated at all.But counter+1 is passed as parameter to the function.


问:
Generate Entity domain model from classes
I write my domain classes first. Entity framework allows you to generate code and create a database and also generate domain classes. What about generating the entity diagram from the already written domain and then generating the database?</p>

答:
You can:

Build classes, then generate a DB, then make a UML model (not an entity model) from your classes (code-first)

Build a model, generate classes, generate a DB (model-first)

But there's nothing built in that precisely matches the flow in your question.

ContentLicense: CC BY-SA 2.5


问:
Multiple local search algorithms to find global optima
So I'm fairly new to the whole evolutionary and genetic algorithm world and I'm in the process of writing one now that will optimize an array and return the best possible solution - the fitness.

My algorithm right now is optimized through simulated annealing, I can change the cooling rate and starting temperature to change the pressure and diversity of the population to get different results, it works great. My question is, is using two different kinds of local search in one algorithm viable? Say I limit my iterations to 5000 for example. Would it be worth using 4000 for simulated annealing and then devote the remaining 1000 to a hill climber local search to find the optimal solution from the values found in the first local search? Or is using two different local searches in one algorithm just not standard practice? I'm new to this world of programming so I'm open to any suggestions!

答:
I use stimulated annealing (SA) to help me optimize error estimation in delta-style 3d printer.  I'm fitting a 34 dof error function to samples error map.  I run 3 million iterations of SA followed by hill climbing (HC).  The HC reduces the error (cost) function value.  I don't know of this is common, but it works for me.
Typical results:  original error function, 150.  After SA, 18.  After HC, 2.</p>


问:
What does '@' char mean before parameter name in method declaration?

Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

```<code>protected void Method1(Type1 @arg1, Type2 arg2)
...
</code>```

I use c# with .net 3.5.

Thanks.

答:
It is a way of escaping an identifier.

E.g. the following two are equivalent:

```<code>protected void Method1(Type1 @arg1, Type2 arg2)
protected void Method1(Type1 arg1, Type2 arg2)
</code>```

@ is only really usefull if you need to name an identifier after a keyword. The below would not compile without the @:

protected void Method1(Type1 @class, Type2 arg2)

Body:
Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

protected void Method1(Type1 @arg1, Type2 arg2)
...

I use c# with .net 3.5.

Thanks.

Body:
It is a way of escaping an identifier.

E.g. the following two are equivalent:

protected void Method1(Type1 @arg1, Type2 arg2)
protected void Method1(Type1 arg1, Type2 arg2)

@ is only really usefull if you need to name an identifier after a keyword. The below would not compile without the @:

protected void Method1(Type1 @class, Type2 arg2)


问:
User input upperCase and lowerCase - Java
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error</p>

```<code>import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}
</code>```

答:
You can use</p>

```<code>char user = input.next().toUpperCase().charAt(0);
</code>```

Body:
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error

import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}

Body:
You can use

char user = input.next().toUpperCase().charAt(0);


问:
Fixed footer in landscape and portrait mode in Android
I would like to have a fixed footer something like this:

I tried to achieve this using relative layout:

```<code>   <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/_12sdp"
        android:layout_alignParentBottom="true">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Version 1.0 Demo"
            android:layout_marginTop="@dimen/_22sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/versionText" />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Copyright (c) 2017 Aglive Pty Ltd"
            android:layout_marginTop="@dimen/_8sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/copyrightText"
            android:layout_alignParentBottom="false"
            android:layout_below="@id/versionText" />
        <RelativeLayout
            android:orientation="vertical"
            android:layout_column="0"
            android:layout_row="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_columnSpan="7"
            android:layout_marginTop="7.0dp"
            android:layout_marginBottom="7.0dp"
            android:id="@+id/relative"
            android:layout_below="@id/copyrightText">
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Terms of Service"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="5.5sp"
                android:id="@+id/termsOfService"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="@dimen/_15sdp" />
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Contact Us"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="@dimen/_15sdp"
                android:id="@+id/contactUs"
                android:layout_alignParentRight="true" />
        </RelativeLayout>
    </RelativeLayout>
</code>```

But the problem here is that whenever the keyboard opens up the footer moves up. For which I tried to add WindowSoftInputMode =  SoftInput.AdjustPan. It worked for the keyboard issue but whenever the screen rotates to landscape mode the footer overlaps the other text. Also my relative layout does not come as required.  The relative layout seems to be covering other text.

答: If you want to have both modes in the app then you have to make an xml with same name placed in folder layout-land along with the one you have made. With this you will have different layouts for both portrait and landscape and hence this will solve your problem. Hope this helps.</p>

Body:
I would like to have a fixed footer something like this:

I tried to achieve this using relative layout:

   <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/_12sdp"
        android:layout_alignParentBottom="true">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Version 1.0 Demo"
            android:layout_marginTop="@dimen/_22sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/versionText" />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Copyright (c) 2017 Aglive Pty Ltd"
            android:layout_marginTop="@dimen/_8sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/copyrightText"
            android:layout_alignParentBottom="false"
            android:layout_below="@id/versionText" />
        <RelativeLayout
            android:orientation="vertical"
            android:layout_column="0"
            android:layout_row="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_columnSpan="7"
            android:layout_marginTop="7.0dp"
            android:layout_marginBottom="7.0dp"
            android:id="@+id/relative"
            android:layout_below="@id/copyrightText">
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Terms of Service"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="5.5sp"
                android:id="@+id/termsOfService"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="@dimen/_15sdp" />
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Contact Us"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="@dimen/_15sdp"
                android:id="@+id/contactUs"
                android:layout_alignParentRight="true" />
        </RelativeLayout>
    </RelativeLayout>

But the problem here is that whenever the keyboard opens up the footer moves up. For which I tried to add WindowSoftInputMode =  SoftInput.AdjustPan. It worked for the keyboard issue but whenever the screen rotates to landscape mode the footer overlaps the other text. Also my relative layout does not come as required.  The relative layout seems to be covering other text.


问:
How to change the displayed title of a soft keyboard in iOS?
Here's how my soft keyboard's title is currently displayed among the keyboard choices in iOS:

I'd prefer for it to be displayed like the Gboard example above it, simply as "ASETNIOP" on the top line and "Multiple languages" below, as shown in the mockup here:

I can change the lowercased prefix if I modify the extension's "Display Name" in Target->General->Identity, but I can't eliminate it (or the associated dash) entirely:

And (although I don't actually need to do this) it doesn't look like it's possible to change the main application's Display Name at all - it's grayed out:

Can anyone let me know where I need to go to make these changes, and where I need to go to change the Language designation as well?

答:
For multi language, open your info.plist as source code of extension part.
Then find

```<code> <key>PrimaryLanguage</key>
    <string>en-US</string>
</code>```

replace with

```<code><key>PrimaryLanguage</key>
    <string>mul</string>
</code>```

Body:
For multi language, open your info.plist as source code of extension part.
Then find

 <key>PrimaryLanguage</key>
    <string>en-US</string>

replace with

<key>PrimaryLanguage</key>
    <string>mul</string>


问:
Second largest in negative numbers
I am using this to find second largest in the array, it works fine in case of positive numbers but it fails in case of negative numbers.
Can you suggest this solution so it works for negative numbers also?</p>

```<code>arr = [-3,3,-3,3];
k = max(arr)
m= arr[0];
i=0;
k = max(arr)
while i <(len(arr)-1):
    if(m<arr[i+1] and arr[i+1] !=k ):
        m= arr[i+1]
    i+=1
print m
</code>```

答:
Here is an O(n) solution that finds and returns the second largest element in an array of numbers:

```<code>def second_largest(seq):
    largest = float("-inf")
    second_largest = float("-inf")

    for elt in seq:
        if elt > largest:
            second_largest = largest
            largest = elt
        elif elt > second_largest:
            second_largest = elt
    return second_largest

arr = [-3,3,-3,3]
print(second_largest(arr))

arr = [-3, -4, -5, -1]
print(second_largest(arr))
</code>```

Caveat:

Unless your sequence is very large (1000's of elements), it it probably faster to sort it and retrieve the second element.

Title: Second largest in negative numbers

Body:
I am using this to find second largest in the array, it works fine in case of positive numbers but it fails in case of negative numbers.
Can you suggest this solution so it works for negative numbers also?

arr = [-3,3,-3,3];
k = max(arr)
m= arr[0];
i=0;
k = max(arr)
while i <(len(arr)-1):
    if(m<arr[i+1] and arr[i+1] !=k ):
        m= arr[i+1]
    i+=1
print m

Body:
Here is an O(n) solution that finds and returns the second largest element in an array of numbers:

def second_largest(seq):
    largest = float("-inf")
    second_largest = float("-inf")

    for elt in seq:
        if elt > largest:
            second_largest = largest
            largest = elt
        elif elt > second_largest:
            second_largest = elt
    return second_largest

arr = [-3,3,-3,3]
print(second_largest(arr))

arr = [-3, -4, -5, -1]
print(second_largest(arr))

Caveat:

Unless your sequence is very large (1000's of elements), it it probably faster to sort it and retrieve the second element.


问:
The Meaning of @override in Android Studio
I am completely new to Android Studio and I want to know the purpose of the @Override statement in Android Studio.

答: That's a special, compiler reserved, Java annotation that denotes that you are overriding a superclass method.</p>

ContentLicense: CC BY-SA 4.0


问:
is it possible to make a NSTextView autoscroll down to the last line in swift xcode
i'm trying to make it so that every time i press enter in a textfield

it makes a NSTextView automaticly scroll down to the last line in the scrollview

```<code>let range = NSMakeRange(textView.text.characters.count - 1, 0)
textView.scrollRangeToVisible(range)
</code>```

i tried all sort of ways but it never scroll down the text in the NSTextView

答:
You can addLocalMonitorForEvents for .keyDown events to your view controller and check if the event.keyCode == 76.

```<code>import Cocoa

class ViewController: NSViewController {
    @IBOutlet var textview: NSTextView!
    var keyDown: Any!
    override func viewDidLoad() {
        super.viewDidLoad()
        keyDown = NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
            self.keyDown(with: $0)
            return $0
        }
    }
    override func keyDown(with event: NSEvent) {
        if event.keyCode == 76 {
            print("enter key pressed")
            DispatchQueue.main.async {
                self.textview.scrollRangeToVisible(NSRange(location: self.textview.string.count, length: 0))
            }
        }
    }
    deinit {
        NSEvent.removeMonitor(keyDown)
    }
}
</code>```

If you just need to scroll it down after your method adds lines to the textview just add this to the end of it:

```<code>DispatchQueue.main.async {
    self.textview.scrollRangeToVisible(NSRange(location: self.textview.string.count, length: 0))
}
</code>```

Body:
i'm trying to make it so that every time i press enter in a textfield

it makes a NSTextView automaticly scroll down to the last line in the scrollview

let range = NSMakeRange(textView.text.characters.count - 1, 0)
textView.scrollRangeToVisible(range)

i tried all sort of ways but it never scroll down the text in the NSTextView

Body:
You can addLocalMonitorForEvents for .keyDown events to your view controller and check if the event.keyCode == 76.

import Cocoa

class ViewController: NSViewController {
    @IBOutlet var textview: NSTextView!
    var keyDown: Any!
    override func viewDidLoad() {
        super.viewDidLoad()
        keyDown = NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
            self.keyDown(with: $0)
            return $0
        }
    }
    override func keyDown(with event: NSEvent) {
        if event.keyCode == 76 {
            print("enter key pressed")
            DispatchQueue.main.async {
                self.textview.scrollRangeToVisible(NSRange(location: self.textview.string.count, length: 0))
            }
        }
    }
    deinit {
        NSEvent.removeMonitor(keyDown)
    }
}

If you just need to scroll it down after your method adds lines to the textview just add this to the end of it:

DispatchQueue.main.async {
    self.textview.scrollRangeToVisible(NSRange(location: self.textview.string.count, length: 0))
}


问:
Angular service observable updating from within component
I am an Angular newbie and am stuck on a problem.

I have a problem where i have a BehaviourSubject defined within a singleton service which is being shared among 3 components. My app.ts component gets array data from an API call, then updates the BehaviourSubject using next() within the service.

The issue i am having is that when i subscribe to the service within component A, copy the data to a local empty array and then push items into that array, Component B is seeing the items appended to the array within it's subscription to paymentdataservice.ts which i don't want (I only want the 'master list').

I'm obviously doing something wrong and perhaps have misunderstood the concept of observables so i'd greatly appreciate some help as this has me stumped!

All functions are called from ngOnInit which i have excluded for code simplicity.

PaymentDataService.ts:

```<code>@Injectable()

constructor(private http: Http) { }

private _paymentlistdata = new BehaviorSubject<any>([]);
public readonly paymentlistdata = this._paymentlistdata.asObservable();

//Function to get latest Paymethodlist data and input into subject
updatePaymentListData(data) {
    this._paymentlistdata.next(data);
}

//HTTP Call for PayMethods from API
getPayMethods() {
        let token = localStorage.getItem('token')
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('https://api.xyz.com/api/paymethods?
        token='+token+'', {headers: headers})
            .map((res: Response) => res.json())
}
</code>```

App.ts

App.ts needs to get the Master Payment list and store it in the service for performance purposes, so it doesn't have to pull from the API in each component.

```<code>import { PaymentDataService } from '../app/services/paymentdata.service';

constructor(private payservice : PaymentDataService) { }

//Get payment data from PaymentDataService HTTP API
getPaymentData() {
    this.payservice.getPayMethods().subscribe(
    data => {
    if (data.Error === false) {
        this.payservice.updatePaymentListData(data); //update Behaviour
        subject so other components can use the data locally
    } else {
    this.router.navigate(["errorloading"]);
    console.log (data);
    }
},
error => {
    this.router.navigate(["errorloading"]);
    console.log (error);
});
</code>```

Component A

Component A needs to take the master payment list and append some additional options for a drop down menu. These options are only applicable in this component.

```<code>import { PaymentDataService } from '../app/services/paymentdata.service';

constructor(private payservice : PaymentDataService) { }

paymentlistdatalocal = [];

//Populate paymentlist from service observable
getPaymentListData() {
    this.paymentlistsubscription = this._payservice.paymentlistdata
    .subscribe(
    data => {
        this.paymentlistdatalocal = data.Paymethods;
        this.paymentlistdatalocal.push({paymethod_id:0, paymethod_name: 'No
        payment method selected'});
    });
}
</code>```

Component B

Component B simply needs to list out the master payment list

```<code>import { PaymentDataService } from '../app/services/paymentdata.service';

constructor(private payservice : PaymentDataService) { }

paymentlistdatalocal = [];

//Populate paymentlist from service observable
getPaymentListData() {
    this.paymentlistsubscription = this._payservice.paymentlistdata
    .subscribe(
    data => {
        this.paymentlistdatalocal = data.Paymethods;
        console.log (data.Paymethods);
    });
}
</code>```

A console.log from Component B shows the items appended from Component A, assuming I initialise Component A first, otherwise it only contains the 'Master List' obtained from the initial API call.

答: Men this is becouse you are assigning the variable by reference, It means, when you do this.paymentlistdatalocal = data.Paymethods, you're not doing an other space in memory, try this.paymentlistdatalocal = Object.create(data.Paymethods) and the same in component B.

Body:
I am an Angular newbie and am stuck on a problem.

I have a problem where i have a BehaviourSubject defined within a singleton service which is being shared among 3 components. My app.ts component gets array data from an API call, then updates the BehaviourSubject using next() within the service.

The issue i am having is that when i subscribe to the service within component A, copy the data to a local empty array and then push items into that array, Component B is seeing the items appended to the array within it's subscription to paymentdataservice.ts which i don't want (I only want the 'master list').

I'm obviously doing something wrong and perhaps have misunderstood the concept of observables so i'd greatly appreciate some help as this has me stumped!

All functions are called from ngOnInit which i have excluded for code simplicity.

PaymentDataService.ts:

@Injectable()

constructor(private http: Http) { }

private _paymentlistdata = new BehaviorSubject<any>([]);
public readonly paymentlistdata = this._paymentlistdata.asObservable();

//Function to get latest Paymethodlist data and input into subject
updatePaymentListData(data) {
    this._paymentlistdata.next(data);
}

//HTTP Call for PayMethods from API
getPayMethods() {
        let token = localStorage.getItem('token')
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('https://api.xyz.com/api/paymethods?
        token='+token+'', {headers: headers})
            .map((res: Response) => res.json())
}

App.ts

App.ts needs to get the Master Payment list and store it in the service for performance purposes, so it doesn't have to pull from the API in each component.

import { PaymentDataService } from '../app/services/paymentdata.service';

constructor(private payservice : PaymentDataService) { }

//Get payment data from PaymentDataService HTTP API
getPaymentData() {
    this.payservice.getPayMethods().subscribe(
    data => {
    if (data.Error === false) {
        this.payservice.updatePaymentListData(data); //update Behaviour
        subject so other components can use the data locally
    } else {
    this.router.navigate(["errorloading"]);
    console.log (data);
    }
},
error => {
    this.router.navigate(["errorloading"]);
    console.log (error);
});

Component A

Component A needs to take the master payment list and append some additional options for a drop down menu. These options are only applicable in this component.

import { PaymentDataService } from '../app/services/paymentdata.service';

constructor(private payservice : PaymentDataService) { }

paymentlistdatalocal = [];

//Populate paymentlist from service observable
getPaymentListData() {
    this.paymentlistsubscription = this._payservice.paymentlistdata
    .subscribe(
    data => {
        this.paymentlistdatalocal = data.Paymethods;
        this.paymentlistdatalocal.push({paymethod_id:0, paymethod_name: 'No
        payment method selected'});
    });
}

Component B

Component B simply needs to list out the master payment list

import { PaymentDataService } from '../app/services/paymentdata.service';

constructor(private payservice : PaymentDataService) { }

paymentlistdatalocal = [];

//Populate paymentlist from service observable
getPaymentListData() {
    this.paymentlistsubscription = this._payservice.paymentlistdata
    .subscribe(
    data => {
        this.paymentlistdatalocal = data.Paymethods;
        console.log (data.Paymethods);
    });
}

A console.log from Component B shows the items appended from Component A, assuming I initialise Component A first, otherwise it only contains the 'Master List' obtained from the initial API call.


问:
CSV file_reading datetime
I have a csv file, and it has time column with format:
yyyy-mm-dd hh:mm:ss

I want to plot other columns as a function of time. So i need to define "time". I have assigned to each time, a number, which is yyyymmddhhmmss.

However, it generates a jump between numbers, whenever date, or month or year chanegs.

How can I solve this?

答:
Fist you should format correctly. Pandas is aware of the object datetime but when you use some of the import functions it is taken as a string. So what you need to do is make sure the column is set as the datetime type not as a string.

```<code>df['date']  = pd.to_datetime(df['date'])
</code>```

Now you can use the plot function or whatever in matplotlib. After plotting you should call

```<code>fig.autofmt_xdate()
</code>```

to get the date ticks to work

Title: CSV file_reading datetime

Body:
Fist you should format correctly. Pandas is aware of the object datetime but when you use some of the import functions it is taken as a string. So what you need to do is make sure the column is set as the datetime type not as a string.

df['date']  = pd.to_datetime(df['date'])

Now you can use the plot function or whatever in matplotlib. After plotting you should call

fig.autofmt_xdate()

to get the date ticks to work


问:
C++ Template pointer-based variable results in garbage being returned unless stored and outputted before
For an assignment I'm implementing a hash map. My valueOf() function is returning garbage in main even though its finding the key's value and outputting it in the function. I've found 2 possible solutions, but neither are suitable for my case.

Class overview:

HashTable

```<code>template <typename V>
class HashTable {
private:
    string m_key;
    V m_value;
...
</code>```

MyStringMap

```<code>template <typename V>
class MyStringMap : public AbstractStringMap<V> {
private:
    HashTable<V> * m_table;
    int m_maxSize;
    int m_currSize;
    string EMPTY_KEY;
    string TOMB_KEY;
...
</code>```

And the problem function (which is in MyStringMap):

```<code>const V& valueOf(const string& key) const throw (Oops) {
    int home;
    int pos = home = hash(key);

    // stops at found key (for success) or empty key (for failed)
    for (int i = 1; (key != m_table[pos].getKey()) && (EMPTY_KEY != m_table[pos].getKey()); i++)
        pos = (home + probe(key, i)) % m_maxSize;

    // check found pos and return accordingly
    if (key == m_table[pos].getKey()) {
        return m_table[pos].getValue();
    }
    else
        throw Oops("Key Not Found!!");
}
</code>```

The return m_table[pos].getValue(); part above is returning garbage when outputting in main and causing the program to crash. However, having cout << "FOUND [" << m_table[pos].getKey() << "] [" << m_table[pos].getValue() << "]" << endl; in the function (before the return) displays the correct value.

The way I'm running it in main is:

```<code>try {
  cout << "Person1? " << thelist.valueOf("Person1") << endl;
  cout << "Person2? " << thelist.valueOf("Person2") << endl;
} catch (Oops e) {
  cout << e.getMsg() << endl;
}
</code>```

The two solutions I found, but aren't suitable are:

Appending c_str() to the end of the function in main, Ex: cout << "Person1? " << thelist.valueOf("Person1").c_str() << endl;. Since I can't edit main (as the assignment dictates), I can't use this.

Returning a variable instead of the direct value AND having to output it there, Ex:

V found = m_table[pos].getValue();
cout << "FOUND [" << m_table[pos].getKey() << "] [" << found << "]" << endl;

For whatever reason, this makes the return display the correct non-garbage value. But, its a hacky solution and I don't want the extra output.

Any help would be appreciated. I'll clarify where needed as I'm sure this probably makes no sense.

答:
I'm guessing your getValue() method returns a V object. That object is created on the stack. You then return a reference to that object. Then the stack is overwriten by something else going on in your computer, and you get garbage. This would also explain why returning an object works: it is allocated in the memory space and is not overwritten.

In short, you are returning a reference to an object on the stack. You can't do that because you don't know what will be at that address when it is read later.

Body:
For an assignment I'm implementing a hash map. My valueOf() function is returning garbage in main even though its finding the key's value and outputting it in the function. I've found 2 possible solutions, but neither are suitable for my case.

Class overview:

HashTable

template <typename V>
class HashTable {
private:
    string m_key;
    V m_value;
...

MyStringMap

template <typename V>
class MyStringMap : public AbstractStringMap<V> {
private:
    HashTable<V> * m_table;
    int m_maxSize;
    int m_currSize;
    string EMPTY_KEY;
    string TOMB_KEY;
...

And the problem function (which is in MyStringMap):

const V& valueOf(const string& key) const throw (Oops) {
    int home;
    int pos = home = hash(key);

    // stops at found key (for success) or empty key (for failed)
    for (int i = 1; (key != m_table[pos].getKey()) && (EMPTY_KEY != m_table[pos].getKey()); i++)
        pos = (home + probe(key, i)) % m_maxSize;

    // check found pos and return accordingly
    if (key == m_table[pos].getKey()) {
        return m_table[pos].getValue();
    }
    else
        throw Oops("Key Not Found!!");
}

The return m_table[pos].getValue(); part above is returning garbage when outputting in main and causing the program to crash. However, having cout << "FOUND [" << m_table[pos].getKey() << "] [" << m_table[pos].getValue() << "]" << endl; in the function (before the return) displays the correct value.

The way I'm running it in main is:

try {
  cout << "Person1? " << thelist.valueOf("Person1") << endl;
  cout << "Person2? " << thelist.valueOf("Person2") << endl;
} catch (Oops e) {
  cout << e.getMsg() << endl;
}

The two solutions I found, but aren't suitable are:

Appending c_str() to the end of the function in main, Ex: cout << "Person1? " << thelist.valueOf("Person1").c_str() << endl;. Since I can't edit main (as the assignment dictates), I can't use this.

Returning a variable instead of the direct value AND having to output it there, Ex:

V found = m_table[pos].getValue();
cout << "FOUND [" << m_table[pos].getKey() << "] [" << found << "]" << endl;

For whatever reason, this makes the return display the correct non-garbage value. But, its a hacky solution and I don't want the extra output.

Any help would be appreciated. I'll clarify where needed as I'm sure this probably makes no sense.


答: It's a Java annotation that tells the compiler that the method is intended to override a method from the superclass.  It's not strictly necessary, but does help to catch errors at compile time.</p>

Title: The Meaning of @override in Android Studio

Body: I am completely new to Android Studio and I want to know the purpose of the @Override statement in Android Studio.


问:
Why isn't my for loop functioning without data.frame()?
I'm working on the Coursera Data Science course. I evaluated my code along the way to the correct answer, and for some reason by 2nd to last step doesn't produce the output I expect, even though my final answer is correct.

Here's my final code. It's a function that reads a directory full of csv files and counts the complete values in each file and prints that along with the associated id number.

```<code>complete<-function(dir, id=1:332){
    comp_cases<-numeric()
    files<-list.files(dir, full.names=TRUE){
        for (i in id){
            data<-read.csv(filelist[i])
            vals<-sum(complete.cases(data)
            comp_cases<-c(comp_cases,v)
           }

  data.frame(id, comp_cases)
}
</code>```

However, when I omit data.frame(id, comp_cases) and just call comp_cases, I get the number of complete cases in the first file, instead of the vector of the number of completes in all of the files. Why isn't my loop functioning without the data.frame(id, comp_cases), which is outside of the loop itself? What exactly is data.frames() doing here? Im using R 3.42 on Windows.

答:
The value returned when a function is called in R is the value of the statement.  you can explicitly return a value using return(something), of course, but when you don't need to explicitly cause the function to be returned, many R programmers will omit the call to return() and simply end the function with a function call (in this case data.frame(...) that returns a value, or if the value was already returned, the programmer may just evaluate the value to be returned as in:

```<code>my_fun <- function(x){
    out <- NULL # initialize the return value.

    ... do things ...

    out # implicitly return this value
}
</code>```

As an aside, everything in R has a return value.  for and while loops return NULL, and an assignments (e.g. x = 3) return the value assigned.  R programmers may do weird things with this last bit such as:

```<code>complete<-function(dir, id=2:332){
    comp_cases<-numeric()
    files<-list.files(dir, full.names=TRUE){
        for (i in id){
            data<-read.csv(filelist[i])
            vals<-sum(complete.cases(data)
            comp_cases<-c(comp_cases,v)
           }

  answer <- data.frame(id, comp_cases)
}
</code>```

which are technically valid code, but weird from a code-as-documentation perspective

Body:
I'm working on the Coursera Data Science course. I evaluated my code along the way to the correct answer, and for some reason by 2nd to last step doesn't produce the output I expect, even though my final answer is correct.

Here's my final code. It's a function that reads a directory full of csv files and counts the complete values in each file and prints that along with the associated id number.

complete<-function(dir, id=1:332){
    comp_cases<-numeric()
    files<-list.files(dir, full.names=TRUE){
        for (i in id){
            data<-read.csv(filelist[i])
            vals<-sum(complete.cases(data)
            comp_cases<-c(comp_cases,v)
           }

  data.frame(id, comp_cases)
}

However, when I omit data.frame(id, comp_cases) and just call comp_cases, I get the number of complete cases in the first file, instead of the vector of the number of completes in all of the files. Why isn't my loop functioning without the data.frame(id, comp_cases), which is outside of the loop itself? What exactly is data.frames() doing here? Im using R 3.42 on Windows.

Body:
The value returned when a function is called in R is the value of the statement.  you can explicitly return a value using return(something), of course, but when you don't need to explicitly cause the function to be returned, many R programmers will omit the call to return() and simply end the function with a function call (in this case data.frame(...) that returns a value, or if the value was already returned, the programmer may just evaluate the value to be returned as in:

my_fun <- function(x){
    out <- NULL # initialize the return value.

    ... do things ...

    out # implicitly return this value
}

As an aside, everything in R has a return value.  for and while loops return NULL, and an assignments (e.g. x = 3) return the value assigned.  R programmers may do weird things with this last bit such as:

complete<-function(dir, id=2:332){
    comp_cases<-numeric()
    files<-list.files(dir, full.names=TRUE){
        for (i in id){
            data<-read.csv(filelist[i])
            vals<-sum(complete.cases(data)
            comp_cases<-c(comp_cases,v)
           }

  answer <- data.frame(id, comp_cases)
}

which are technically valid code, but weird from a code-as-documentation perspective


问:
Generating a unique ID
I was looking into functions that generate unique IDs - my specific requirement is that the unique ID would need to be 8 digits only.

Anyway I've just realised we can set an ID auto increment field to start from any number. So suppose I have it start from 11111111 - am I right in thinking that all new records will increment from this value? If so then I have my unique 8 digit ID and no need to use a function for this.

And also if a record is deleted then will a new record re-use that deleted ID?

答:
That is correct.  If your auto-number columns start at 11111111, then your next row will have the number 11111112.

When a record is deleted, its auto-number is not reused.

Edit: Regarding maximum values, that is dependent on the column type you have chosen.  From the MySQL documentation:

Use a large enough integer data type for the AUTO_INCREMENT column to hold the maximum sequence value you will need. When the column reaches the upper limit of the data type, the next attempt to generate a sequence number fails. For example, if you use TINYINT, the maximum permissible sequence number is 127. For TINYINT UNSIGNED, the maximum is 255.

You could use an INT and go up to 4294967295, or BIGINT and go up to 18446744073709551615.  See http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

Title: Generating a unique ID


问:
Is it possible to replace a Python function/method decorator at runtime?
If I have a function :

```<code>
@aDecorator
def myfunc1():
  # do something here

if __name__ = "__main__":
  # this will call the function and will use the decorator @aDecorator
  myfunc1()
  # now I want the @aDecorator to be replaced with the decorator @otherDecorator
  # so that when this code executes, the function no longer goes through
  # @aDecorator, but instead through @otherDecorator. How can I do this?
  myfunc1()
</code>```

Is it possible to replace a decorator at runtime?

答:
I know it's an old thread, but I had fun doing this</p>

```<code>def change_deco(name, deco, placeholder='    #'):
with open(name + '.py', 'r') as file:
    lines = file.readlines()
for idx, string in enumerate(lines):
    if placeholder in string and repr(placeholder) not in string:
        lines[idx] = f'    @{deco}\r\n'
exec(''.join(lines))
return locals()[name]
</code>```

OwnerDisplayName: Geo

Body:
If I have a function :

@aDecorator
def myfunc1():
  # do something here

if __name__ = "__main__":
  # this will call the function and will use the decorator @aDecorator
  myfunc1()
  # now I want the @aDecorator to be replaced with the decorator @otherDecorator
  # so that when this code executes, the function no longer goes through
  # @aDecorator, but instead through @otherDecorator. How can I do this?
  myfunc1()

Is it possible to replace a decorator at runtime?

Body:
I know it's an old thread, but I had fun doing this

def change_deco(name, deco, placeholder='    #'):
with open(name + '.py', 'r') as file:
    lines = file.readlines()
for idx, string in enumerate(lines):
    if placeholder in string and repr(placeholder) not in string:
        lines[idx] = f'    @{deco}\r\n'
exec(''.join(lines))
return locals()[name]


问:
Response code 500 in JMeter when running with threads
Getting the following error in JMeter while running the list of APIs (with no of threads:1-140 with ramp up period-1).

```<code>Response code:500
Response message: Internal Server Error
</code>```

How should I overcome this Error Response code in order to get the accurate response?
What should do to decrease amount of response with this response code?

答: Status code - 500 comes from server/API's and it's not an issue of Jmeter. Sometimes the concurrent requests are rejected by server as it's too weak to handle that number of requests.In my case, I asked my server team to scale up servers so that we can test the underlying API . It's worth mentioning that sometimes Jmeter also runs out of memory. You can do some tweaking in set HEAP=-Xms512m -Xmx512m property of jmeter execuble file. Also listeners consume too much resources.Try not to use them.

Body:
Getting the following error in JMeter while running the list of APIs (with no of threads:1-140 with ramp up period-1).

Response code:500
Response message: Internal Server Error

How should I overcome this Error Response code in order to get the accurate response?
What should do to decrease amount of response with this response code?


问:
C# - multiple thread start one thread
I have 3 threads in 3 classes running in parallel. Each of them, increase Pos or Neg of the Fourthclass by "1". After 3 threads are done, if Fourclass.Pos > Fourclass.Neg, it will run Terminal4.

Q: How can i run the Terminal4 only 1 time. Because putting Fourthclass.Terminal4(); in each Terminal1-2-3 will run the Terminal4 3 times.

Here is what i have done:

```<code>public class Firstclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal1()
    {
        if (Pos > Neg)
        {
            Fourthclass.Pos += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public class Secondclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal2()
    {
        if (Pos > Neg)
        {
            Fourthclass.Pos += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public class Thirdclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal3()
    {
        if (Pos > Neg)
        {
            Fourthclass.Neg += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public static class Fourthclass
{
    public static int Pos = 0;
    public static int Neg = 0;
    public static void Terminal4()
    {
        if (Pos > Neg)
        {
            Console.WriteLine("Pos = {0} - Neg = {1}", Pos, Neg);
            Console.WriteLine();
        }
        else { Console.WriteLine("fail"); }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Thread obj1 = new Thread(new ThreadStart(Firstclass.Terminal1));
        Thread obj2 = new Thread(new ThreadStart(Secondclass.Terminal2));
        Thread obj3 = new Thread(new ThreadStart(Thirdclass.Terminal3));
        obj1.Start();
        obj2.Start();
        obj3.Start();
    }
}
</code>```

答:
Original Answer

By the by... these increments are not thread safe, they may suffer the ABA problem and that is ignoring thread visibility problems.

For that problem, please use Interloked. Interlocked.Increment and Interlocked.Decrement will take care of it.

Now, for making a code block run only once, keep an int variable that will be 1 if it did run, and 0 if it did not. Then use Interlocked.CompareExchange:

```<code>int didrun;

// ...

if (Interlocked.CompareExchange(ref didrun, 1, 0) == 0)
{
    // code here will only run once, until you put didrun back to 0
}
</code>```

There are other ways, of course. This one is just very versatile.

Addendum: Ok, what it does...

Interlocked.CompareExchange will look at the value of the passed variable (didrun) compare it to the second parameter (0) and if it matches, it will change the variable to the value of first parameter (1) [Since it may change the variable, you have to pass it by ref]. The return value is what it found in the variable.

Thus, if it returns 0, you know it found 0, which means that it did update the value to 1. Now, the next time this piece of code is called, the value of the variable is 1, so Interlocked.CompareExchange returns 1 and the thread does not enter the block.

Ok, why do not use a bool instead? Because of thread visibility. A thread may change the value of the variable, but this update could happen in CPU cache only, and not be visible to other threads... Interlocked gets around of that problem. Just use Interlocked. And MSDN is your friend.

That will work regardless if you are using ThreadPool, Task or async/await or just plain old Threads as you do. I mention that because I would like to suggest using those...

Sneaky link to Threading in C#.

Extended Answer

In comment, you ask about a different behavior:

The Terminal4 has cooldown until the next run

Well, if there is a cool down (which I understand as a period) you do not only need to store whatever or not the code did run, but also when was the last time it did.

Now, the conditional cannot be just "run only if it has not run yet" but instead "run if it has not run yet or if the period from the last time it ran to now is greater than the cool down".

We have to check multiple things, that is a problem. Now the check will no longer be atomic (from the Latin atomus which means indivisible, from a- "not" + tomos "a cutting, slice, volume, section").

That is relevant because if the check is not atomic, we are back to the ABA problem.

I will use this case to explain the ABA problem. If we encode the following:

```<code>1. Check if the operation has not run (if it has not go to 4)
2. Get the last time it ran
3. Compute the difference from the last run to now (exit if less than cool down)
4. Update the last run time to now
5. Run code
</code>```

Two threads may do the following:

```<code> |
 t  Thread1: Check if the operation has not run (it has)
 i  Thread2: Check if the operation has not run (it has)
 m  Thread2: Get the last time it ran
 e  Thread1: Get the last time it ran
 |  Thread1: Compute the difference from the last run to now (more than cool down)
 v  Thread2: Compute the difference from the last run to now (more than cool down)
    Thread2: Update the last run time to now
    Thread2: Run code
    Thread1: Update the last run time to now
    Thread1: Run code
</code>```

As you see, they both Run code.

What we need is a way to check and update in a single atomic operation, that way the act of checking will alter the result of the other thread. That is what we get with Interlocked.

How Interlocked manages to do that is beyond the scope of the question. Suffice to say that there are some special CPU instructions for that.

The new pattern I suggest is the following (pseudocode):

```<code>bool canRun = false;
DateTime lastRunCopy;
DateTime now = DateTime.Now;
if (try to set lastRun to now if lastRun is not set, copy lastRun to lastRunCopy)
{
    // We set lastRun
    canRun = true;
}
else
{
    if ((now - lastRunCopy) < cooldown)
    {
        if (try to set lastRun to now if lastRun = lastRunCopy, copy lastRun to lastRunCopy)
        {
            // we updated it
            canRun = true;
        }
    }
    else
    {
            // Another thread got in
    }
}
if (canRun)
{
    // code here will only run once per cool down
}
</code>```

Notice I have expressed the operations in terms of "try to set X to Y if X is Z, copy X to W" which is how Interlocked.CompareExchange works.

There is a reason I left that in pseudo code, and that is that DateTime is not an atomic type.

In order to make the code work we will have to use DateTime.Ticks. For an unset value we will use 0 (00:00:00.0000000 UTC, January 1, 0001), which is something you have to worry about for a cool down greater than a couple of millennia.

In addition, of course, we will use the overload of Interlocked.CompareExchange that takes long because DateTime.Ticks is of that type.

Note: Ah, we will use TimeSpan.Ticks for the cool down.

The code is as follows:

```<code>long lastRun = 0;
long cooldown = TimeSpan.FromSeconds(1).Ticks; // Or whatever, I do not know.

// ...

bool canRun = false;
long lastRunCopy = 0;
long now = DateTime.Now.Ticks;
lastRunCopy = Interlocked.CompareExchange(ref lastRun, now, 0);
if (lastRunCopy == 0)
{
    // We set lastRun
    canRun = true;
}
else
{
    if ((now - lastRunCopy) < cooldown)
    {
        if (Interlocked.CompareExchange(ref lastRun, now, lastRunCopy) == lastRunCopy)
        {
            // we updated it
            canRun = true;
        }
        else
        {
            // Another thread got in
        }
    }
}
if (canRun)
{
    // code here will only run once per cooldown
}
</code>```

Alternatively, if you want to boil it down to a single conditional:

```<code>long lastRun = 0;
long cooldown = TimeSpan.FromSeconds(1).Ticks; // Or whatever, I do not know.

// ...

long lastRunCopy;
var now = DateTime.Now.Ticks;
if
(
    (lastRunCopy = Interlocked.CompareExchange(ref lastRun, now, 0)) == 0
    || now - lastRunCopy < cooldown
    && Interlocked.CompareExchange(ref lastRun, now, lastRunCopy) == lastRunCopy
)
{
    // code here will only run once per cooldown
}
</code>```

As I said, Interlocked.CompareExchange is versatile. Although, as you can see, you still need to think around the requirements.

Title: C# - multiple thread start one thread

Body:
I have 3 threads in 3 classes running in parallel. Each of them, increase Pos or Neg of the Fourthclass by "1". After 3 threads are done, if Fourclass.Pos > Fourclass.Neg, it will run Terminal4.

Q: How can i run the Terminal4 only 1 time. Because putting Fourthclass.Terminal4(); in each Terminal1-2-3 will run the Terminal4 3 times.

Here is what i have done:

public class Firstclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal1()
    {
        if (Pos > Neg)
        {
            Fourthclass.Pos += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public class Secondclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal2()
    {
        if (Pos > Neg)
        {
            Fourthclass.Pos += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public class Thirdclass
{
    static int Pos = 1;
    static int Neg = 0;
    public static void Terminal3()
    {
        if (Pos > Neg)
        {
            Fourthclass.Neg += 1;
         // Fourthclass.Terminal4();
        }
    }
}
public static class Fourthclass
{
    public static int Pos = 0;
    public static int Neg = 0;
    public static void Terminal4()
    {
        if (Pos > Neg)
        {
            Console.WriteLine("Pos = {0} - Neg = {1}", Pos, Neg);
            Console.WriteLine();
        }
        else { Console.WriteLine("fail"); }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Thread obj1 = new Thread(new ThreadStart(Firstclass.Terminal1));
        Thread obj2 = new Thread(new ThreadStart(Secondclass.Terminal2));
        Thread obj3 = new Thread(new ThreadStart(Thirdclass.Terminal3));
        obj1.Start();
        obj2.Start();
        obj3.Start();
    }
}

Body:
Original Answer

By the by... these increments are not thread safe, they may suffer the ABA problem and that is ignoring thread visibility problems.

For that problem, please use Interloked. Interlocked.Increment and Interlocked.Decrement will take care of it.

Now, for making a code block run only once, keep an int variable that will be 1 if it did run, and 0 if it did not. Then use Interlocked.CompareExchange:

int didrun;

// ...

if (Interlocked.CompareExchange(ref didrun, 1, 0) == 0)
{
    // code here will only run once, until you put didrun back to 0
}

There are other ways, of course. This one is just very versatile.

Addendum: Ok, what it does...

Interlocked.CompareExchange will look at the value of the passed variable (didrun) compare it to the second parameter (0) and if it matches, it will change the variable to the value of first parameter (1) [Since it may change the variable, you have to pass it by ref]. The return value is what it found in the variable.

Thus, if it returns 0, you know it found 0, which means that it did update the value to 1. Now, the next time this piece of code is called, the value of the variable is 1, so Interlocked.CompareExchange returns 1 and the thread does not enter the block.

Ok, why do not use a bool instead? Because of thread visibility. A thread may change the value of the variable, but this update could happen in CPU cache only, and not be visible to other threads... Interlocked gets around of that problem. Just use Interlocked. And MSDN is your friend.

That will work regardless if you are using ThreadPool, Task or async/await or just plain old Threads as you do. I mention that because I would like to suggest using those...

Sneaky link to Threading in C#.

Extended Answer

In comment, you ask about a different behavior:

The Terminal4 has cooldown until the next run

Well, if there is a cool down (which I understand as a period) you do not only need to store whatever or not the code did run, but also when was the last time it did.

Now, the conditional cannot be just "run only if it has not run yet" but instead "run if it has not run yet or if the period from the last time it ran to now is greater than the cool down".

We have to check multiple things, that is a problem. Now the check will no longer be atomic (from the Latin atomus which means indivisible, from a- "not" + tomos "a cutting, slice, volume, section").

That is relevant because if the check is not atomic, we are back to the ABA problem.

I will use this case to explain the ABA problem. If we encode the following:

1. Check if the operation has not run (if it has not go to 4)
2. Get the last time it ran
3. Compute the difference from the last run to now (exit if less than cool down)
4. Update the last run time to now
5. Run code

Two threads may do the following:

 |
 t  Thread1: Check if the operation has not run (it has)
 i  Thread2: Check if the operation has not run (it has)
 m  Thread2: Get the last time it ran
 e  Thread1: Get the last time it ran
 |  Thread1: Compute the difference from the last run to now (more than cool down)
 v  Thread2: Compute the difference from the last run to now (more than cool down)
    Thread2: Update the last run time to now
    Thread2: Run code
    Thread1: Update the last run time to now
    Thread1: Run code

As you see, they both Run code.

What we need is a way to check and update in a single atomic operation, that way the act of checking will alter the result of the other thread. That is what we get with Interlocked.

How Interlocked manages to do that is beyond the scope of the question. Suffice to say that there are some special CPU instructions for that.

The new pattern I suggest is the following (pseudocode):

bool canRun = false;
DateTime lastRunCopy;
DateTime now = DateTime.Now;
if (try to set lastRun to now if lastRun is not set, copy lastRun to lastRunCopy)
{
    // We set lastRun
    canRun = true;
}
else
{
    if ((now - lastRunCopy) < cooldown)
    {
        if (try to set lastRun to now if lastRun = lastRunCopy, copy lastRun to lastRunCopy)
        {
            // we updated it
            canRun = true;
        }
    }
    else
    {
            // Another thread got in
    }
}
if (canRun)
{
    // code here will only run once per cool down
}

Notice I have expressed the operations in terms of "try to set X to Y if X is Z, copy X to W" which is how Interlocked.CompareExchange works.

There is a reason I left that in pseudo code, and that is that DateTime is not an atomic type.

In order to make the code work we will have to use DateTime.Ticks. For an unset value we will use 0 (00:00:00.0000000 UTC, January 1, 0001), which is something you have to worry about for a cool down greater than a couple of millennia.

In addition, of course, we will use the overload of Interlocked.CompareExchange that takes long because DateTime.Ticks is of that type.

Note: Ah, we will use TimeSpan.Ticks for the cool down.

The code is as follows:

long lastRun = 0;
long cooldown = TimeSpan.FromSeconds(1).Ticks; // Or whatever, I do not know.

// ...

bool canRun = false;
long lastRunCopy = 0;
long now = DateTime.Now.Ticks;
lastRunCopy = Interlocked.CompareExchange(ref lastRun, now, 0);
if (lastRunCopy == 0)
{
    // We set lastRun
    canRun = true;
}
else
{
    if ((now - lastRunCopy) < cooldown)
    {
        if (Interlocked.CompareExchange(ref lastRun, now, lastRunCopy) == lastRunCopy)
        {
            // we updated it
            canRun = true;
        }
        else
        {
            // Another thread got in
        }
    }
}
if (canRun)
{
    // code here will only run once per cooldown
}

Alternatively, if you want to boil it down to a single conditional:

long lastRun = 0;
long cooldown = TimeSpan.FromSeconds(1).Ticks; // Or whatever, I do not know.

// ...

long lastRunCopy;
var now = DateTime.Now.Ticks;
if
(
    (lastRunCopy = Interlocked.CompareExchange(ref lastRun, now, 0)) == 0
    || now - lastRunCopy < cooldown
    && Interlocked.CompareExchange(ref lastRun, now, lastRunCopy) == lastRunCopy
)
{
    // code here will only run once per cooldown
}

As I said, Interlocked.CompareExchange is versatile. Although, as you can see, you still need to think around the requirements.


问:
Applying style.css to echo table
I've echo table in a PHP. Instead of having to style the table manually, how can I get it to pick up the same style for tables that I have listed in style.css?

Below, I have the code for echo table and the code for tables in style.css

```<code>echo "<table>";
echo "<thead>".
            "<tr>".
                '<th>ETF Ticker</th>'.
                '<th>ETF Name</th>'.
                '<th>1 Yr Direction %</th>'.
                '<th>Holding Name</th>'.
                '<th>Industry</th>'.
                '<th>% of total</th>'.
            "</tr>".
        "</thead>";

// Loop to show results
while($row = mysqli_fetch_assoc($result))
{
    echo "<tr>";
            echo  "<td>" . $row['ETF'] . "</td>";
            echo  "<td>" . $row['ETF NAME'] . "</td>";
             echo "<td>" . $row['1 YR Direction %'] . "</td>";
             echo "<td>" . $row['Holding Name'] . "</td>";
             echo "<td>" . $row['Industry'] . "</td>";
             echo "<td>" . $row['Percent Holdings'] . "</td>";

"</tr>";
}

echo "</table>";
</code>```

CSS

```<code>table {
    /* tables still need 'cellspacing="0"' in the markup */
    border-collapse: collapse;
    border-spacing: 0;
    margin: 0 0 1.5em;
    width: 100%;
    display: block;
    overflow-x: auto;
    white-space: nowrap;
    }

thead {
    font-weight: bold;
    border: 2px;
    background-color: #992c29
    color #f7f4f4;
    text-align: center;
}
</code>```

答: The style should work on the echoed table too just like html tables. Make sure that you have included the css file, deleted the cache of browser (or press ctrl + f5 on the keyboard), deleted framework's cache (maybe restart server to delete cache).</p>

Title: Applying style.css to echo table

Body:
I've echo table in a PHP. Instead of having to style the table manually, how can I get it to pick up the same style for tables that I have listed in style.css?

Below, I have the code for echo table and the code for tables in style.css

echo "
";
echo "
".
            "
".
                'ETF Ticker	'.
                'ETF Name	'.
                '1 Yr Direction %	'.
                'Holding Name	'.
                'Industry	'.
                '% of total	'.
            "
".
        "
";

// Loop to show results
while($row = mysqli_fetch_assoc($result))
{
    echo "
";
            echo  "" . $row['ETF'] . "	";
            echo  "" . $row['ETF NAME'] . "	";
             echo "" . $row['1 YR Direction %'] . "	";
             echo "" . $row['Holding Name'] . "	";
             echo "" . $row['Industry'] . "	";
             echo "" . $row['Percent Holdings'] . "	";

"
";
}

echo "
";

CSS

table {
    /* tables still need 'cellspacing="0"' in the markup */
    border-collapse: collapse;
    border-spacing: 0;
    margin: 0 0 1.5em;
    width: 100%;
    display: block;
    overflow-x: auto;
    white-space: nowrap;
    }

thead {
    font-weight: bold;
    border: 2px;
    background-color: #992c29
    color #f7f4f4;
    text-align: center;
}


问:
how to detect all dollar signs in different encoding with javascript
Suppose I have a string "$ $ $ ＄ ＄", Google chrome can detect each dollar sign in the string with ctrl+F. But Javascript cannot detect all of them.

I wish to detect and replace all dollar signs in the string with Javascript . Please help.

答:
This shall replace all occurences of dollar in mystring with 'R' :</p>

```<code>let mystring = "$ $ $ ＄ ＄";
mystring = mystring.replace(/\$/g , "R");
mystring = mystring.replace(/\＄/g , "R");
console.log(mystring);
</code>```

Body:
This shall replace all occurences of dollar in mystring with 'R' :

let mystring = "$ $ $ ＄ ＄";
mystring = mystring.replace(/\$/g , "R");
mystring = mystring.replace(/\＄/g , "R");
console.log(mystring);


答:
<s>Two</s>Four of your dollar signs are not the standard dollar sign character.

Take a close look at this screenshot from where I did Ctrl+F in Chrome:

See the extra padding around the last two $ characters? They're a different character. Chrome's presumably doing some work to consider them to be the same thing (I'd bet they do the same with a versus á), but JavaScript's string functions are more picky.

(There actually seem to be five different $ characters.)

```<code>var foo = '$ $ $ ＄ ＄';

foo = foo.replace('$', 'DOLLAR');
console.log(foo);
foo = foo.replace('＄', 'DOLLAR');
console.log(foo);
foo = foo.replace('＄', 'DOLLAR');
console.log(foo);
foo = foo.replace('$', 'DOLLAR');
console.log(foo);
foo = foo.replace('$', 'DOLLAR');
console.log(foo);
</code>```

Title: how to detect all dollar signs in different encoding with javascript

Body:
Suppose I have a string "$ $ $ ＄ ＄", Google chrome can detect each dollar sign in the string with ctrl+F. But Javascript cannot detect all of them.

I wish to detect and replace all dollar signs in the string with Javascript . Please help.

Body:
<s>Two</s>Four of your dollar signs are not the standard dollar sign character.

Take a close look at this screenshot from where I did Ctrl+F in Chrome:

See the extra padding around the last two $ characters? They're a different character. Chrome's presumably doing some work to consider them to be the same thing (I'd bet they do the same with a versus á), but JavaScript's string functions are more picky.

(There actually seem to be five different $ characters.)

var foo = '$ $ $ ＄ ＄';

foo = foo.replace('$', 'DOLLAR');
console.log(foo);
foo = foo.replace('＄', 'DOLLAR');
console.log(foo);
foo = foo.replace('＄', 'DOLLAR');
console.log(foo);
foo = foo.replace('$', 'DOLLAR');
console.log(foo);
foo = foo.replace('$', 'DOLLAR');
console.log(foo);


问:
incresing counter in a recursive function
I have a question about the functionality of increasing values within a recursive function.

When I use:

counter++ does not work

But when i use counter + 1 It works correctly.

I also found another way for it to work: ++counter, but I really could not understand what a difference it is to use the ++ before the counter.

Example:

```<code>printEachName = (companyNames, newPeople, counter, callback) => {
  if (companyNames.length === newPeople.length) {
    return callback(false, companyNames);
  }
  console.log('counter >>> ', counter);
  let newP = newPeople[counter];

  companyNames.push(newP.name);
  printEachName(companyNames, newPeople, counter + 1, callback);
}

printEachName([], newPeople, 0, (errorPrinting, response) => {
  if (errorPrinting) {
    //res.send()
    return;
  }

  console.log('response is >>> ', response);
});
</code>```

答:
Just to add to everyone else's explanations

```<code>counter++
</code>```

Is equivalent to this

```<code>temp = counter, counter = counter + 1, temp
</code>```

You can try it here to see

var counter1 = 123;
var foo1 = counter1++;

console.log("counter1:", counter1, "foo1:", foo1);

var counter2 = 123;
var foo2 = (temp = counter2, counter2 = counter2 + 1, temp);

console.log("counter2:", counter2, "foo2:", foo2);```

variable++ is a post increment. In other words return the value that was in the variable, then increment.

If you really want to just increment you just arguably use ++variable

Body:
I have a question about the functionality of increasing values within a recursive function.

When I use:

counter++ does not work

But when i use counter + 1 It works correctly.

I also found another way for it to work: ++counter, but I really could not understand what a difference it is to use the ++ before the counter.

Example:

printEachName = (companyNames, newPeople, counter, callback) => {
  if (companyNames.length === newPeople.length) {
    return callback(false, companyNames);
  }
  console.log('counter >>> ', counter);
  let newP = newPeople[counter];

  companyNames.push(newP.name);
  printEachName(companyNames, newPeople, counter + 1, callback);
}

printEachName([], newPeople, 0, (errorPrinting, response) => {
  if (errorPrinting) {
    //res.send()
    return;
  }

  console.log('response is >>> ', response);
});

Body:
Just to add to everyone else's explanations

counter++

Is equivalent to this

temp = counter, counter = counter + 1, temp

You can try it here to see

var counter1 = 123;
var foo1 = counter1++;

console.log("counter1:", counter1, "foo1:", foo1);

var counter2 = 123;
var foo2 = (temp = counter2, counter2 = counter2 + 1, temp);

console.log("counter2:", counter2, "foo2:", foo2);

variable++ is a post increment. In other words return the value that was in the variable, then increment.

If you really want to just increment you just arguably use ++variable


问:
Spring-boot restful web service connect to ftp server
Firstly , I am really new to spring framework and java.

I have the following, FTP server with subdirectory containing files.

I want to make getAll / getOne request to the server and also a process method where I will do asynchronous processing of a file and save it to a new subdirectory and notify client once processing complete.

So far I have managed to make GET / POST / DELETE requests to hard coded entities and display this in browser, also got similar functionality using embedded derby server.
Have model with constructor, getters and setters, created mappings to URI in my controller which calls my services to complete the request.

I'm struggling to figure out where do I implement the code to actually connect to the ftp server and how i do the processing asynchronously on the server itself.

Any link to resources or pseudo code to help me understand would be amazing, spring docs are quite complicated for my level. I couldn't find any simple(ish) examples to help me understand.

Thanks

答:
Create a FtpService class and annotate it with @Service. create a connect method inside it.

in the main method use the ftp service to connect to the ftp

```<code>FtpService ftpService = context.getBean(FtpService.class);
ftpService.connect();
</code>```

you can read about the @Async annotation that can make the process of the recieved files work asynchronously

Body:
Create a FtpService class and annotate it with @Service. create a connect method inside it.

in the main method use the ftp service to connect to the ftp

FtpService ftpService = context.getBean(FtpService.class);
ftpService.connect();

you can read about the @Async annotation that can make the process of the recieved files work asynchronously


问:
Python Pandas group datetimes by hour and count row
This is my transaction dataframe, where each row mean a transaction :

```<code>date               station
30/10/2017 15:20    A
30/10/2017 15:45    A
31/10/2017 07:10    A
31/10/2017 07:25    B
31/10/2017 07:55    B
</code>```

I need to group the start_date to a hour interval and count each city, so the end result will be:

```<code>date        hour      station   count
30/10/2017  16:00        A       2
31/10/2017  08:00        A       1
31/10/2017  08:00        B       2
</code>```

Where the first row means from 15:00 to 16:00 on 30/10/2017, there are 2 transactions in station A

How to do this in Pandas?

I tried this code, but the result is wrong :

```<code>df_start_tmp = df_trip[['Start Date', 'Start Station']]

times = pd.DatetimeIndex(df_start_tmp['Start Date'])

df_start = df_start_tmp.groupby([times.hour, df_start_tmp['Start Station']]).count()
</code>```

Thanks a lot for the help

答:
IIUC size+pd.Grouper

```<code>df.date=pd.to_datetime(df.date)
df.groupby([pd.Grouper(key='date',freq='H'),df.station]).size().reset_index(name='count')
Out[235]:
                 date station  count
0 2017-10-30 15:00:00       A      2
1 2017-10-31 07:00:00       A      1
2 2017-10-31 07:00:00       B      2
</code>```

Body:
This is my transaction dataframe, where each row mean a transaction :

date               station
30/10/2017 15:20    A
30/10/2017 15:45    A
31/10/2017 07:10    A
31/10/2017 07:25    B
31/10/2017 07:55    B

I need to group the start_date to a hour interval and count each city, so the end result will be:

date        hour      station   count
30/10/2017  16:00        A       2
31/10/2017  08:00        A       1
31/10/2017  08:00        B       2

Where the first row means from 15:00 to 16:00 on 30/10/2017, there are 2 transactions in station A

How to do this in Pandas?

I tried this code, but the result is wrong :

df_start_tmp = df_trip[['Start Date', 'Start Station']]

times = pd.DatetimeIndex(df_start_tmp['Start Date'])

df_start = df_start_tmp.groupby([times.hour, df_start_tmp['Start Station']]).count()

Thanks a lot for the help

Body:
IIUC size+pd.Grouper

df.date=pd.to_datetime(df.date)
df.groupby([pd.Grouper(key='date',freq='H'),df.station]).size().reset_index(name='count')
Out[235]:
                 date station  count
0 2017-10-30 15:00:00       A      2
1 2017-10-31 07:00:00       A      1
2 2017-10-31 07:00:00       B      2


答:
```<code>echo "<table class='class_name'>";
echo "<thead>".
            "<tr>".
                '<th>ETF Ticker</th>'.
                '<th>ETF Name</th>'.
                '<th>1 Yr Direction %</th>'.
                '<th>Holding Name</th>'.
                '<th>Industry</th>'.
                '<th>% of total</th>'.
            "</tr>".
        "</thead>";

// Loop to show results
while($row = mysqli_fetch_assoc($result))
{
    echo "<tr>";
            echo  "<td>" . $row['ETF'] . "</td>";
            echo  "<td>" . $row['ETF NAME'] . "</td>";
             echo "<td>" . $row['1 YR Direction %'] . "</td>";
             echo "<td>" . $row['Holding Name'] . "</td>";
             echo "<td>" . $row['Industry'] . "</td>";
             echo "<td>" . $row['Percent Holdings'] . "</td>";

"</tr>";
}

echo "</table>";
</code>```

<p>// just put class name in table with single qota</p>

Title: Applying style.css to echo table

Body:
echo "<table class='class_name'>";
echo "<thead>".
            "<tr>".
                '<th>ETF Ticker</th>'.
                '<th>ETF Name</th>'.
                '<th>1 Yr Direction %</th>'.
                '<th>Holding Name</th>'.
                '<th>Industry</th>'.
                '<th>% of total</th>'.
            "</tr>".
        "</thead>";

// Loop to show results
while($row = mysqli_fetch_assoc($result))
{
    echo "<tr>";
            echo  "<td>" . $row['ETF'] . "</td>";
            echo  "<td>" . $row['ETF NAME'] . "</td>";
             echo "<td>" . $row['1 YR Direction %'] . "</td>";
             echo "<td>" . $row['Holding Name'] . "</td>";
             echo "<td>" . $row['Industry'] . "</td>";
             echo "<td>" . $row['Percent Holdings'] . "</td>";

"</tr>";
}

echo "</table>";

// just put class name in table with single qota


问:
How do you have a workflow in hg, where one does very frequent commits?
Workflow I have is to do very frequent commits and pushes, then later when I am ready, combine the commits into a single commit (with histedit etc.) to cleanup the log.

With git, I would do a rebase and push. The dangling head left behind would not litter my log, and would eventually be garbage collected.

With mercurial, I end up with multiple heads. And if I close the branch to get rid of the stale heads, I end up with a million closed branches that still show up in the log. That defeats the original purpose.

How do you have such a workflow in mercurial without completely screwing up the log? Is there an alternative workflow that does work under mercurial?

NOTE that the frequent commits also get pushed out to a repo (just for safety). Which means I can't quite use things like strip.

答:
Consider the evolve extension, which is best explained in this post, though it's not bitbucket specific and is widely supported in Mercurial environments.  You probably have it installed and just need to enable it.

Once you grok it it's the best of all world.  It lets one commit replace another -- it obsoletes the other even if it's already pushed.  It lets you re-write commits in a way that doesn't break already pushed commits.  Think of it as git --amend or git rebase but safe for already pushed stuff.

When you do a push of a changeset that obsoletes one or more other changesets you, push obsolete markers for those changesets and anyone who subsequently pulls from that repo has the obsoleted changesets replaced in their history/log with what you've pushed. The obsoleted changesets exist still, but they don't clutter the log.

I hope we get something similar in git soon -- a few people have started work on similar features.


问:
Word comparison algorithm
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

```<code>   1,   John Doe,     ACME Comapny   (the typo is on purpose)
</code>```

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

答:
I'm implementing it in PHP, and I am now writing a piece of code that will break up 2 strings in words and compare each of the words from the first string with the words of the second string using levenshtein and accept the lowes possible values. Ill post it when I'm done.

Thanks a lot.

Update: Here's what I've come up with:

```<code>function myLevenshtein( $str1, $str2 )
{
  // prepare the words
  $words1 = explode( " ",  preg_replace( "/\s+/", " ", trim($str1) ) );
  $words2 = explode( " ",  preg_replace( "/\s+/", " ", trim($str2) ) );

  $found = array(); // array that keeps the best matched words so we don't check them again
  $score = 0;       // total score
  // In my case, strings that have different amount of words can be good matches too
  // For example, Acme Company and International Acme Company Ltd. are the same thing
  // I will just add the wordcount differencre to the total score, and weigh it more later if needed
  $wordDiff = count( $words1 ) - count( $words2 );
  foreach( $words1 as $word1 )
  {
    $minlevWord = "";
    $minlev = 1000;
    $return = 0;
    foreach( $words2 as $word2 )
    {
      $return = 1;
      if( in_array( $word2, $found ) )
        continue;
      $lev = levenshtein( $word1, $word2 );
      if( $lev < $minlev )
      {
        $minlev = $lev;
        $minlevWord = $word2;
      }
    }
    if( !$return )
      break;
    $score += $minlev;
    array_push( $found, $minlevWord );
  }

  return $score + $wordDiff;
}
</code>```

OwnerDisplayName: Discodancer

Title: Word comparison algorithm

Body:
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

   1,   John Doe,     ACME Comapny   (the typo is on purpose)

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

Body:
I'm implementing it in PHP, and I am now writing a piece of code that will break up 2 strings in words and compare each of the words from the first string with the words of the second string using levenshtein and accept the lowes possible values. Ill post it when I'm done.

Thanks a lot.

Update: Here's what I've come up with:

function myLevenshtein( $str1, $str2 )
{
  // prepare the words
  $words1 = explode( " ",  preg_replace( "/\s+/", " ", trim($str1) ) );
  $words2 = explode( " ",  preg_replace( "/\s+/", " ", trim($str2) ) );

  $found = array(); // array that keeps the best matched words so we don't check them again
  $score = 0;       // total score
  // In my case, strings that have different amount of words can be good matches too
  // For example, Acme Company and International Acme Company Ltd. are the same thing
  // I will just add the wordcount differencre to the total score, and weigh it more later if needed
  $wordDiff = count( $words1 ) - count( $words2 );
  foreach( $words1 as $word1 )
  {
    $minlevWord = "";
    $minlev = 1000;
    $return = 0;
    foreach( $words2 as $word2 )
    {
      $return = 1;
      if( in_array( $word2, $found ) )
        continue;
      $lev = levenshtein( $word1, $word2 );
      if( $lev < $minlev )
      {
        $minlev = $lev;
        $minlevWord = $word2;
      }
    }
    if( !$return )
      break;
    $score += $minlev;
    array_push( $found, $minlevWord );
  }

  return $score + $wordDiff;
}

LastEditorDisplayName: Discodancer


问:
What does '@' char mean before parameter name in method declaration?

Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

```<code>protected void Method1(Type1 @arg1, Type2 arg2)
...
</code>```

I use c# with .net 3.5.

Thanks.

答:
For your specific example, it has no meaning.  In C#, the @ symbol is used to escape keywords so that they can be used as variable names.

For instance, the following would generate a compiler error:

```<code>public void Test(string class){...}
</code>```

But if you escape with @, it is fine:

```<code>public void Test(string @class){...}
</code>```

Body:
Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

protected void Method1(Type1 @arg1, Type2 arg2)
...

I use c# with .net 3.5.

Thanks.

Body:
For your specific example, it has no meaning.  In C#, the @ symbol is used to escape keywords so that they can be used as variable names.

For instance, the following would generate a compiler error:

public void Test(string class){...}

But if you escape with @, it is fine:

public void Test(string @class){...}


问:
Can I omit interface methods which I do not use in Kotlin?
What if I am only interested in onSee and do not care for other events? Can I at least omit the methods that have no return values?

```<code>interface EventHandler
{
    fun onSee()
    fun onHear()
    fun onSmell()
    fun onTouch()
    fun onAwake()
    fun onSleep()
}

fun addEventHandler(handler:EventHandler)
{

}

fun Main()
{
    addEventHandler(object:EventHandler
    {
        override fun onSee()
        {
            print("I see.")
        }
    })
}
</code>```

答:
Sure, that is possible! you can implement one interface method when you extend it, all you have to do is to provide a default implementation for the other methods in the interface declaration

```<code>interface EventHandler {
    fun onSee()
    fun onHear() { /* default implementation */ }
    fun onSmell(){ /* default implementation */ }
    fun onTouch(){ /* default implementation */ }
    fun onAwake(){ /* default implementation */ }
    fun onSleep(){ /* default implementation */ }
}
</code>```

Now when you create an instance of this interface you only need to provide a compulsory implementation for onSee() method, rest are optional

If you're not the author of the original interface
You could extend the original interface and provide a default implementation for the methods you want

```<code>interface OnSeeEventHandler: EventHandler {
    override fun onHear() { /* default implementation */ }
    override fun onSmell(){ /* default implementation */ }
    override fun onTouch(){ /* default implementation */ }
    override fun onAwake(){ /* default implementation */ }
    override fun onSleep(){ /* default implementation */ }
}
</code>```

And use the OnSeeEventHandler to provide only onSee method imeplementation

Body:
What if I am only interested in onSee and do not care for other events? Can I at least omit the methods that have no return values?

interface EventHandler
{
    fun onSee()
    fun onHear()
    fun onSmell()
    fun onTouch()
    fun onAwake()
    fun onSleep()
}

fun addEventHandler(handler:EventHandler)
{

}

fun Main()
{
    addEventHandler(object:EventHandler
    {
        override fun onSee()
        {
            print("I see.")
        }
    })
}

Body:
Sure, that is possible! you can implement one interface method when you extend it, all you have to do is to provide a default implementation for the other methods in the interface declaration

interface EventHandler {
    fun onSee()
    fun onHear() { /* default implementation */ }
    fun onSmell(){ /* default implementation */ }
    fun onTouch(){ /* default implementation */ }
    fun onAwake(){ /* default implementation */ }
    fun onSleep(){ /* default implementation */ }
}

Now when you create an instance of this interface you only need to provide a compulsory implementation for onSee() method, rest are optional

If you're not the author of the original interface
You could extend the original interface and provide a default implementation for the methods you want

interface OnSeeEventHandler: EventHandler {
    override fun onHear() { /* default implementation */ }
    override fun onSmell(){ /* default implementation */ }
    override fun onTouch(){ /* default implementation */ }
    override fun onAwake(){ /* default implementation */ }
    override fun onSleep(){ /* default implementation */ }
}

And use the OnSeeEventHandler to provide only onSee method imeplementation


问:
Using primary keys as index for active record reads, Rails
When I use users=User.where(...)
I can use users.find(id) to find by it's id

I want to use a hash such so that I can use users[id] as a means of searching, where the id becomes the index of the hash.

How do I do this?

I have tried:

```<code>users.to_a.map(&:serializable_hash)
users.map(&:attributes)
users.map { |r| r.attributes.symbolize_keys }
</code>```

None of these worked in turning the primary key into the index

答:
To convert any Enumerable into a Hash, you can use index_by from ActiveSupport (activesupport/lib/active_support/core_ext/enumerable.rb)

```<code>users = User.where(...)
users.index_by(&:id)
# => { 1 => <User ...>, 2 => <User ...>, ...}

# note the difference between 'index_by' and 'group_by' where the latter will return an array of a single User for each id
users.group_by(&:id)
# => { 1 => [<User ...>], 2 => [<User ...>], ...}
</code>```

As ActiveRecord::Relation includes the Enumerable module in its ancestors chain (you can check by ActiveRecord::Relation.ancestors.include? Enumerable), you can use any Enumerable instance methods on any ActiveRecord::Relation object.

Body:
When I use users=User.where(...)
I can use users.find(id) to find by it's id

I want to use a hash such so that I can use users[id] as a means of searching, where the id becomes the index of the hash.

How do I do this?

I have tried:

users.to_a.map(&:serializable_hash)
users.map(&:attributes)
users.map { |r| r.attributes.symbolize_keys }

None of these worked in turning the primary key into the index

Body:
To convert any Enumerable into a Hash, you can use index_by from ActiveSupport (activesupport/lib/active_support/core_ext/enumerable.rb)

users = User.where(...)
users.index_by(&:id)
# => { 1 => <User ...>, 2 => <User ...>, ...}

# note the difference between 'index_by' and 'group_by' where the latter will return an array of a single User for each id
users.group_by(&:id)
# => { 1 => [<User ...>], 2 => [<User ...>], ...}

As ActiveRecord::Relation includes the Enumerable module in its ancestors chain (you can check by ActiveRecord::Relation.ancestors.include? Enumerable), you can use any Enumerable instance methods on any ActiveRecord::Relation object.