问:
How to configure the back stack when activity is launched by BroadcastReceiver?
I have an app with MainActivity.java which has a button that when clicked launches Main2Activity.java. Main2Activity.java is added to the project in Android Studio using New/Activity/Basic Activity. It has a back arrow at the top and touching it will return the app to MainActivity. AndroidManifest.xml has the following for Main2Activity:

```<code>android:parentActivityName=".MainActivity"
</code>```

The app also has a BroadcastReceiver which, after performing its work, launches Main2Activity.java.  When started this way (when the app is in the background), the back arrow in Main2Activity does not go back to MainActivity but instead exits the app.

I would like the back function of Main2Activity to always go to MainActivity.  According to Navigate up with a new back stack, there seems a way to do this, but the example is meant for an activity launched by another app.

How do I set the back destination for an activity launced by a BroadcastReceiver?

答:
There are two ways of doing this:

Providing the Up Navigation as mentioned in the link quoted by you in the question. It should work even when you're navigating to the Activity through a broadcast.

Use startActivities from the BroadcastReceiver to start both MainActivity and Main2Activity. This allows you to create a backstack when starting an Activity and it's parent is not on the stack.

I prefer approach 2 simply because it works even when you press the hardware back, not just the back button on the Action Bar. For achieving that with approach 1, you'd also have to override onBackPressed.

Body:
I have an app with MainActivity.java which has a button that when clicked launches Main2Activity.java. Main2Activity.java is added to the project in Android Studio using New/Activity/Basic Activity. It has a back arrow at the top and touching it will return the app to MainActivity. AndroidManifest.xml has the following for Main2Activity:

android:parentActivityName=".MainActivity"

The app also has a BroadcastReceiver which, after performing its work, launches Main2Activity.java.  When started this way (when the app is in the background), the back arrow in Main2Activity does not go back to MainActivity but instead exits the app.

I would like the back function of Main2Activity to always go to MainActivity.  According to Navigate up with a new back stack, there seems a way to do this, but the example is meant for an activity launched by another app.

How do I set the back destination for an activity launced by a BroadcastReceiver?


来源: stackexchange

问:
LISP function that takes 2 lists as parameters
After briefly talking about LISP in a past class, I have decided to jump in head first and try to learn CLISP (reading Seibel's PCL chpt 5). My question is in regards to writing a function that takes a set of lists as parameters. The first list is a series of indexes mapped to the second list. I want to pass a sequence of indexes and have it return the corresponding elements.

Here is the outline of my code so far. I wasn't sure if I could use nth and pass a list of arguments to it. I am not sure what the body-form should look like.

sys-info: CLISP 2.49 Win7

```<code>(defun get-elements('(nth (x y z) '(a b c)) )
  "takes a list of arguments that returns corresponding elements from a list."
  (format t "The elements at index ~d are: ~%" x y z)
  ((maybe indexes go here)'(elements go here?))
</code>```

The list (x y z) are the indexes and the data list (a b c) is some list of arbitrary elements. The evaluation is passed as data to the function get-elements. Am I even on the right track with this line of thinking?

Hints and pointers to relevant topics in LISP education are greatly appreciated.

postmortem:
Upon re-examination of chpts 3-4, it would seem that PCL is a bit of a reach for a beginning programmer (at least for me). I can enter the code from the book, but I obviously don't have a deep understanding of the basic structure of the language. I will probably try a few gentler introductions to Lisp before undertaking PCL again.

答:
I am not quite sure if this is what you are asking about, but you might want to try:

```<code>(defun get-nth (index-list data-list)
  (mapcar (lambda (index)
            (nth index data-list))
          index-list))
(get-nth '(0 1 0 2 0 3) '(a b c d e f))
==> (A B A C A D)
</code>```

Please take a look at

mapcar

nth

Formatted Output - your format call is broken

Lather, Rinse, Repeat: A Tour of the REPL - you claim to have read it, but you obviously posted your code before pasting it into a REPL, so please review it again.

More gentle introductions to Lisp:

ANSI Common Lisp by Graham

ContentLicense: CC BY-SA 3.0

Body:
After briefly talking about LISP in a past class, I have decided to jump in head first and try to learn CLISP (reading Seibel's PCL chpt 5). My question is in regards to writing a function that takes a set of lists as parameters. The first list is a series of indexes mapped to the second list. I want to pass a sequence of indexes and have it return the corresponding elements.

Here is the outline of my code so far. I wasn't sure if I could use nth and pass a list of arguments to it. I am not sure what the body-form should look like.

sys-info: CLISP 2.49 Win7

(defun get-elements('(nth (x y z) '(a b c)) )
  "takes a list of arguments that returns corresponding elements from a list."
  (format t "The elements at index ~d are: ~%" x y z)
  ((maybe indexes go here)'(elements go here?))

The list (x y z) are the indexes and the data list (a b c) is some list of arbitrary elements. The evaluation is passed as data to the function get-elements. Am I even on the right track with this line of thinking?

Hints and pointers to relevant topics in LISP education are greatly appreciated.

postmortem:
Upon re-examination of chpts 3-4, it would seem that PCL is a bit of a reach for a beginning programmer (at least for me). I can enter the code from the book, but I obviously don't have a deep understanding of the basic structure of the language. I will probably try a few gentler introductions to Lisp before undertaking PCL again.

Body:
I am not quite sure if this is what you are asking about, but you might want to try:

(defun get-nth (index-list data-list)
  (mapcar (lambda (index)
            (nth index data-list))
          index-list))
(get-nth '(0 1 0 2 0 3) '(a b c d e f))
==> (A B A C A D)

Please take a look at

mapcar

nth

Formatted Output - your format call is broken

Lather, Rinse, Repeat: A Tour of the REPL - you claim to have read it, but you obviously posted your code before pasting it into a REPL, so please review it again.

More gentle introductions to Lisp:

ANSI Common Lisp by Graham


问:
What is the difference between screen.blit(player, (xpos, ypos)) and display.flip() in pygame?
Both appear to update either the entire screen or just a section of the screen, but which does what and how?</p>

答:
blit() doesn't update screen - it draws image in buffer.

update() and flip() sends buffer to video card which displays it on monitor.

If you have code with blit() but without update() or flip() then it will display nothing.

flip() sends all buffer to video card. Probably it can use optimized method to do it fast.

update() can get list with Rect() and sends only some part of buffer so it could be faster. But you have to know which parts you what to replace. Sometimes it is hard to correctly choose which areas to update.

See doc: update(), flip()

ContentLicense: CC BY-SA 4.0


问:
How to use a servlet in annotations based struts2 project having no struts.xml
I am new to Struts and I have to add a functionality to a legacy system.

I have to create a servlet that's required to be accessed from a JSP page. I created one and added servlet-mapping in the web.xml file but it always shows an error like the following:

```<code>There is no Action mapped for namespace [/myServlet] and action name
   [test] associated with context path [/MyProject]
</code>```

I have searched for the solution but the one I got here is for the sturts.xml entry and I am not using the struts.xml, rather I am using the annotations.

Could someone please tell me how to use excludePattern in a annotations based Struts2 project?
NOTE: I tried adding the exclue-pattern in my web.xml like this:

```<code><init-param>
  <param-name>struts.action.excludePattern</param-name>
  <param-value>/FileUploadServlet</param-value>
</init-param>
</code>```

But it's still not working.

答:
Well, I have solved the problem by adding struts.xml to my project and adding only the constant there like this:

```<code><constant name="struts.action.excludePattern" value="/MyServlet"/>
</code>```

I was first wondering that I will have to provide all the mappings manually instead of the annotations but it worked without doing so.

Body:
I am new to Struts and I have to add a functionality to a legacy system.

I have to create a servlet that's required to be accessed from a JSP page. I created one and added servlet-mapping in the web.xml file but it always shows an error like the following:

There is no Action mapped for namespace [/myServlet] and action name
   [test] associated with context path [/MyProject]

I have searched for the solution but the one I got here is for the sturts.xml entry and I am not using the struts.xml, rather I am using the annotations.

Could someone please tell me how to use excludePattern in a annotations based Struts2 project?
NOTE: I tried adding the exclue-pattern in my web.xml like this:

<init-param>
  <param-name>struts.action.excludePattern</param-name>
  <param-value>/FileUploadServlet</param-value>
</init-param>

But it's still not working.

Body:
Well, I have solved the problem by adding struts.xml to my project and adding only the constant there like this:

<constant name="struts.action.excludePattern" value="/MyServlet"/>

I was first wondering that I will have to provide all the mappings manually instead of the annotations but it worked without doing so.


问:
Mocha Chai regex are equals
I am trying to test the behaviour of a method that produce regex.

Using Mocha/Chai test suite I have the following code :

```<code>describe('regexTest',function () {
  it('should return a regexp', function () {
    var regex = regexTest();
    assert.equal(regex, /someregex/);
  });
});
</code>```

But it seems that the code above doesn't work. I tried in the chrome console :

```<code>/a/ == /a/
> false
</code>```

For the moment the only way I found is to compare the toString of the two regex (that should be equals and that I can compare) :

```<code>describe('regexTest',function () {
  it('should return a regexp', function () {
    var regex = regexTest();
    assert.equal(regex.toString(), '/someregex/');
  });
});
</code>```

Do you know a better way to do this ? Because I find this not really clean ...

答:
It's a little late, but for anyone else who stumbles across this on Google way I did, Chai's normal comparison functions work with Regexp objects too...</p>

```<code>const re = new RegExp( '^foo.*bar$', 'i' );
re.should.eql( /^foo.*bar$/i );
</code>```

Title: Mocha Chai regex are equals

Body:
I am trying to test the behaviour of a method that produce regex.

Using Mocha/Chai test suite I have the following code :

describe('regexTest',function () {
  it('should return a regexp', function () {
    var regex = regexTest();
    assert.equal(regex, /someregex/);
  });
});

But it seems that the code above doesn't work. I tried in the chrome console :

/a/ == /a/
> false

For the moment the only way I found is to compare the toString of the two regex (that should be equals and that I can compare) :

describe('regexTest',function () {
  it('should return a regexp', function () {
    var regex = regexTest();
    assert.equal(regex.toString(), '/someregex/');
  });
});

Do you know a better way to do this ? Because I find this not really clean ...

Body:
It's a little late, but for anyone else who stumbles across this on Google way I did, Chai's normal comparison functions work with Regexp objects too...

const re = new RegExp( '^foo.*bar$', 'i' );
re.should.eql( /^foo.*bar$/i );


问:
Dispose JDialog in constructor
I have one condition where, the condition passes, I'll show a JDialog. If it fails, I just need to show a JOption pane and dispose the JDialog. EX. I have to show the dialog on a button click,

```<code>import javax.swing.JDialog;
import javax.swing.JLabel;

public class MyDialog extends JDialog {
public MyDialog(String name){
    JLabel welcomeLable = new JLabel("Hi welcome");
    add(welcomeLable);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setSize(100, 100);
    if(name.equals("pass")){
        //Do nothing
    }else{
        dispose();
    }
}

public static void main(String[] d){
    MyDialog dialog = new  MyDialog("fail");
    dialog.setModal(true);
    dialog.show();
}
}
</code>```

The message box is shown with validation message but still the dialog is being displayed. How to solve this.
How to solve this.

答:
First off: show() is now deprecated. Instead use pack() followed by setVisible(true).

As regards your problem: The issue is that the dialog can still be shown/set visible even if it has been disposed. This may not make sense from a logical standpoint, but that is how the implementation behaves. I would accomplish what you are trying to do by having the constructor set a flag that the main method will react to. Something like this:

```<code>import javax.swing.JDialog;
import javax.swing.JLabel;

public class MyDialog extends JDialog {

private boolean showMe;

public MyDialog(String name){
    JLabel welcomeLable = new JLabel("Hi welcome");
    add(welcomeLable);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setSize(100, 100);
    showMe = name.equals("pass");
}

public boolean getShowMe(){
    return showMe;
}

public static void main(String[] d){
    MyDialog dialog = new  MyDialog("fail");
    dialog.setModal(true);
    if (dialog.getShowMe()){
        dialog.pack();
        dialog.setVisible(true);
    }else{
        dialog.dispose();
    }
}
}
</code>```

Title: Dispose JDialog in constructor

Body:
I have one condition where, the condition passes, I'll show a JDialog. If it fails, I just need to show a JOption pane and dispose the JDialog. EX. I have to show the dialog on a button click,

import javax.swing.JDialog;
import javax.swing.JLabel;

public class MyDialog extends JDialog {
public MyDialog(String name){
    JLabel welcomeLable = new JLabel("Hi welcome");
    add(welcomeLable);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setSize(100, 100);
    if(name.equals("pass")){
        //Do nothing
    }else{
        dispose();
    }
}

public static void main(String[] d){
    MyDialog dialog = new  MyDialog("fail");
    dialog.setModal(true);
    dialog.show();
}
}

The message box is shown with validation message but still the dialog is being displayed. How to solve this.
How to solve this.

Body:
First off: show() is now deprecated. Instead use pack() followed by setVisible(true).

As regards your problem: The issue is that the dialog can still be shown/set visible even if it has been disposed. This may not make sense from a logical standpoint, but that is how the implementation behaves. I would accomplish what you are trying to do by having the constructor set a flag that the main method will react to. Something like this:

import javax.swing.JDialog;
import javax.swing.JLabel;

public class MyDialog extends JDialog {

private boolean showMe;

public MyDialog(String name){
    JLabel welcomeLable = new JLabel("Hi welcome");
    add(welcomeLable);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setSize(100, 100);
    showMe = name.equals("pass");
}

public boolean getShowMe(){
    return showMe;
}

public static void main(String[] d){
    MyDialog dialog = new  MyDialog("fail");
    dialog.setModal(true);
    if (dialog.getShowMe()){
        dialog.pack();
        dialog.setVisible(true);
    }else{
        dialog.dispose();
    }
}
}


问:
React not overwriting state
I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

```<code>{
    0: {name: foo},
    1: {name: bar}
}
</code>```

If I add another element, it works just fine:

```<code>store[2] = {name: hohoho};
setState(store, console.log(this.state));
</code>```

With the code above, I end up with the expected state:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}
</code>```

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

```<code>delete store[2]
</code>```

If I console.log(store), I get:

```<code>{
    0: {name: foo},
    1: {name: bar}
}
</code>```

then:

```<code>setState(store, console.log(this.state))
</code>```

gives me:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}
</code>```

But stranger than this, is if I add another element to the store, and set the state after:

```<code>store[3] = {name: heyheyhey};
setState(store, console.log(this.state));
</code>```

I end up with the following state:

```<code>{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}
</code>```

Even if console.log(store) gives me the following:

```<code>{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}
</code>```

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

```<code>var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;
</code>```

But I'm still experiencing the same problem.

答:
To answer the question like I mentioned in my comment. Delete doesn't free up memory like the key word makes you think it does.

According to MDN Delete

Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references

So all you have to do is replace it with a new object instead of modifying the old one.

Edit:

Try something like this

```<code>cloneObject(obj) {
        if (null == obj || "object" != typeof obj) return obj;
        var copy = obj.constructor();
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) {
                copy[attr] = obj[attr];
            }
        }
        return copy;
}
</code>```

Title: React not overwriting state

Body:
I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

{
    0: {name: foo},
    1: {name: bar}
}

If I add another element, it works just fine:

store[2] = {name: hohoho};
setState(store, console.log(this.state));

With the code above, I end up with the expected state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

delete store[2]

If I console.log(store), I get:

{
    0: {name: foo},
    1: {name: bar}
}

then:

setState(store, console.log(this.state))

gives me:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But stranger than this, is if I add another element to the store, and set the state after:

store[3] = {name: heyheyhey};
setState(store, console.log(this.state));

I end up with the following state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}

Even if console.log(store) gives me the following:

{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;

But I'm still experiencing the same problem.

Body:
To answer the question like I mentioned in my comment. Delete doesn't free up memory like the key word makes you think it does.

According to MDN Delete

Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references

So all you have to do is replace it with a new object instead of modifying the old one.

Edit:

Try something like this

cloneObject(obj) {
        if (null == obj || "object" != typeof obj) return obj;
        var copy = obj.constructor();
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) {
                copy[attr] = obj[attr];
            }
        }
        return copy;
}


问:
Where I put NotificationCenter.default.addObserver so that it can be called from any point of my framework?
I need add a NotificationCenter.default.addObserver in my framework project for logout. Previously I had this instruction in the appdelegate when the project was not a framework, but the frameworks don't have  this class. I tried to add this in a main uiviewcontroller, but sometimes this viewcontroller is destroyed and then the observer is removed.</p>

答: You can use a custom singleton and add the "observer" there. If you need information about singleton this article is good: what is a singleton swift</p>


问:
Swift 4 - How to enable / disable keyboard by using buttons
My tricky problem is :

I've 2 buttons with 2 UITextView.
Like you know, when I push an UITextView, keyboard appear. Well, this is not what I want.

I want to enable / disable the display's keyboard according a specific @IBAction taped.

The scenario is the following:
- First button (Keyboard icon) allow the user to display the keyboard to type something in one of the UITextView, with a FirstResponder init on the top one.

Second button (REC icon) allow the user to speak and display in pre-selected TextView but without displaying keyboard.

I already known that there is :

isUserInteractionEnabled

and

textViewDidBeginEditing

But it doesn't really fit well and/or fix my issue.

Here a screen to be more explicit (don't give a mind about the third green validate button, it's just for the .POST feature) :

Thanks for any help!

答:
If I understand your problem correctly, You don't want the keyboard to appear when user taps on the textField but rather should come up only when user taps on Keyboard button and should dismiss on tapping other button.

All the posted answers mostly focus only on second part of showing keyboard and dismissing them on tapping button. Whats more tricky is preventing keyboard from appearing in when user taps on textField :)

Possible solutions you can try and their cons:

Solution 1:

Try setting textfield isEnabled = false sure this will prevent keyboard from appearing when user taps on textField but guess what Keyboard will not appear even on calling textfield.becomeFirstResponder() ahhh trouble :)

Solution 2:

implementing textFieldShouldBeginEditing of UITextField delegate and returing true or false based on whether used tapped on button or textField itself.

Sure it works but you will need to figure out way to tell textFieldShouldBeginEditing why was it triggered because of button or because of touch on textField again complications.

My Solution:

Use 2 textFields. One disable user interaction forever and use another textField which will never appear to user but will take care of showing keyboard when required.

Enough talk lets code :)

Step 1:

Lets say your textField which appears on screen is called textField

```<code>textfield.isEnabled = false
</code>```

This will ensure whatever you do keyboard will not appear for this keyboard.

Step 2:

Create a temp textField of frame zero (which user can never tap :P )

```<code>    tempTextField = UITextField(frame: CGRect.zero)
    tempTextField.delegate = self
    self.view.addSubview(tempTextField)
</code>```

Step 3:

Now when user taps on show keyboard button, make your temp textField first responder

```<code>tempTextField.becomeFirstResponder()
</code>```

and when user taps on other button resignFirstResponder for tempTextField.

```<code>tempTextField.resignFirstResponder()
</code>```

Step 4:

But wait when user types nothing appears on my textField. Wait simply implement

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == tempTextField {
        self.textfield.text = (self.textfield.text ?? "") + string
    }
    return true
}
</code>```

EDIT:

You don't really need two textFields, you can achieve the same with a UILabel and UITextField as well. I chose UITextField as I am not sure what are other requirements of yours!

Problem fixed. Hope it helps :)

Body:
If I understand your problem correctly, You don't want the keyboard to appear when user taps on the textField but rather should come up only when user taps on Keyboard button and should dismiss on tapping other button.

All the posted answers mostly focus only on second part of showing keyboard and dismissing them on tapping button. Whats more tricky is preventing keyboard from appearing in when user taps on textField :)

Possible solutions you can try and their cons:

Solution 1:

Try setting textfield isEnabled = false sure this will prevent keyboard from appearing when user taps on textField but guess what Keyboard will not appear even on calling textfield.becomeFirstResponder() ahhh trouble :)

Solution 2:

implementing textFieldShouldBeginEditing of UITextField delegate and returing true or false based on whether used tapped on button or textField itself.

Sure it works but you will need to figure out way to tell textFieldShouldBeginEditing why was it triggered because of button or because of touch on textField again complications.

My Solution:

Use 2 textFields. One disable user interaction forever and use another textField which will never appear to user but will take care of showing keyboard when required.

Enough talk lets code :)

Step 1:

Lets say your textField which appears on screen is called textField

textfield.isEnabled = false

This will ensure whatever you do keyboard will not appear for this keyboard.

Step 2:

Create a temp textField of frame zero (which user can never tap :P )

    tempTextField = UITextField(frame: CGRect.zero)
    tempTextField.delegate = self
    self.view.addSubview(tempTextField)

Step 3:

Now when user taps on show keyboard button, make your temp textField first responder

tempTextField.becomeFirstResponder()

and when user taps on other button resignFirstResponder for tempTextField.

tempTextField.resignFirstResponder()

Step 4:

But wait when user types nothing appears on my textField. Wait simply implement

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == tempTextField {
        self.textfield.text = (self.textfield.text ?? "") + string
    }
    return true
}

EDIT:

You don't really need two textFields, you can achieve the same with a UILabel and UITextField as well. I chose UITextField as I am not sure what are other requirements of yours!

Problem fixed. Hope it helps :)


问:
Handle invalid arguments with argparse in Python
I am using argparse to parse command line arguments and by default on receiving invalid arguments it prints help message and exit. Is it possible to customize the behavior of argparse when it receives invalid arguments?

Generally I want to catch all invalid arguments and do stuff with them. I am looking for something like:

```<code>parser = argparse.ArgumentParser()
# add some arguments here
try:
    parser.parse_args()
except InvalidArgvsError, iae:
    print "handle this invalid argument '{arg}' my way!".format(arg=iae.get_arg())
</code>```

So that I can have:

```<code>>> python example.py --invalid some_text
handle this invalid argument 'invalid' my way!
</code>```

答:
Since the error code 2 is reserved for internal docker usage, I'm using the following to parse arguments in scripts inside docker containers:</p>

```<code>ERROR_CODE = 1
class DockerArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        """error(message: string)

    Prints a usage message incorporating the message to stderr and
    exits.

    If you override this in a subclass, it should not return -- it
    should either exit or raise an exception.

    Overrides error method of the parent class to exit with error code 1 since default value is
    reserved for internal docker usage
    """
    self.print_usage(sys.stderr)
    args = {'prog': self.prog, 'message': message}
    self.exit(ERROR_CODE, '%(prog)s: error: %(message)s\n' % args)
</code>```

Body:
I am using argparse to parse command line arguments and by default on receiving invalid arguments it prints help message and exit. Is it possible to customize the behavior of argparse when it receives invalid arguments?

Generally I want to catch all invalid arguments and do stuff with them. I am looking for something like:

parser = argparse.ArgumentParser()
# add some arguments here
try:
    parser.parse_args()
except InvalidArgvsError, iae:
    print "handle this invalid argument '{arg}' my way!".format(arg=iae.get_arg())

So that I can have:

>> python example.py --invalid some_text
handle this invalid argument 'invalid' my way!

Body:
Since the error code 2 is reserved for internal docker usage, I'm using the following to parse arguments in scripts inside docker containers:

ERROR_CODE = 1
class DockerArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        """error(message: string)

    Prints a usage message incorporating the message to stderr and
    exits.

    If you override this in a subclass, it should not return -- it
    should either exit or raise an exception.

    Overrides error method of the parent class to exit with error code 1 since default value is
    reserved for internal docker usage
    """
    self.print_usage(sys.stderr)
    args = {'prog': self.prog, 'message': message}
    self.exit(ERROR_CODE, '%(prog)s: error: %(message)s\n' % args)


问:
Add rows to DataGridView without freezing GUI
I want to display a table. Data for table must to be precalculated and it is heavy calculation. Also result table is long.
I want to provide acces to part of data while another part is calculated in the background.

I wrote background worker for calculation and DataGridView for display. Sometimes worker submit new rows via ProgressChangedEvent. I am tried to add this rows at bottom.
My problem starts when I tried add new rows at bottom. My UI is freezes.

Here is how I initialize DataGridView:

```<code>private void InitDataGridView()
{
    BindingList<TableRow> tableRows = new BindingList<TableRow>();
    dataGridView.DataSource = tableRows;
}
</code>```

and here is how I adding new rows at bottom in ProgressChangedEvent

```<code>private void UpdateDataGridView (List<Items> newItems)
{
    BindingList<TableRow> dataSource = (BindingList<TableRow>)this.dataGridView.DataSource;
    foreach (var item in newItems)
        dataSource.Add(new TableRow(item));
}
</code>```

I think that problem is because adding one row initiate redrawing of the table.
But I don't found AddRange for BindingList or mechanism to stop rendering temporary.

Any suggestions?

答:
By adding a new item to the list, BindingList raises a ListChanged which leads to updating DataGridView. To make updating of DataGridView more efficient, as an option you can stop raising ListChanged event of the BindingList. This way you can turn it off before adding items and then turn it on and raise the event just after adding a group of items to the list.

Here is an implementation which supports turning ListChanged event on/off:

```<code>public class MyBindingList<T>:BindingList<T>
{
    public bool EnableChangeNotifications { get; set; }
    protected override void OnListChanged(ListChangedEventArgs e)
    {
        if(EnableChangeNotifications)
            base.OnListChanged(e);
    }
}
</code>```

And for example, disable the event when adding items::

```<code>list.EnableChangeNotifications = false;
//Add new items to the list using a loop or something else.
</code>```

Then to showing changes in DataGridView, enable the event and raise it:

```<code>list.EnableChangeNotifications = true;
list.ResetBindings();
</code>```

Body:
I want to display a table. Data for table must to be precalculated and it is heavy calculation. Also result table is long.
I want to provide acces to part of data while another part is calculated in the background.

I wrote background worker for calculation and DataGridView for display. Sometimes worker submit new rows via ProgressChangedEvent. I am tried to add this rows at bottom.
My problem starts when I tried add new rows at bottom. My UI is freezes.

Here is how I initialize DataGridView:

private void InitDataGridView()
{
    BindingList<TableRow> tableRows = new BindingList<TableRow>();
    dataGridView.DataSource = tableRows;
}

and here is how I adding new rows at bottom in ProgressChangedEvent

private void UpdateDataGridView (List<Items> newItems)
{
    BindingList<TableRow> dataSource = (BindingList<TableRow>)this.dataGridView.DataSource;
    foreach (var item in newItems)
        dataSource.Add(new TableRow(item));
}

I think that problem is because adding one row initiate redrawing of the table.
But I don't found AddRange for BindingList or mechanism to stop rendering temporary.

Any suggestions?

Body:
By adding a new item to the list, BindingList raises a ListChanged which leads to updating DataGridView. To make updating of DataGridView more efficient, as an option you can stop raising ListChanged event of the BindingList. This way you can turn it off before adding items and then turn it on and raise the event just after adding a group of items to the list.

Here is an implementation which supports turning ListChanged event on/off:

public class MyBindingList<T>:BindingList<T>
{
    public bool EnableChangeNotifications { get; set; }
    protected override void OnListChanged(ListChangedEventArgs e)
    {
        if(EnableChangeNotifications)
            base.OnListChanged(e);
    }
}

And for example, disable the event when adding items::

list.EnableChangeNotifications = false;
//Add new items to the list using a loop or something else.

Then to showing changes in DataGridView, enable the event and raise it:

list.EnableChangeNotifications = true;
list.ResetBindings();


问:
Printing given array in a reverse order utilizing async-await
I'm learning the usage of async and await, and tried to do the following:

I have an array of numbers in a particular order, and an async method that gets a number and a time delay, and return the same passed-in number.

What I'd like to achieve is to print the numbers in a reveresed order (relative to the calling order), utilizing the time delay.

I'm having a hard time figuring out how to do it, and be glad for a guidance. Here's what I have (which, ofcourse, doesn't work):

```<code>public static async Task<int> DelayAndReturn(int number, int milisecDelay)
{
    await Task.Delay(milisecDelay);
    return number;
}

public static void Main(string[] args)
{
    int[] arr = { 1, 2, 3 };
    int milisecDelay = 10000;
    foreach (int num in arr)
    {
       Console.WriteLine(DelayAndReturn(num, milisecDelay));
       milisecDelay /= 10;
    }
    Console.ReadLine();
}
</code>```

答:
DelayAndReturn returns a Task object and the correct way to get the result of that object is to await the task. However, awaiting the task will also stop your foreach until 10000 ms have passed, and only then send the next item for processing.

Note that, although the code execution is waiting for the asynchronous operation to complete, the thread is free to be used by other processes.

Your best bet to get them printed in reversed order, is to create a collection of tasks and await all of them.

```<code>public static async Task DelayAndReturn(int number, int milisecDelay)
{
    await Task.Delay(milisecDelay);
    Console.WriteLine(number);
}

public static void Main(string[] args)
{
    PrintReversed().GetAwaiter().GetResult();
}

public static async Task PrintReversed() {
    int[] arr = { 1, 2, 3 };
    int milisecDelay = 1000;

    List<Task> tasks = new List<Task>();
    foreach (int num in arr)
    {
       tasks.Add(DelayAndReturn(num, milisecDelay));
       milisecDelay /= 10;
    }

    await Task.WhenAll(tasks);
}
</code>```

Body:
I'm learning the usage of async and await, and tried to do the following:

I have an array of numbers in a particular order, and an async method that gets a number and a time delay, and return the same passed-in number.

What I'd like to achieve is to print the numbers in a reveresed order (relative to the calling order), utilizing the time delay.

I'm having a hard time figuring out how to do it, and be glad for a guidance. Here's what I have (which, ofcourse, doesn't work):

public static async Task<int> DelayAndReturn(int number, int milisecDelay)
{
    await Task.Delay(milisecDelay);
    return number;
}

public static void Main(string[] args)
{
    int[] arr = { 1, 2, 3 };
    int milisecDelay = 10000;
    foreach (int num in arr)
    {
       Console.WriteLine(DelayAndReturn(num, milisecDelay));
       milisecDelay /= 10;
    }
    Console.ReadLine();
}

Body:
DelayAndReturn returns a Task object and the correct way to get the result of that object is to await the task. However, awaiting the task will also stop your foreach until 10000 ms have passed, and only then send the next item for processing.

Note that, although the code execution is waiting for the asynchronous operation to complete, the thread is free to be used by other processes.

Your best bet to get them printed in reversed order, is to create a collection of tasks and await all of them.

public static async Task DelayAndReturn(int number, int milisecDelay)
{
    await Task.Delay(milisecDelay);
    Console.WriteLine(number);
}

public static void Main(string[] args)
{
    PrintReversed().GetAwaiter().GetResult();
}

public static async Task PrintReversed() {
    int[] arr = { 1, 2, 3 };
    int milisecDelay = 1000;

    List<Task> tasks = new List<Task>();
    foreach (int num in arr)
    {
       tasks.Add(DelayAndReturn(num, milisecDelay));
       milisecDelay /= 10;
    }

    await Task.WhenAll(tasks);
}


问:
How to connect properly symfony 3.3.x doctrine2 and sql server 2005
I am working with symfony 3.3.10, php5.6.31 and I tried several times to connect doctrine to SQL Server 2005 database. I already installed the driver to use sqlsrv and pdo_sqlsrv. Here are my config files:

php.ini

```<code>extension=php_sqlsrv_56_ts.dll
extension=php_pdo_sqlsrv_56_ts.dll
</code>```

symfony config.yml

driver: pdo_sqlsrv
host: server_addr

port: 1433
dbname: dbname

user: db_user

password: db_p@ssw0rd

That is my config, now when I try to do something with doctrine it raises the following errors:

Using pdo_sqlsrv as driver

[Doctrine\DBAL\Driver\PDOException]

    SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]ODBC Driver 11 f

    or SQL Server does not support connections to SQL Server 2000 or earlier ve

    rsions.

[PDOException]

    SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]ODBC Driver 11 f

    or SQL Server does not support connections to SQL Server 2000 or earlier ve

    rsions.

Using sqlsrv as driver

[Doctrine\DBAL\Driver\SQLSrv\SQLSrvException]

    SQLSTATE [IMSSP, -33]: Invalid value type for option Database was specified

    .  String type was expected.

my phpinfo() has no problems and is detectig both php_sqlsrv and php_pdo_sqlsrv

Registered PHP Streams  php, file, glob, data, http, ftp, zip, compress.zlib, compress.bzip2, https, ftps, sqlsrv, phar

PDO drivers

```<code>mysql, odbc, pgsql, sqlite, sqlsrv
</code>```

Thanks in advance and sorry for bad English.

My SQL Server version output is:

Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)   Feb  9 2007 22:47:07   Copyright (c) 1988-2005 Microsoft Corporation  Enterprise Edition on Windows NT 6.0 (Build 6002: Service Pack 2)

答:
I have found this post which makes a reference to this link. Now I am using the lastest version (5.1.1). After check the extension is working I just configure multiples entity managers and I can connect to the database and execute/fetch queries.

php.ini

```<code>extension=php_pdo_sqlsrv_ts.dll
extension=php_sqlsrv_ts.dll
</code>```

Body:
I am working with symfony 3.3.10, php5.6.31 and I tried several times to connect doctrine to SQL Server 2005 database. I already installed the driver to use sqlsrv and pdo_sqlsrv. Here are my config files:

php.ini

extension=php_sqlsrv_56_ts.dll
extension=php_pdo_sqlsrv_56_ts.dll

symfony config.yml

driver: pdo_sqlsrv
host: server_addr

port: 1433
dbname: dbname

user: db_user

password: db_p@ssw0rd

That is my config, now when I try to do something with doctrine it raises the following errors:

Using pdo_sqlsrv as driver

[Doctrine\DBAL\Driver\PDOException]

    SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]ODBC Driver 11 f

    or SQL Server does not support connections to SQL Server 2000 or earlier ve

    rsions.

[PDOException]

    SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]ODBC Driver 11 f

    or SQL Server does not support connections to SQL Server 2000 or earlier ve

    rsions.

Using sqlsrv as driver

[Doctrine\DBAL\Driver\SQLSrv\SQLSrvException]

    SQLSTATE [IMSSP, -33]: Invalid value type for option Database was specified

    .  String type was expected.

my phpinfo() has no problems and is detectig both php_sqlsrv and php_pdo_sqlsrv

Registered PHP Streams  php, file, glob, data, http, ftp, zip, compress.zlib, compress.bzip2, https, ftps, sqlsrv, phar

PDO drivers

mysql, odbc, pgsql, sqlite, sqlsrv

Thanks in advance and sorry for bad English.

My SQL Server version output is:

Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)   Feb  9 2007 22:47:07   Copyright (c) 1988-2005 Microsoft Corporation  Enterprise Edition on Windows NT 6.0 (Build 6002: Service Pack 2)

Body:
I have found this post which makes a reference to this link. Now I am using the lastest version (5.1.1). After check the extension is working I just configure multiples entity managers and I can connect to the database and execute/fetch queries.

php.ini

extension=php_pdo_sqlsrv_ts.dll
extension=php_sqlsrv_ts.dll


答:
Or like this:</p>

```<code>WITH CTE AS
(
SELECT *, generate_series ( date_trunc('hour', validitybegin::timestamp)
        , date_trunc('hour', validityend::timestamp)
        , INTERVAL '1 hour') AS STRT,
          generate_series ( date_trunc('hour', validitybegin::timestamp)
        , date_trunc('hour', validityend::timestamp)
        , INTERVAL '1 hour') +  INTERVAL '1 hour' AS END
FROM my_data
),

CTE2 AS
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY CTE.ticketid ORDER BY CTE.STRT DESC) AS RN,
    COUNT(CTE.ticketid) OVER(PARTITION BY CTE.ticketid) AS CNT
FROM CTE
)

SELECT CTE2.STRT, CTE2.END,
CASE WHEN CTE2.CNT>2 THEN CASE
  WHEN CTE2.RN<>1 AND CTE2.RN<>CTE2.CNT THEN 60
  WHEN CTE2.RN<>1 AND CTE2.RN=CTE2.CNT THEN ROUND((EXTRACT('EPOCH' FROM CTE2.END-CTE2.VALIDITYBEGIN)/60)::decimal, 0)
  ELSE ROUND((EXTRACT('EPOCH' FROM CTE2.VALIDITYEND-CTE2.STRT)/60)::decimal, 0)
  END
ELSE CASE
  WHEN CTE2.RN<>1 THEN ROUND((EXTRACT('EPOCH' FROM CTE2.END-CTE2.VALIDITYBEGIN)/60)::decimal, 0)
  ELSE ROUND((EXTRACT('EPOCH' FROM CTE2.VALIDITYEND-CTE2.STRT)/60)::decimal, 0)
  END
END AS OVERLAP, CTE2.ticketid
FROM CTE2
ORDER BY CTE2.ticketid, CTE2.STRT;
</code>```

Title: SQL: Split time interval into intersects of one hour

Body:
I am new to SQL, where I am trying to split time intervals into multiple rows of one hour, together with an indicator of how many minutes the interval overlaps each hour.

My data:

    validitybegin    |     validityend     |     ticketid     |
---------------------+---------------------+------------------+
 2017-08-31 12:22:04 | 2017-08-31 13:08:56 |       ID1        |
 2017-08-31 13:09:02 | 2017-08-31 16:46:51 |       ID2        |
 2017-08-31 13:09:10 | 2017-08-31 14:09:10 |       ID3        |

What I would like:

       start         |        end          |   overlap   |     ticketid     |
---------------------+---------------------+-------------+------------------+
 2017-08-31 12:00:00 | 2017-08-31 13:00:00 |     38      |       ID1        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |      9      |       ID1        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |     51      |       ID2        |
 2017-08-31 14:00:00 | 2017-08-31 15:00:00 |     60      |       ID2        |
 2017-08-31 15:00:00 | 2017-08-31 16:00:00 |     60      |       ID2        |
 2017-08-31 16:00:00 | 2017-08-31 17:00:00 |     47      |       ID2        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |     51      |       ID3        |
 2017-08-31 14:00:00 | 2017-08-31 15:00:00 |      9      |       ID3        |

What would be the easiest/fastest way to do this?

Body:
Or like this:

WITH CTE AS
(
SELECT *, generate_series ( date_trunc('hour', validitybegin::timestamp)
        , date_trunc('hour', validityend::timestamp)
        , INTERVAL '1 hour') AS STRT,
          generate_series ( date_trunc('hour', validitybegin::timestamp)
        , date_trunc('hour', validityend::timestamp)
        , INTERVAL '1 hour') +  INTERVAL '1 hour' AS END
FROM my_data
),

CTE2 AS
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY CTE.ticketid ORDER BY CTE.STRT DESC) AS RN,
    COUNT(CTE.ticketid) OVER(PARTITION BY CTE.ticketid) AS CNT
FROM CTE
)

SELECT CTE2.STRT, CTE2.END,
CASE WHEN CTE2.CNT>2 THEN CASE
  WHEN CTE2.RN<>1 AND CTE2.RN<>CTE2.CNT THEN 60
  WHEN CTE2.RN<>1 AND CTE2.RN=CTE2.CNT THEN ROUND((EXTRACT('EPOCH' FROM CTE2.END-CTE2.VALIDITYBEGIN)/60)::decimal, 0)
  ELSE ROUND((EXTRACT('EPOCH' FROM CTE2.VALIDITYEND-CTE2.STRT)/60)::decimal, 0)
  END
ELSE CASE
  WHEN CTE2.RN<>1 THEN ROUND((EXTRACT('EPOCH' FROM CTE2.END-CTE2.VALIDITYBEGIN)/60)::decimal, 0)
  ELSE ROUND((EXTRACT('EPOCH' FROM CTE2.VALIDITYEND-CTE2.STRT)/60)::decimal, 0)
  END
END AS OVERLAP, CTE2.ticketid
FROM CTE2
ORDER BY CTE2.ticketid, CTE2.STRT;


问:
Generic Types and Object in Java
I just have learned that there is a problem with generic types in Java.
The problem occurs if I want to write a method that uses a generic class.
With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

```<code>public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}
</code>```

Main.java

```<code>public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}
</code>```

Error Message

```<code>Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
</code>```

答:
Just to contribute to Damian's answer.

Your method called printPartsOfTriplet should probably be replaced to stay inside the Triplet class and then you should use the same generic type T to print it.

the owner of the information should handle the processing in major cases.

Title: Generic Types and Object in Java

Body:
I just have learned that there is a problem with generic types in Java.
The problem occurs if I want to write a method that uses a generic class.
With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}

Error Message

Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error


问:
Select pairs with unique elements
I have a list of potential matches in this form:

```<code>rev_id, click_id
A,   1
A,   2
B,   1
B,   2
B,   3
C,   3
</code>```

How can select pairs with unique elements be so that values in both columns show up only once? The result would looks like:

```<code>rev_id, click_id
A,   1
B,   2
C,   3
</code>```

Is there a window function that would get me what I want?

```<code>select rev_id, ????
from matches
group by 1
</code>```

答:
so with your requirement in your comment that a you can only use a click_id once it becomes way more difficult.  But because you are using 3 rev_ids you can use 3 Cartesian joins and then narrow down to which options are allowed then choose 1 and format the way you want. Unfortunately this type of answer isn't very scalable.

```<code>;WITH cteOption AS (
    SELECT TOP 1 *
    FROM
       (
          SELECT DISTINCT
             CASE
                WHEN m1.rev_id < m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.rev_id
                WHEN m2.rev_id < m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.rev_id
                ELSE m3.rev_id
             END as rev1
             ,CASE
                WHEN m1.rev_id < m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.click_id
                WHEN m2.rev_id < m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.click_id
                ELSE m3.click_id
             END as click1
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.rev_id
                WHEN m1.rev_id > m3.rev_id AND m1.rev_id < m2.rev_id THEN m1.rev_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.rev_id
                WHEN m2.rev_id > m3.rev_id AND m2.rev_id < m1.rev_id THEN m2.rev_id
                ELSE m3.rev_id
             END as rev2
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.click_id
                WHEN m1.rev_id > m3.rev_id AND m1.rev_id < m2.rev_id THEN m1.click_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.click_id
                WHEN m2.rev_id > m3.rev_id AND m2.rev_id < m1.rev_id THEN m2.click_id
                ELSE m3.click_id
             END as click2
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id > m3.rev_id THEN m1.rev_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id > m3.rev_id THEN m2.rev_id
                ELSE m3.rev_id
             END as rev3
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id > m3.rev_id THEN m1.click_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id > m3.rev_id THEN m2.click_id
                ELSE m3.click_id
             END as click3
          FROM
             @matches m1
             CROSS JOIN @matches m2
             CROSS JOIN @matches m3
          WHERE
             m1.rev_id <> m2.rev_id
             AND m1.rev_id <> m3.rev_id
             AND m2.rev_id <> m3.rev_id
             AND m1.click_id <> m2.click_id
             AND m1.click_id <> m3.click_id
             AND m2.click_id <> m3.click_id
    ) t
)

SELECT
    rev1 as rev_id
    ,click1 as click_id
FROM
    cteOption
UNION ALL
SELECT
    rev2 as rev_id
    ,click2 as click_id
FROM
    cteOption
UNION ALL
SELECT
    rev3 as rev_id
    ,click3 as click_id
FROM
    cteOption
</code>```

I am sure there is a recursion way of doing it as well but I don't know if redshift supports that and don't have the time to chase down just yet.

OLD:

from your comments if you don't care which value but you just want to keep a value per rev_id you could just take the highest or lowest value.

```<code>SELECT rev_id, MIN(click_id) as click_id FROM matches GROUP BY rev_id
</code>```

OR

```<code>SELECT rev_id, MAX(click_id) as click_id FROM matches GROUP BY rev_id
</code>```

Title: Select pairs with unique elements

Body:
I have a list of potential matches in this form:

rev_id, click_id
A,   1
A,   2
B,   1
B,   2
B,   3
C,   3

How can select pairs with unique elements be so that values in both columns show up only once? The result would looks like:

rev_id, click_id
A,   1
B,   2
C,   3

Is there a window function that would get me what I want?

select rev_id, ????
from matches
group by 1

Body:
so with your requirement in your comment that a you can only use a click_id once it becomes way more difficult.  But because you are using 3 rev_ids you can use 3 Cartesian joins and then narrow down to which options are allowed then choose 1 and format the way you want. Unfortunately this type of answer isn't very scalable.

;WITH cteOption AS (
    SELECT TOP 1 *
    FROM
       (
          SELECT DISTINCT
             CASE
                WHEN m1.rev_id < m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.rev_id
                WHEN m2.rev_id < m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.rev_id
                ELSE m3.rev_id
             END as rev1
             ,CASE
                WHEN m1.rev_id < m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.click_id
                WHEN m2.rev_id < m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.click_id
                ELSE m3.click_id
             END as click1
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.rev_id
                WHEN m1.rev_id > m3.rev_id AND m1.rev_id < m2.rev_id THEN m1.rev_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.rev_id
                WHEN m2.rev_id > m3.rev_id AND m2.rev_id < m1.rev_id THEN m2.rev_id
                ELSE m3.rev_id
             END as rev2
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id < m3.rev_id THEN m1.click_id
                WHEN m1.rev_id > m3.rev_id AND m1.rev_id < m2.rev_id THEN m1.click_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id < m3.rev_id THEN m2.click_id
                WHEN m2.rev_id > m3.rev_id AND m2.rev_id < m1.rev_id THEN m2.click_id
                ELSE m3.click_id
             END as click2
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id > m3.rev_id THEN m1.rev_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id > m3.rev_id THEN m2.rev_id
                ELSE m3.rev_id
             END as rev3
             ,CASE
                WHEN m1.rev_id > m2.rev_id AND m1.rev_id > m3.rev_id THEN m1.click_id
                WHEN m2.rev_id > m1.rev_id AND m2.rev_id > m3.rev_id THEN m2.click_id
                ELSE m3.click_id
             END as click3
          FROM
             @matches m1
             CROSS JOIN @matches m2
             CROSS JOIN @matches m3
          WHERE
             m1.rev_id <> m2.rev_id
             AND m1.rev_id <> m3.rev_id
             AND m2.rev_id <> m3.rev_id
             AND m1.click_id <> m2.click_id
             AND m1.click_id <> m3.click_id
             AND m2.click_id <> m3.click_id
    ) t
)

SELECT
    rev1 as rev_id
    ,click1 as click_id
FROM
    cteOption
UNION ALL
SELECT
    rev2 as rev_id
    ,click2 as click_id
FROM
    cteOption
UNION ALL
SELECT
    rev3 as rev_id
    ,click3 as click_id
FROM
    cteOption

I am sure there is a recursion way of doing it as well but I don't know if redshift supports that and don't have the time to chase down just yet.

OLD:

from your comments if you don't care which value but you just want to keep a value per rev_id you could just take the highest or lowest value.

SELECT rev_id, MIN(click_id) as click_id FROM matches GROUP BY rev_id

OR

SELECT rev_id, MAX(click_id) as click_id FROM matches GROUP BY rev_id


问:
How to display PHP echo's in different div elements in an Ajax response
```<code>if ($_POST['username']==""){
 echo "enter your username"; //echo 1
}
if ($_POST['password']==""){
 echo "enter your password"; //echo 2
}

 <div class="username-error"> <!-- echo 1 has to be displayed here --></div>
    <div class="password-error"> <!-- echo 2 has to be displayed here --> </div>
</code>```

```<code>    $.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              contentType: false,
              processData: false,
              success: function(response){
                $('.username-error').html(response);
                $('.password-error').html(response);
              }
            });
</code>```

If I want to display this two echo's separately in two div elements in another page through ajax, how would i do it? below are the two div's that i want them to be displayed separately.

答:
So there are several ways to solve your problem. I will show you 2 possible solutions. Which one you choose is up to you.

First solution:

Change your PHP code to this:

```<code>if ($_POST['username']==""){
    $userErrMsg = "enter your username"; //echo 1
}
if ($_POST['password']==""){
    $passErrMsg = "enter your password"; //echo 2
}

echo $userErrMsg .'|'. $passErrMsg;

?>
</code>```

Next, change your jQuery ajax function to this:

```<code>$.ajax({
    url: $url,
    type: json,
    data :formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(response){
        var splitResponse = response.split('|');
        $('.username-error').html(splitResponse[0]);
        $('.password-error').html(splitResponse[1]);
    }
});
</code>```

In this solution you are returning both strings in a single string. In javascript, you are splitting that string up using the pipe character that was added in PHP. That way you have both strings available to you in javascript and you can add each to their own div element.

There are a few downsides to this solution. It assumes those error messages will be returned. If no error is returned, this solution will cause problems.

Second solution:

Change your PHP code to this:

```<code>$userErrMsg = '';
$passErrMsg = '';

if ($_POST['username']==""){
    $userErrMsg = "enter your username"; //echo 1
}
if ($_POST['password']==""){
    $passErrMsg = "enter your password"; //echo 2
}

echo json_encode(['userErrMsg' => $userErrMsg, 'passErrMsg' => $passErrMsg]);

?>
</code>```

Next, change your jQuery ajax function to this:

```<code>$.ajax({
    url: $url,
    type: $type,
    data :formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(response){
        $('.username-error').html(response.userErrMsg);
        $('.password-error').html(response.passErrMsg);
    }
});
</code>```

In this solution you are returning both strings encoded in JSON. In javascript, you can easily access the JSON string and get the information you need out of it. The advantage of this solution is that you don't have to use it. You can further enhance the JSON encoded string in PHP and return success messages just as well. So your Ajax function won't get into trouble if no errors are returned.

Last note:

Shayllis Alves de Sousa came up with this solution before I did. Therefor you should accept his answer and not mine. I simply provided you with my answer because it makes it easier for you to work with your code.

Body:
if ($_POST['username']==""){
 echo "enter your username"; //echo 1
}
if ($_POST['password']==""){
 echo "enter your password"; //echo 2
}

    $.ajax({
              url: $url,
              type: $type,
              data :formData,
              cache: false,
              contentType: false,
              processData: false,
              success: function(response){
                $('.username-error').html(response);
                $('.password-error').html(response);
              }
            });

If I want to display this two echo's separately in two div elements in another page through ajax, how would i do it? below are the two div's that i want them to be displayed separately.

Body:
So there are several ways to solve your problem. I will show you 2 possible solutions. Which one you choose is up to you.

First solution:

Change your PHP code to this:

if ($_POST['username']==""){
    $userErrMsg = "enter your username"; //echo 1
}
if ($_POST['password']==""){
    $passErrMsg = "enter your password"; //echo 2
}

echo $userErrMsg .'|'. $passErrMsg;

?>

Next, change your jQuery ajax function to this:

$.ajax({
    url: $url,
    type: json,
    data :formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(response){
        var splitResponse = response.split('|');
        $('.username-error').html(splitResponse[0]);
        $('.password-error').html(splitResponse[1]);
    }
});

In this solution you are returning both strings in a single string. In javascript, you are splitting that string up using the pipe character that was added in PHP. That way you have both strings available to you in javascript and you can add each to their own div element.

There are a few downsides to this solution. It assumes those error messages will be returned. If no error is returned, this solution will cause problems.

Second solution:

Change your PHP code to this:

$userErrMsg = '';
$passErrMsg = '';

if ($_POST['username']==""){
    $userErrMsg = "enter your username"; //echo 1
}
if ($_POST['password']==""){
    $passErrMsg = "enter your password"; //echo 2
}

echo json_encode(['userErrMsg' => $userErrMsg, 'passErrMsg' => $passErrMsg]);

?>

Next, change your jQuery ajax function to this:

$.ajax({
    url: $url,
    type: $type,
    data :formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(response){
        $('.username-error').html(response.userErrMsg);
        $('.password-error').html(response.passErrMsg);
    }
});

In this solution you are returning both strings encoded in JSON. In javascript, you can easily access the JSON string and get the information you need out of it. The advantage of this solution is that you don't have to use it. You can further enhance the JSON encoded string in PHP and return success messages just as well. So your Ajax function won't get into trouble if no errors are returned.

Last note:

Shayllis Alves de Sousa came up with this solution before I did. Therefor you should accept his answer and not mine. I simply provided you with my answer because it makes it easier for you to work with your code.


问:
Using Cycle2 Malsup php library to show images based on information from my MySQL database. Only image image is showing at a time
I am trying to build a book carousel that shows books that are available to check out at the library based on items in our catalogue.  I am querying a MySQL database to get items that match a specific query and using that with the Malsup Cycle2 php library.  My image will show up on the screen but I only see one image and it disappears and another zooms in.  I want to be able to see 5 books covers at a time and have one scroll of and another on.  Here is my code.

```<code>    $con = mysqli_connect("1.2.3.4","user","pass","database");
        if (mysqli_connect_errno())
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        mysqli_set_charset($con, "utf8");
        $sql = "SELECT DISTINCT bibs.record_id, "
        . "bibs.TITLE, bibs.AUTHOR, bibs.ISBNISSN, bibs.RECORDKEY, items.itemstatus, "
        . "items.bib_record_id, items.locationcode, items.branchcode "
        . "FROM bibs "
        . "INNER JOIN items ON bibs.record_id = items.bib_record_id "
        . "WHERE bibs.CATDATE >= '$last_thirty_days' "
        . "AND bibs.MATTYPE = 'a' "
        . "AND bibs.ISBNISSN != '' "
        . "AND items.locationcode LIKE '%af%' "
        . "AND items.branchcode = '1' "
        . "AND items.locationcode NOT LIKE '%wb%' "
        . "GROUP BY bibs.record_id "
        . "LIMIT 15";
        $result = mysqli_query($con,$sql);
      ?>
        <ul class="cycle-slideshow"
  data-cycle-carousel-visible="5"
  data-cycle-fx="scrollHorz"
  data-cycle-slides="li">
        <?php
            while ($bibs = mysqli_fetch_assoc($result)) {
            $bookcoverURL = createImageURL($bibs['ISBNISSN']);
        ?>
        <li>    <a href = "<?php echo $encoreURL; ?>">
            <img width=188px height=300px src="<?php echo $bookcoverURL;?>">
            </a></li>
        <?php }
            mysqli_free_result($result);
            mysqli_close($con);

        ?>
</ul>
</div>
    <br />

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script src="includes/jquery.cycle2.js"></script>
</body>
</code>```

答:
I've answered my own question.  It doesn't specify on the demo pages, but in order to get the carousel to work and to have the images transition properly you need to include one of the optional plugins that is available on this page http://jquery.malsup.com/cycle2/download/

After I downloaded and included that plugin the carousel is working as expected.

Body:
I am trying to build a book carousel that shows books that are available to check out at the library based on items in our catalogue.  I am querying a MySQL database to get items that match a specific query and using that with the Malsup Cycle2 php library.  My image will show up on the screen but I only see one image and it disappears and another zooms in.  I want to be able to see 5 books covers at a time and have one scroll of and another on.  Here is my code.

    $con = mysqli_connect("1.2.3.4","user","pass","database");
        if (mysqli_connect_errno())
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        mysqli_set_charset($con, "utf8");
        $sql = "SELECT DISTINCT bibs.record_id, "
        . "bibs.TITLE, bibs.AUTHOR, bibs.ISBNISSN, bibs.RECORDKEY, items.itemstatus, "
        . "items.bib_record_id, items.locationcode, items.branchcode "
        . "FROM bibs "
        . "INNER JOIN items ON bibs.record_id = items.bib_record_id "
        . "WHERE bibs.CATDATE >= '$last_thirty_days' "
        . "AND bibs.MATTYPE = 'a' "
        . "AND bibs.ISBNISSN != '' "
        . "AND items.locationcode LIKE '%af%' "
        . "AND items.branchcode = '1' "
        . "AND items.locationcode NOT LIKE '%wb%' "
        . "GROUP BY bibs.record_id "
        . "LIMIT 15";
        $result = mysqli_query($con,$sql);
      ?>

        <?php
            while ($bibs = mysqli_fetch_assoc($result)) {
            $bookcoverURL = createImageURL($bibs['ISBNISSN']);
        ?>

    <a href = "<?php echo $encoreURL; ?>">
            <img width=188px height=300px src="<?php echo $bookcoverURL;?>">

        <?php }
            mysqli_free_result($result);
            mysqli_close($con);

        ?>


问:
How can you have two dex files in a androidTest apk when minSdk is < 21?
why does assembleAndroidTest build successfully when over the 64k dex limit in the androidTest apk when using AGP 2.3.3? Is this a bug?

Some info:

Using multidex to create a test APK is not currently supported.

using android gradle plugin 2.3.3

minSdk is 16.

multidexEnabled true

72k method references in my androidTest apk, split across 2 dex files.

builds successfully

runtime crashes on pre-lollipop devices because a dex issue

I noticed this after trying to upgrade to AGP 3.0.

With AGP 3.0:

minSdk 16

multidexEnabled true

./gradlew assembleAndroidTest causes DexIndexOverflowException, failing the task

if I set minSdk 21, then :assembleAndroidTest succeeds. There are then 70k method references across 3 classes.dex files.

答:
Multidexing the test apk is actually supported (multidex 1.0.2 feature), but broken by a bug in 3.0 AGP.

Google's documentation is incorrect.


问:
Automatically log out php application after 2 mins
I have finished designing an application but would like to make the application logout out after 5 minutes of inactivity.

The first page is:

```<code><?php
session_start();
require_once("class.user.php");
$login = new USER();
if($login->is_loggedin()!="")
{
$login->redirect('user.php');
}
?>
</code>```

This is the user page:

```<code><?php
require_once("session.php");

require_once("class.user.php");
$auth_user = new USER();
$user_pin = $_SESSION['user_session']; ?>
</code>```

The session.php page

```<code><?php

session_start();
require_once 'class.user.php';
$session = new USER();
if(!$session->is_loggedin())
{
    $session->redirect('index.php');
}
?>
</code>```

This are the classes:

```<code>require_once('dbconfig.php');

class USER
{

private $conn;

public function __construct()
{
    $database = new Database();
    $db = $database->dbConnection();
    $this->conn = $db;
}

public function runQuery($sql)
{
    $stmt = $this->conn->prepare($sql);
    return $stmt;
}

public function is_loggedin()
{
    if(isset($_SESSION['user_session']) )
    {
        return true;
    }
}

public function redirect($url)
{
    header("Location: $url");
}

public function doLogout()
{
    session_destroy();
    unset($_SESSION['user_session']);

    return true;
}
}
?>
</code>```

答:
Theres multiple ways to achieve this:

You can make a verification with a cookie or a session with a Timestamp to verify if the user has not changed paged within 2 minutes and it will log him out the moment he access that page. The Con in this method is that for all intents and purposes the user is still considered "Online" until he changes page.

My preferred method is to make a pooling with JQuery and Ajax request.
Basically every X seconds you send a request with AJAX to the user to see if hes still there and update his timestamp on the database. And then with a server side script if the timestamp has reach 2 minutes difference set the user offline and force log him out.

There is always websockets, at the moment im exploring this method with rachetphp but it allows you to track a connection in real time, which is also pretty sweet.

Check this link for methods.

Body:
I have finished designing an application but would like to make the application logout out after 5 minutes of inactivity.

The first page is:

<?php
session_start();
require_once("class.user.php");
$login = new USER();
if($login->is_loggedin()!="")
{
$login->redirect('user.php');
}
?>

This is the user page:

<?php
require_once("session.php");

require_once("class.user.php");
$auth_user = new USER();
$user_pin = $_SESSION['user_session']; ?>

The session.php page

<?php

session_start();
require_once 'class.user.php';
$session = new USER();
if(!$session->is_loggedin())
{
    $session->redirect('index.php');
}
?>

This are the classes:

require_once('dbconfig.php');

class USER
{

private $conn;

public function __construct()
{
    $database = new Database();
    $db = $database->dbConnection();
    $this->conn = $db;
}

public function runQuery($sql)
{
    $stmt = $this->conn->prepare($sql);
    return $stmt;
}

public function is_loggedin()
{
    if(isset($_SESSION['user_session']) )
    {
        return true;
    }
}

public function redirect($url)
{
    header("Location: $url");
}

public function doLogout()
{
    session_destroy();
    unset($_SESSION['user_session']);

    return true;
}
}
?>


问:
Get informations from mouse
I'm doing my own FTP in C with ncurses. I know it's possible to get information like coord of click ... with the function getch(). My problem is for this school subject I can't use this function.

I would like to know if it's possible to get information like coord click, position, with button is used ... from the mouse in a terminal with read?

If it's possible with file descriptor I have to read?

Else with call system can do it?

I'm on sierra :)

Update

Yes I have a piece of code to get values

for example :

```<code>mouse click left down : 27, 91, 77, 32, 57, 67, 0, 0, 0
mouse click left up   : 27, 91, 77, 35, 57, 67, 0, 0, 0
</code>```

Like you can see I get 6 bytes for all events.

I understand byte[0] until byte[3] but I don't know what the byte 4 and 5 mean ... They look like random :(

Values are print in decimal

答:
My problem is for this school subject i can't use this function.

Then you're out of luck. curses provides this for a reason: it abstracts the many platform-dependent ways how to get mouse input. If you can't use what curses provides, you have to write code specifically for your target platform, which doesn't make any sense if you already use curses.

Title: Get informations from mouse

Body:
I'm doing my own FTP in C with ncurses. I know it's possible to get information like coord of click ... with the function getch(). My problem is for this school subject I can't use this function.

I would like to know if it's possible to get information like coord click, position, with button is used ... from the mouse in a terminal with read?

If it's possible with file descriptor I have to read?

Else with call system can do it?

I'm on sierra :)

Update

Yes I have a piece of code to get values

for example :

mouse click left down : 27, 91, 77, 32, 57, 67, 0, 0, 0
mouse click left up   : 27, 91, 77, 35, 57, 67, 0, 0, 0

Like you can see I get 6 bytes for all events.

I understand byte[0] until byte[3] but I don't know what the byte 4 and 5 mean ... They look like random :(

Values are print in decimal


问:
Can you reuse fragments of XML (in some kind of variables/references way)?
I am using SLD to style output from my geoserver. I have couple types of objects to be displayed. Each type have different icons, but text description is generated from the same information (text field in the database). I cannot use object_type as image name because you cannot use variable in image name (or I do not know how to do it...). So I Have SLD like (without unimportant parts):

```<code><StyledLayerDescriptor>
  <NamedLayer>
    <UserStyle>
      <FeatureTypeStyle>
        <Rule>
          <Filter>
            <PropertyIsEqualTo>
              <PropertyName>object_type</PropertyName>
              <Literal>1</Literal>
            </PropertyIsEqualTo>
          </Filter>
          <PointSymbolizer>
            <Graphic>
              <ExternalGraphic>
                <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="/images/1.png" />
                <Format>image/png</Format>
              </ExternalGraphic>
              <Size>16</Size>
              <Opacity>1</Opacity>
            </Graphic>
          </PointSymbolizer>
          <TextSymbolizer>
            <Label>
              <ogc:PropertyName>name</ogc:PropertyName>
            </Label>
            <Font>
              <CssParameter name="font-family">Times New Roman</CssParameter>
              <CssParameter name="font-style">Normal</CssParameter>
              <CssParameter name="font-size">12</CssParameter>
            </Font>
            <Fill>
              <CssParameter name="fill">#110011</CssParameter>
              <CssParameter name="fill-opacity">1</CssParameter>
            </Fill>
            <Halo />
          </TextSymbolizer>
        </Rule>

        <Rule>
          <Filter>
            <PropertyIsEqualTo>
              <PropertyName>object_type</PropertyName>
              <Literal>2</Literal>
            </PropertyIsEqualTo>
          </Filter>
          <PointSymbolizer>
            <Graphic>
              <ExternalGraphic>
                <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="/images/2.png" />
                <Format>image/png</Format>
              </ExternalGraphic>
              <Size>16</Size>
              <Opacity>1</Opacity>
            </Graphic>
          </PointSymbolizer>
          <TextSymbolizer>
            <Label>
              <ogc:PropertyName>name</ogc:PropertyName>
            </Label>
            <Font>
              <CssParameter name="font-family">Times New Roman</CssParameter>
              <CssParameter name="font-style">Normal</CssParameter>
              <CssParameter name="font-size">12</CssParameter>
            </Font>
            <Fill>
              <CssParameter name="fill">#110011</CssParameter>
              <CssParameter name="fill-opacity">1</CssParameter>
            </Fill>
            <Halo />
          </TextSymbolizer>
        </Rule>
      </FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>
</code>```

And the thing I'd love to do would be writing TextSymbolizer once and using it in two or more places... I have not heard of anything like that in XML, but maybe you have? :-)

One solution that comes to me, is to write some very simple generator (xml.erb? :P) and let it generate XML...

答: XML includes?  http://www.xml.com/pub/a/2002/07/31/xinclude.html</p>

OwnerDisplayName: rkj

ContentLicense: CC BY-SA 2.5

Body:
I am using SLD to style output from my geoserver. I have couple types of objects to be displayed. Each type have different icons, but text description is generated from the same information (text field in the database). I cannot use object_type as image name because you cannot use variable in image name (or I do not know how to do it...). So I Have SLD like (without unimportant parts):

And the thing I'd love to do would be writing TextSymbolizer once and using it in two or more places... I have not heard of anything like that in XML, but maybe you have? :-)

One solution that comes to me, is to write some very simple generator (xml.erb? :P) and let it generate XML...

OwnerDisplayName: Stephen Friederichs


问:
switch branches without checkout in GIT
Here are the steps that I have followed:

Created a repository

added a file to the master branch.

created a branch called test_branch.

added close to 30k files in the test_branch & committed.

now when I try to switch to master branch.
It says "checking out files:  83% (24967/30002)", and now I have all the files which I have committed in test_branch in my master branch as well.

Why I am getting this error, and how to overcome it ?

答: For such large volume of files in one branch, as opposed to the other, it might be better to clone the repository (which should reference by default the master branch), while leaving your first repo on the test_branch.

Title: switch branches without checkout in GIT


问:
Javascript Canvas edge detection
I would like to achieve this kind of image processing effect in Canvas :

WebGL image processing

What i need is an edge detection algorithm or explanation to draw only black pixels or border element ( such as a face for example ) of the image that an user can submit.

cheers

答:
Following your idea, the first step is the Edge detection. The example below shows hot to detect edges using MarvinJ. Having the edges, you might get the object contour.

Input Image:

Edge Detection:

var canvas = document.getElementById("canvas");

image = new MarvinImage();
image.load("https://i.imgur.com/ZHgkM9w.jpg", imageLoaded);

function imageLoaded(){
  var imageOut = new MarvinImage(image.getWidth(), image.getHeight());

  // Edge Detection (Prewitt approach)
  Marvin.prewitt(image, imageOut);
  // Invert color
  Marvin.invertColors(imageOut, imageOut);
  // Threshold
  Marvin.thresholding(imageOut, imageOut, 220);
  imageOut.draw(canvas);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas" width="500" height="344"></canvas></code>```

Title: Javascript Canvas edge detection

Body:
Following your idea, the first step is the Edge detection. The example below shows hot to detect edges using MarvinJ. Having the edges, you might get the object contour.

Input Image:

Edge Detection:

var canvas = document.getElementById("canvas");

image = new MarvinImage();
image.load("https://i.imgur.com/ZHgkM9w.jpg", imageLoaded);

function imageLoaded(){
  var imageOut = new MarvinImage(image.getWidth(), image.getHeight());

  // Edge Detection (Prewitt approach)
  Marvin.prewitt(image, imageOut);
  // Invert color
  Marvin.invertColors(imageOut, imageOut);
  // Threshold
  Marvin.thresholding(imageOut, imageOut, 220);
  imageOut.draw(canvas);
}

<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas" width="500" height="344"></canvas>


问:
adding numbers to string representations of numbers in python
I'm dealing with strings of the following form '000351'. Think of them as odometer readings. I want to increment them. For example
I want to add 1 to '000345' and get '000346'.

The following python code does the job, but appears rather cumbersome. Is there a more elegant way to do this?

```<code>s='000345'
t=int(s)
t=t+1
int_to_6digit_string(t)
</code>```

where the function int_to_6digit_string() is as follows

```<code>def int_to_6digit_string(i):
    if i<0 or i>999999:
        return 'argument out of bounds'
    j=str(i)
    if len(j) == 1:
        return '00000'+j
    elif len(j) == 2:
        return '0000'+j
    elif len(j) == 3:
        return '000'+j
    elif len(j) == 4:
        return '00'+j
    elif len(j) == 5:
        return '0'+j
    else:
        return j
</code>```

答: use string format: '{:06}'.format(your_number)

Body:
I'm dealing with strings of the following form '000351'. Think of them as odometer readings. I want to increment them. For example
I want to add 1 to '000345' and get '000346'.

The following python code does the job, but appears rather cumbersome. Is there a more elegant way to do this?

s='000345'
t=int(s)
t=t+1
int_to_6digit_string(t)

where the function int_to_6digit_string() is as follows

def int_to_6digit_string(i):
    if i<0 or i>999999:
        return 'argument out of bounds'
    j=str(i)
    if len(j) == 1:
        return '00000'+j
    elif len(j) == 2:
        return '0000'+j
    elif len(j) == 3:
        return '000'+j
    elif len(j) == 4:
        return '00'+j
    elif len(j) == 5:
        return '0'+j
    else:
        return j


问:
Angular router link in bootstrap navbar
Hi my link is not showing up as tab (using Bootstrap 4 and Angular 5). I only get a plain link. This got to very simple but this is first time with bootstrap...
Thanks a lot!</p>

```<code><div>
  <nav class="navbar navbar-inverse bg-primary">
    <div class="container">
      <ul class="nav navbar-nav" routerLinkActive="active">
        <li class="nav-item active">
          <a class="nav-link" [routerLink]="['/legalTerms']">Legal Terms</a>
        </li>
      </ul>
    </div>
  </nav>
</div>
<router-outlet></router-outlet>
</code>```

答:
Seems like some of your classes are for Bootstrap 3.

Here's the right way to do a tab nav:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

    Active

    Link

    Link

```

Title: Angular router link in bootstrap navbar

Body:
Hi my link is not showing up as tab (using Bootstrap 4 and Angular 5). I only get a plain link. This got to very simple but this is first time with bootstrap...
Thanks a lot!

          Legal Terms

<router-outlet></router-outlet>

Body:
Seems like some of your classes are for Bootstrap 3.

Here's the right way to do a tab nav:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<ul class="nav nav-tabs">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
</ul>


问:
Why is the VBA code not saving individual sheets?
The code below should save every sheet in my automated file. Why does it save the whole file again and again with sheets(i) simply highlighted?</p>

```<code> Sub Splitbook()
        MyPath = ThisWorkbook.Path
                For i = 1 To Worksheets.Count
                Sheets(i).Activate
                Sheets(i).SaveAs _
                        Filename:=MyPath & "\" & Sheets(i).Name & ".xlsx"
                        'ActiveWorkbook.Close savechanges:=False

        Next i
    End Sub
</code>```

答:
As @braX said -  Each sheet will be saved in a new workbook.

As @TimWilliams said - each sheet needs copying to a new workbook before saving.

ThisWorkbook is the file containing the VBA code.

When a worksheet is copied to a new file the new file becomes the active workbook so we can reference it that way (it would be great if we could write Set wrkBk = wrkSht.Copy, but VBA doesn't like that).

Once we have a reference to the new file we can save it using the sheet name - you may want to add code that ensures the sheet name is a viable file name.

```<code>Public Sub SplitWorkbook()

    Dim wrkSht As Worksheet
    Dim wrkBk As Workbook

    For Each wrkSht In ThisWorkbook.Worksheets
        wrkSht.Copy
        Set wrkBk = ActiveWorkbook
        'Save the new file without closing.
        'wrkBk.SaveAs ThisWorkbook.Path & "\" & wrkBk.Worksheets(1).Name

        'Save the new file and close.
        wrkBk.Close True, ThisWorkbook.Path & "\" & wrkBk.Worksheets(1).Name
    Next wrkSht

End Sub
</code>```

Body:
The code below should save every sheet in my automated file. Why does it save the whole file again and again with sheets(i) simply highlighted?

 Sub Splitbook()
        MyPath = ThisWorkbook.Path
                For i = 1 To Worksheets.Count
                Sheets(i).Activate
                Sheets(i).SaveAs _
                        Filename:=MyPath & "\" & Sheets(i).Name & ".xlsx"
                        'ActiveWorkbook.Close savechanges:=False

        Next i
    End Sub

Body:
As @braX said -  Each sheet will be saved in a new workbook.

As @TimWilliams said - each sheet needs copying to a new workbook before saving.

ThisWorkbook is the file containing the VBA code.

When a worksheet is copied to a new file the new file becomes the active workbook so we can reference it that way (it would be great if we could write Set wrkBk = wrkSht.Copy, but VBA doesn't like that).

Once we have a reference to the new file we can save it using the sheet name - you may want to add code that ensures the sheet name is a viable file name.

Public Sub SplitWorkbook()

    Dim wrkSht As Worksheet
    Dim wrkBk As Workbook

    For Each wrkSht In ThisWorkbook.Worksheets
        wrkSht.Copy
        Set wrkBk = ActiveWorkbook
        'Save the new file without closing.
        'wrkBk.SaveAs ThisWorkbook.Path & "\" & wrkBk.Worksheets(1).Name

        'Save the new file and close.
        wrkBk.Close True, ThisWorkbook.Path & "\" & wrkBk.Worksheets(1).Name
    Next wrkSht

End Sub


问:
Pandas style object members
I'm trying to figure out how Pandas manages to create new object members on the fly. For example, if you do this:

```<code>d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
</code>```

You can immediately do this:

```<code>df.col1
</code>```

and get the contents of col1. How does Pandas create the col1 member on the fly?

Thanks.

答:
Relevant code in the repository that checks for a dictionary input:

```<code>class DataFrame(NDFrame):
    def __init__(self, data=None, index=None, columns=None, dtype=None,
                 copy=False):
        if data is None:
            data = {}

        # Some other if-statements that check data types...

        elif isinstance(data, dict): mgr = self._init_dict(data, index, columns, dtype=dtype)
</code>```

Which uses_init_dict method:

```<code>def _init_dict(self, data, index, columns, dtype=None):

    if columns is not None:
       # Does some stuff - but this isn't your case

    else:
        keys = list(data.keys())
        if not isinstance(data, OrderedDict):
            # So this part is trying to sort keys to cols in alphabetical order
            # The _try_sort function is simple, exists in pandas.core.common
            keys = _try_sort(keys)
        columns = data_names = Index(keys)
</code>```

So the real work comes from the Index class in pandas.core.indexes.base. From there things start to get really complicated (and my understanding of what it means to explain the "how" of anything without continuing to regress until you get to machine code, started to melt away) but it's safe to say that if you give the pandas.Index class a 1-dimentional array of data it will create an object with a sliceable set and an associated data type.

Which is exactly what you're observing - you essentially fed it a bunch of keys and pandas understood that it needed to give you something back that you could access as an index (since df.col1 is just syntactic sugar for df['col1']), that you could slice (df[0:1]), and that knew its own data types.

Title: Pandas style object members

Body:
I'm trying to figure out how Pandas manages to create new object members on the fly. For example, if you do this:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

You can immediately do this:

df.col1

and get the contents of col1. How does Pandas create the col1 member on the fly?

Thanks.

Body:
Relevant code in the repository that checks for a dictionary input:

class DataFrame(NDFrame):
    def __init__(self, data=None, index=None, columns=None, dtype=None,
                 copy=False):
        if data is None:
            data = {}

        # Some other if-statements that check data types...

        elif isinstance(data, dict): mgr = self._init_dict(data, index, columns, dtype=dtype)

Which uses_init_dict method:

def _init_dict(self, data, index, columns, dtype=None):

    if columns is not None:
       # Does some stuff - but this isn't your case

    else:
        keys = list(data.keys())
        if not isinstance(data, OrderedDict):
            # So this part is trying to sort keys to cols in alphabetical order
            # The _try_sort function is simple, exists in pandas.core.common
            keys = _try_sort(keys)
        columns = data_names = Index(keys)

So the real work comes from the Index class in pandas.core.indexes.base. From there things start to get really complicated (and my understanding of what it means to explain the "how" of anything without continuing to regress until you get to machine code, started to melt away) but it's safe to say that if you give the pandas.Index class a 1-dimentional array of data it will create an object with a sliceable set and an associated data type.

Which is exactly what you're observing - you essentially fed it a bunch of keys and pandas understood that it needed to give you something back that you could access as an index (since df.col1 is just syntactic sugar for df['col1']), that you could slice (df[0:1]), and that knew its own data types.


问:
Split lines in clojure while reading from file
I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.

I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".

Here is my code so far

```<code>(defn readFile []
  (map (fn [line] (clojure.string/split line #";"))
  (with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
    (doseq [line (line-seq rdr)]
      (clojure.string/split line #";")
        (println line)))))
</code>```

When I do this, I still get the output:

```<code>"I;Am;A;String;"
</code>```

Am I missing something?

答:
TL;DR embrace the REPL and embrace immutability

Your question was "what am I missing?" and to that I'd say you're missing one of the best features of Clojure, the REPL.

Edit: you might also be missing that Clojure uses immutable data structures so

consider this code snippet:

```<code>(doseq [x [1 2 3]]
   (inc x)
   (prn x))
</code>```

This code does not print "2 3 4"

it prints "1 2 3" because x isn't a mutable variable.

During the first iteration  (inc x) gets called, returns 2, and that gets thrown away because it wasn't passed to anything, then (prn x) prints the value of x which is still 1.

Now consider this code snippet:

```<code>(doseq [x [1 2 3]] (prn (inc x)))
</code>```

During the first iteration the inc passes its return value to prn so you get 2

Long example:

I don't want to rob you of the opportunity to solve the problem yourself so I'll use a different problem as an example.

Given the file "birds.txt"
with the data "1chicken\n 2duck\n 3Larry"
you want to write a function that takes a file and returns a sequence of bird names

Lets break this problem down into smaller chunks:

first lets read the file and split it up into lines

(slurp "birds.txt") will give us the whole file a string

clojure.string/split-lines will give us a collection with each line as an element in the collection

(clojure.string/split-lines (slurp "birds.txt")) gets us ["1chicken" "2duck" "3Larry"]

At this point we could map some function over that collection to strip out the number like (map #(clojure.string/replace % #"\d" "") birds-collection)

or we could just move that step up the pipeline when the whole file is one string.

Now that we have all of our pieces we can put them together in a functional pipeline where the result of one piece feeds into the next

In Clojure there is a nice macro to make this more readable, the -> macro

It takes the result of one computation and injects it as the first argument to the next

so our pipeline looks like this:

```<code>(-> "C:/birds.txt"
     slurp
     (clojure.string/replace #"\d" "")
     clojure.string/split-lines)
</code>```

last note on style, for Clojure functions you want to stick to kebab case so readFile should be read-file

Body:
I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.

I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".

Here is my code so far

(defn readFile []
  (map (fn [line] (clojure.string/split line #";"))
  (with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
    (doseq [line (line-seq rdr)]
      (clojure.string/split line #";")
        (println line)))))

When I do this, I still get the output:

"I;Am;A;String;"

Am I missing something?

Body:
TL;DR embrace the REPL and embrace immutability

Your question was "what am I missing?" and to that I'd say you're missing one of the best features of Clojure, the REPL.

Edit: you might also be missing that Clojure uses immutable data structures so

consider this code snippet:

(doseq [x [1 2 3]]
   (inc x)
   (prn x))

This code does not print "2 3 4"

it prints "1 2 3" because x isn't a mutable variable.

During the first iteration  (inc x) gets called, returns 2, and that gets thrown away because it wasn't passed to anything, then (prn x) prints the value of x which is still 1.

Now consider this code snippet:

(doseq [x [1 2 3]] (prn (inc x)))

During the first iteration the inc passes its return value to prn so you get 2

Long example:

I don't want to rob you of the opportunity to solve the problem yourself so I'll use a different problem as an example.

Given the file "birds.txt"
with the data "1chicken\n 2duck\n 3Larry"
you want to write a function that takes a file and returns a sequence of bird names

Lets break this problem down into smaller chunks:

first lets read the file and split it up into lines

(slurp "birds.txt") will give us the whole file a string

clojure.string/split-lines will give us a collection with each line as an element in the collection

(clojure.string/split-lines (slurp "birds.txt")) gets us ["1chicken" "2duck" "3Larry"]

At this point we could map some function over that collection to strip out the number like (map #(clojure.string/replace % #"\d" "") birds-collection)

or we could just move that step up the pipeline when the whole file is one string.

Now that we have all of our pieces we can put them together in a functional pipeline where the result of one piece feeds into the next

In Clojure there is a nice macro to make this more readable, the -> macro

It takes the result of one computation and injects it as the first argument to the next

so our pipeline looks like this:

(-> "C:/birds.txt"
     slurp
     (clojure.string/replace #"\d" "")
     clojure.string/split-lines)

last note on style, for Clojure functions you want to stick to kebab case so readFile should be read-file