答:
i is the list element, not an index. It should be:

```<code>del candidates_and_fp_votes[i]
</code>```

or it should be:

```<code>for i in in range(len(losers)):
</code>```

if you really want the indexes for some reason.

Title: Delete a dictionary item based on a value from a list iteration

Body:
i is the list element, not an index. It should be:

del candidates_and_fp_votes[i]

or it should be:

for i in in range(len(losers)):

if you really want the indexes for some reason.


来源: stackexchange

问:
Draggable view within parent boundaries
I'm facing a task where I want to place a draggable marker on a background image and afterwards get the coordinates of the marker within the background image.

I've followed this neat tutorial to make a draggable marker using Animated.Image, PanResponder and Animated.ValueXY. The problem is that I cannot figure out how to limit the draggable view to only move around within the boundaries of its parent (the background image).

Any help is very much appreciated :)

Best regards

Jens

答:
Here is one way to do it using the react-native-gesture-responder.</p>

```<code>import React, { Component } from 'react'
import {
  StyleSheet,
  Animated,
  View,
} from 'react-native'
import { createResponder } from 'react-native-gesture-responder'

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
  },
  draggable: {
    height: 50,
    width: 50,
  },
})

export default class WorldMap extends Component {
  constructor(props) {
    super(props)

    this.state = {
      x: new Animated.Value(0),
      y: new Animated.Value(0),
    }
  }
  componentWillMount() {
    this.Responder = createResponder({
      onStartShouldSetResponder: () => true,
      onStartShouldSetResponderCapture: () => true,
      onMoveShouldSetResponder: () => true,
      onMoveShouldSetResponderCapture: () => true,
      onResponderMove: (evt, gestureState) => {
        this.pan(gestureState)
      },
      onPanResponderTerminationRequest: () => true,
    })
  }
  pan = (gestureState) => {
    const { x, y } = this.state
    const maxX = 250
    const minX = 0
    const maxY = 250
    const minY = 0

    const xDiff = gestureState.moveX - gestureState.previousMoveX
    const yDiff = gestureState.moveY - gestureState.previousMoveY
    let newX = x._value + xDiff
    let newY = y._value + yDiff

    if (newX < minX) {
      newX = minX
    } else if (newX > maxX) {
      newX = maxX
    }

    if (newY < minY) {
      newY = minY
    } else if (newY > maxY) {
      newY = maxY
    }

    x.setValue(newX)
    y.setValue(newY)
  }
  render() {
    const {
      x, y,
    } = this.state
    const imageStyle = { left: x, top: y }

    return (
      <View
        style={styles.container}
      >
        <Animated.Image
          source={require('./img.png')}
          {...this.Responder}
          resizeMode={'contain'}
          style={[styles.draggable, imageStyle]}
        />
    </View>

    )
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Draggable view within parent boundaries

Body:
Here is one way to do it using the react-native-gesture-responder.

import React, { Component } from 'react'
import {
  StyleSheet,
  Animated,
  View,
} from 'react-native'
import { createResponder } from 'react-native-gesture-responder'

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
  },
  draggable: {
    height: 50,
    width: 50,
  },
})

export default class WorldMap extends Component {
  constructor(props) {
    super(props)

    this.state = {
      x: new Animated.Value(0),
      y: new Animated.Value(0),
    }
  }
  componentWillMount() {
    this.Responder = createResponder({
      onStartShouldSetResponder: () => true,
      onStartShouldSetResponderCapture: () => true,
      onMoveShouldSetResponder: () => true,
      onMoveShouldSetResponderCapture: () => true,
      onResponderMove: (evt, gestureState) => {
        this.pan(gestureState)
      },
      onPanResponderTerminationRequest: () => true,
    })
  }
  pan = (gestureState) => {
    const { x, y } = this.state
    const maxX = 250
    const minX = 0
    const maxY = 250
    const minY = 0

    const xDiff = gestureState.moveX - gestureState.previousMoveX
    const yDiff = gestureState.moveY - gestureState.previousMoveY
    let newX = x._value + xDiff
    let newY = y._value + yDiff

    if (newX < minX) {
      newX = minX
    } else if (newX > maxX) {
      newX = maxX
    }

    if (newY < minY) {
      newY = minY
    } else if (newY > maxY) {
      newY = maxY
    }

    x.setValue(newX)
    y.setValue(newY)
  }
  render() {
    const {
      x, y,
    } = this.state
    const imageStyle = { left: x, top: y }

    return (
      <View
        style={styles.container}
      >
        <Animated.Image
          source={require('./img.png')}
          {...this.Responder}
          resizeMode={'contain'}
          style={[styles.draggable, imageStyle]}
        />
    </View>

    )
  }
}


问:
How can we import video or audio or images in Hadoop and can do further analysis.
I know how to import and analyse structured and semi-structured data in hadoop using Pig,hive,sqoop using Json loader and Json serde but how to import  unstructured data like  video or audio or images and how to do further analysis on it.Kindly explain in simple step by step way, if you have any use case of analysing unstructured data that will be of great help.Thank You! </p>

答:
Since Hadoop does not play well with small files, one approach could be to group the binary files into a small number of large files (to avoid dealing
with big amount of tiny files).

In order to do so, you could convert your binary files (images, audio, video, etc) in sequence files using custom UDFs that aggregates and store them into HDFS.

The following book, Pig Design Patterns, provides some design patterns regarding this topic (see chapter 2).

https://www.packtpub.com/mapt/book/big_data_and_business_intelligence/9781783285556

Some code snipets  are available on github.

https://github.com/pradeep-pasupuleti/pig-design-patterns/blob/master/Chapter2

Hope this help!


问:
How to understand where the crash is taking place from xcode
I'm new to xcode and I don't understand how I'm supposed to tell why the app is crashing from this report. When I click "Open in project" it takes me to a place in the code with little information to work on.
Picture of crash report

```<code>- (void)didTapOnJobTableView:(UIGestureRecognizer *)recognizer {
CGPoint tapLocation = [recognizer
locationInView:self.tableViewJobList];
 NSIndexPath *indexPath = [self.tableViewJobList
indexPathForRowAtPoint:tapLocation];
if (indexPath && indexPath.row >= 0 && indexPath.row <
[self.dispatchTable count]) {
SDMobileAppDelegate *appDelegate = [SDMobileAppDelegate me];
Dispatch *d = [self.dispatchTable objectAtIndex:indexPath.row];
<<<<Last exception backtrace here
if (d != nil && ![d isCancelled]) {
  JobListTableViewCell *cell = (JobListTableViewCell *)
[self.tableViewJobList cellForRowAtIndexPath:indexPath];
  CGPoint tapLocalzied = [recognizer locationInView:cell];
  if (CGRectContainsPoint([cell.labelPrts frame], tapLocalzied)) {
    if ([d.prtsPckQty integerValue] > 0) {
      dispatchForPartsPick = d;
      NSMutableString *partsPickText = [NSMutableString
stringWithString:@""];
      NSArray *list = [PartsPick getListFromDatabase:self.db
forDispatch:dispatchForPartsPick];
      for (PartsPick *p in list) {
        NSString *location = @"";
        if (![Utilities isEmpty:p.binLoc]) {
          location = [NSString stringWithFormat:@"[at %@]", p.binLoc];
        }
        [partsPickText appendFormat:@"%@ %@  %@  %@\r\n", p.qty,
location, [p.prtNmbr stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]], p.dscrptn];
        if (![Utilities isEmpty:p.notes]) {
          [partsPickText appendFormat:@"%@\r\n", p.notes];
        }
        [partsPickText appendString:@"\r\n"];
      }
      [ShowTextViewController show:self request:SEGUE_PARTSPICK_PREVIEW
header:[NSString stringWithFormat:lStr(@"PARTSPICK_PREVIEW"),
dispatchForPartsPick.invNmbr] message:@"" defaultText:partsPickText
editable:NO autoCap:UITextAutocapitalizationTypeNone delegate:nil];
    } else {
      [Utilities showOkAlertWithTitle:lStr(@"PTA")
andMessage:lStr(@"PARTSPICK_PREVIEW_NONE") onComplete:nil];
    }
  } else {
    if ([Utilities allowedToGoToJob: d]) {
      appDelegate.selectedDispatch = [NSNumber
numberWithLong:indexPath.row];
      self.tabBarController.selectedIndex = 1;
    } else {
      [Utilities showOkAlertWithTitle:@"Cannot Continue"
andMessage:@"Cannot select until previous PVR is completed."
onComplete:nil];
    }
  }
} else {
  [Utilities showOkAlertWithTitle:lStr(@"PTA")
andMessage:lStr(@"JOB_CANCELLED_CANNOT_SELECT") onComplete:nil];
  }
}
}
</code>```

Here is the code where this the above is used, specifically the gesture recognizer part:

```<code>- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
 [self refresh];
 XLog(@"Job List View will appear");

  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(didTapOnJobTableView:)];
[self.tableViewJobList addGestureRecognizer:tap];

// startup the ticker
self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:@selector(countdownTimer:) userInfo:nil
repeats:YES];

SDMobileAppDelegate *appDelegate = [SDMobileAppDelegate me];
NSTimeInterval diff = [[appDelegate.refreshTimer fireDate]
timeIntervalSinceNow];
if (diff > 60) {
self.buttonForceRefresh.enabled = YES;
self.buttonForceRefresh.titleLabel.enabled = YES;
}

[self setTimeCardStatus];
}
</code>```

答:
That has lots of information to work with; you just don't know what it means yet. Been there - it's frustrating at times...

See Ray Wenderlich's site and Apple's docs to get started debugging:

https://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1

https://www.raywenderlich.com/10505/my-app-crashed-now-what-part-2

"Unrecognized Selector" or "Does not respond to selector" means the object being called doesn't understand or can't find the method you're trying to call.

When that message is related to the user interface or interaction, it often means you forgot to hook up the IBOutlet or IBAction from the UI element to the code, or there's a typo in the names somewhere, or the method you're trying to call doesn't exist (or isn't publicly exposed) in the object being called.

Make sure you've hooked up your elements from interface builder to the code for the class, that the names are consistent, and that the method didTapOnJobTableViewactually exists in the class JobListViewController.

Body:
I'm new to xcode and I don't understand how I'm supposed to tell why the app is crashing from this report. When I click "Open in project" it takes me to a place in the code with little information to work on.
Picture of crash report

- (void)didTapOnJobTableView:(UIGestureRecognizer *)recognizer {
CGPoint tapLocation = [recognizer
locationInView:self.tableViewJobList];
 NSIndexPath *indexPath = [self.tableViewJobList
indexPathForRowAtPoint:tapLocation];
if (indexPath && indexPath.row >= 0 && indexPath.row <
[self.dispatchTable count]) {
SDMobileAppDelegate *appDelegate = [SDMobileAppDelegate me];
Dispatch *d = [self.dispatchTable objectAtIndex:indexPath.row];
<<<<Last exception backtrace here
if (d != nil && ![d isCancelled]) {
  JobListTableViewCell *cell = (JobListTableViewCell *)
[self.tableViewJobList cellForRowAtIndexPath:indexPath];
  CGPoint tapLocalzied = [recognizer locationInView:cell];
  if (CGRectContainsPoint([cell.labelPrts frame], tapLocalzied)) {
    if ([d.prtsPckQty integerValue] > 0) {
      dispatchForPartsPick = d;
      NSMutableString *partsPickText = [NSMutableString
stringWithString:@""];
      NSArray *list = [PartsPick getListFromDatabase:self.db
forDispatch:dispatchForPartsPick];
      for (PartsPick *p in list) {
        NSString *location = @"";
        if (![Utilities isEmpty:p.binLoc]) {
          location = [NSString stringWithFormat:@"[at %@]", p.binLoc];
        }
        [partsPickText appendFormat:@"%@ %@  %@  %@\r\n", p.qty,
location, [p.prtNmbr stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]], p.dscrptn];
        if (![Utilities isEmpty:p.notes]) {
          [partsPickText appendFormat:@"%@\r\n", p.notes];
        }
        [partsPickText appendString:@"\r\n"];
      }
      [ShowTextViewController show:self request:SEGUE_PARTSPICK_PREVIEW
header:[NSString stringWithFormat:lStr(@"PARTSPICK_PREVIEW"),
dispatchForPartsPick.invNmbr] message:@"" defaultText:partsPickText
editable:NO autoCap:UITextAutocapitalizationTypeNone delegate:nil];
    } else {
      [Utilities showOkAlertWithTitle:lStr(@"PTA")
andMessage:lStr(@"PARTSPICK_PREVIEW_NONE") onComplete:nil];
    }
  } else {
    if ([Utilities allowedToGoToJob: d]) {
      appDelegate.selectedDispatch = [NSNumber
numberWithLong:indexPath.row];
      self.tabBarController.selectedIndex = 1;
    } else {
      [Utilities showOkAlertWithTitle:@"Cannot Continue"
andMessage:@"Cannot select until previous PVR is completed."
onComplete:nil];
    }
  }
} else {
  [Utilities showOkAlertWithTitle:lStr(@"PTA")
andMessage:lStr(@"JOB_CANCELLED_CANNOT_SELECT") onComplete:nil];
  }
}
}

Here is the code where this the above is used, specifically the gesture recognizer part:

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
 [self refresh];
 XLog(@"Job List View will appear");

  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(didTapOnJobTableView:)];
[self.tableViewJobList addGestureRecognizer:tap];

// startup the ticker
self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:@selector(countdownTimer:) userInfo:nil
repeats:YES];

SDMobileAppDelegate *appDelegate = [SDMobileAppDelegate me];
NSTimeInterval diff = [[appDelegate.refreshTimer fireDate]
timeIntervalSinceNow];
if (diff > 60) {
self.buttonForceRefresh.enabled = YES;
self.buttonForceRefresh.titleLabel.enabled = YES;
}

[self setTimeCardStatus];
}


问:
npm does not support Node.js v9.0.0
I just upgraded my project to use Node.js v9.0.0. When I start my project using npm, it tells me I should upgrade to a newer Node version, but I believe this is the newest version. I also believe I'm on the newest version of npm (5.5.1).

Do I need to worry about this warning? Is there a good way to resolve the issue?

Here's the full warning:

```<code>npm WARN npm npm does not support Node.js v9.0.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
Now using node v9.0.0 (npm v5.5.1)
</code>```

答:
npm does not support Node.js v9.1.0

Uninstall did not work for me

```<code>npm uninstall -g npm
</code>```

Node.js v9.1.0 comes bundled with npm v5.5.1. The latest version of npm is also v5.5.1, however, the version bundled with Node.js isn't exactly the same as the original version from npm.

The following is what I needed to do on MacOS

```<code>To completely uninstall node + npm, do the following:
1. go to /usr/local/lib and delete any node and node_modules.
2. go to /usr/local/include and delete any node and node_modules directory.
3. download and install node from nodejs.org
</code>```

Title: npm does not support Node.js v9.0.0

Body:
I just upgraded my project to use Node.js v9.0.0. When I start my project using npm, it tells me I should upgrade to a newer Node version, but I believe this is the newest version. I also believe I'm on the newest version of npm (5.5.1).

Do I need to worry about this warning? Is there a good way to resolve the issue?

Here's the full warning:

npm WARN npm npm does not support Node.js v9.0.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
Now using node v9.0.0 (npm v5.5.1)

Body:
npm does not support Node.js v9.1.0

Uninstall did not work for me

npm uninstall -g npm

Node.js v9.1.0 comes bundled with npm v5.5.1. The latest version of npm is also v5.5.1, however, the version bundled with Node.js isn't exactly the same as the original version from npm.

The following is what I needed to do on MacOS

To completely uninstall node + npm, do the following:
1. go to /usr/local/lib and delete any node and node_modules.
2. go to /usr/local/include and delete any node and node_modules directory.
3. download and install node from nodejs.org


问:
split byte array into even and odd byte array and store in file
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

```<code>        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }
</code>```

In FOR loop i have tried array.length, even.length nothing is working.

答:
Your main array is twice as long as the resulting two. There might be 2 or 3 design errors in your code depending on what your data are

1rst flaw is that you use the same index for all the arrays at the same time. So you skip a memory cell on each pass of your for either for your even or your odd array and since your limit is the size of your even array, you only go halfway through your main array.

2nd flaw is that, depending of your data, you may need a different size for your even and odd array because if you have 46 odd numbers and 20 even numbers you still get your arrays size of 33 for each one

3rd flaw and probably most critical : combining the first and second flaw, you most certainly get an index out of bound exception. If you have 25 even number and 67 odd numbers, since you use the same index, your code will work until you get to index >= 25 where you will get an index out of bound, since even array has a last index of 32.

I would also suggest that you use lists instead of arrays since they are designed to store any number of data.

Here's how you could write your code to avoid those flaws :

```<code>byte[] array = File.ReadAllBytes("PST_Sample.pst");
List<byte> even = new List<byte>();
List<byte> odd = new List<byte>();

for (int index = 0; index < array.Length; index++)
{
    if ((array[index] % 2) == 0)
    {
        even.Add(array[index]);
    }
    else
    {
        odd.Add(array[index]);
    }
}

File.WriteAllBytes("even_file.pst", even.ToArray());
File.WriteAllBytes("odd_file.pst", odd.ToArray());
</code>```

Body:
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }

In FOR loop i have tried array.length, even.length nothing is working.

Body:
Your main array is twice as long as the resulting two. There might be 2 or 3 design errors in your code depending on what your data are

1rst flaw is that you use the same index for all the arrays at the same time. So you skip a memory cell on each pass of your for either for your even or your odd array and since your limit is the size of your even array, you only go halfway through your main array.

2nd flaw is that, depending of your data, you may need a different size for your even and odd array because if you have 46 odd numbers and 20 even numbers you still get your arrays size of 33 for each one

3rd flaw and probably most critical : combining the first and second flaw, you most certainly get an index out of bound exception. If you have 25 even number and 67 odd numbers, since you use the same index, your code will work until you get to index >= 25 where you will get an index out of bound, since even array has a last index of 32.

I would also suggest that you use lists instead of arrays since they are designed to store any number of data.

Here's how you could write your code to avoid those flaws :

byte[] array = File.ReadAllBytes("PST_Sample.pst");
List<byte> even = new List<byte>();
List<byte> odd = new List<byte>();

for (int index = 0; index < array.Length; index++)
{
    if ((array[index] % 2) == 0)
    {
        even.Add(array[index]);
    }
    else
    {
        odd.Add(array[index]);
    }
}

File.WriteAllBytes("even_file.pst", even.ToArray());
File.WriteAllBytes("odd_file.pst", odd.ToArray());

ContentLicense: CC BY-SA 4.0


问:
How to determine where a dependency is used? (Java, Maven)
When using Maven with Java, is it possible to see where a dependency is used? Specifically to know which classes in your project import a class from a given dependency?

This is especially difficult when the package naming of the class and the dependency declaration's tags do not line up.

For example, given a POM which contains a dependency:

```<code><dependency>
  <groupId>org.company.project</groupId>
  <artifactId>someartifact</artifactId>
  <version>1.0</version>
</dependency>
</code>```

find all classes that uses it (such as):

import org.company.similarprojectnamebutnotquitethesame.packagecontinued.SomeClass

TLDR: Is there an efficient way to locate all files in my project that use a given dependency?

答: Use a JAR search engine that matches the class name with a package, such as findjar.com or help4j.com</p>

Body:
When using Maven with Java, is it possible to see where a dependency is used? Specifically to know which classes in your project import a class from a given dependency?

This is especially difficult when the package naming of the class and the dependency declaration's tags do not line up.

For example, given a POM which contains a dependency:

<dependency>
  <groupId>org.company.project</groupId>
  <artifactId>someartifact</artifactId>
  <version>1.0</version>
</dependency>

find all classes that uses it (such as):

import org.company.similarprojectnamebutnotquitethesame.packagecontinued.SomeClass

TLDR: Is there an efficient way to locate all files in my project that use a given dependency?


问:
One ViewController calling delegated method of another ViewController
I have a fairly simple app with three viewControllers. You can see them below:

I want both controllers to segue back to the splash screen after a set amount of time, but only as long as a user isn't interacting with the app. To do this I have them both conform to UITextFieldDelegate protocol so I can use a few different delegate functions to understand when the user interacts with text fields. Both viewControllers incorporate the following UITextFieldDelegate Functions, and both have a variable segueTimer that I reset every time a user interacts with a text field:

I'll try to post only code that is relevant to the issue.

CheckInViewController

```<code>class CheckInViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var checkInView: CheckInView!

    var segueTimer: Timer?

    var fireTime = TimeInterval(20)

    var delegate: CheckInViewControllerDelegate!

    override func viewDidLoad(){

        super.viewDidLoad()

        checkInView.searchTextField.delegate = self

    }

    override func viewDidAppear(_ animated: Bool) {

        resetSegueTimer()
    }

    override func viewWillDisappear(_ animated: Bool) {

        deregisterFromKeyboardNotifications()
        //segueTimer?.invalidate()
        stopTimer()
    }

    func keyboardWillShow(sender: Notification){
        //print("keyboardWillShow()")

        ...

        resetSegueTime()
    }

    //This function fires everytime text changes
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        resetSegueTimer()

        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        resetSegueTimer()

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func resetSegueTimer(){

        stopTimer()
        startTimer()

    }

    func startTimer(){
        print("@CheckInVC  startTimer() \(segueTimer)")
        if segueTimer == nil{
            segueTimer = Timer.scheduledTimer(timeInterval: fireTime, target: self, selector: #selector(unwindToSplash), userInfo: nil, repeats: false)
         }
    }

    func stopTimer(){
        print("@CheckInVC  stopTimer() \(segueTimer)")
        if segueTimer != nil {
            segueTimer!.invalidate()
            segueTimer = nil
        }
    }

    func unwindToSplash(){
        self.performSegue(withIdentifier: "UnwindViewControllers", sender: self)
    }

}
</code>```

CheckInViewControllerDelegate

```<code>protocol CheckInViewControllerDelegate {
    var todaysGuests: NSMutableArray? { get set }
    var currentGuest: NSMutableDictionary? { get set }
    var guestRegisteredInKlik: Bool! { get set }
}
</code>```

RegisterViewController

```<code>class RegisterViewController: UIViewController, CheckInViewControllerDelegate, UITextFieldDelegate {

    var segueTimer: Timer?
    var fireTime = TimeInterval(20)

    var currentGuest: NSMutableDictionary?
    var todaysGuests: NSMutableArray?
    var guestRegisteredInKlik: Bool!

    @IBOutlet weak var registerView: RegisterVisitorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.registerView.companyTextField.delegate = self
        self.registerView.hostTextField.delegate = self
    {

    override func viewWillDisappear(_ animated: Bool) {

        registerView.nameLabel.text = ""
        registerView.companyTextField.text = ""
        registerView.hostTextField.text = ""

        stopTimer()
    }

    override func viewDidAppear(_ animated: Bool) {

        resetSegueTimer()

    }

    //delegate method to differntiate between multiple textfields that have the VC as their delegate
    func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if textFieldToChange == self.registerView.companyTextField {
            resetSegueTimer()

            return true

        } else if textFieldToChange == self.registerView.hostTextField {
            resetSegueTimer()

            return true
        }

        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        resetSegueTimer()

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        return true
    }

    func resetSegueTimer(){

        stopTimer()
        startTimer()

    }

    func startTimer(){
        print("@RegisterVC  startTimer() \(segueTimer)")
        if segueTimer == nil{
            segueTimer = Timer.scheduledTimer(timeInterval: fireTime, target: self, selector: #selector(unwindViewControllers), userInfo: nil, repeats: false)
        }
    }

    func stopTimer(){
        print("@RegisterVC  stopTimer() \(segueTimer)")
        if segueTimer != nil {
            segueTimer!.invalidate()
            segueTimer = nil
        }
    }

}
</code>```

The problem I am having involves the last two viewControllers, one of custom type CheckInViewController, and the other RegisterViewController. I have print statements in two delegated methods, textFielDidBeginEditing, one in each viewController. When I am in RegisterViewController and I switch to a different textfield, I see that the print statement of the textFieldDidBeginEditing function of the first viewController is called instead of the function of the viewController I am in.

The print statement just shows me the incorrect behavior. The actual problem is that the resetSegueTimer() function of the firstViewController is being called when I change textFields in the second viewController. Also, the textField(shouldChangeCharactersIn range: ) function called in the second viewController never invalidates the segueTimer in it's viewController, so the segue back to the splash isn't reset when a user edits the textfield.

I imagine this is an issue with me making two viewControllers conform to the same delegate protocol, while also making the second viewController the first viewController's delegate. But, I'm not sure how to fix this.

**Edit: Added keyBoardWillShow() function to CheckInViewController description, as it was contributing to the problem... that function was being called by RegisterViewController. Still not sure how, though.

答:
Fixed issue by removing resetSegueTimer() from keyboardWillShow() in first viewController. This had resetSegueTimer being called twice, once in keyboardWillShow and then again in EditingDidBegin, it was redundant. This function was also somehow being called by the second viewController when the keyboard would pop up... still not sure how that was possible.

I don't think this is the best fix for the application, and OverD gave a better solution. Will apply it eventually.

Body:
I have a fairly simple app with three viewControllers. You can see them below:

I want both controllers to segue back to the splash screen after a set amount of time, but only as long as a user isn't interacting with the app. To do this I have them both conform to UITextFieldDelegate protocol so I can use a few different delegate functions to understand when the user interacts with text fields. Both viewControllers incorporate the following UITextFieldDelegate Functions, and both have a variable segueTimer that I reset every time a user interacts with a text field:

I'll try to post only code that is relevant to the issue.

CheckInViewController

class CheckInViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var checkInView: CheckInView!

    var segueTimer: Timer?

    var fireTime = TimeInterval(20)

    var delegate: CheckInViewControllerDelegate!

    override func viewDidLoad(){

        super.viewDidLoad()

        checkInView.searchTextField.delegate = self

    }

    override func viewDidAppear(_ animated: Bool) {

        resetSegueTimer()
    }

    override func viewWillDisappear(_ animated: Bool) {

        deregisterFromKeyboardNotifications()
        //segueTimer?.invalidate()
        stopTimer()
    }

    func keyboardWillShow(sender: Notification){
        //print("keyboardWillShow()")

        ...

        resetSegueTime()
    }

    //This function fires everytime text changes
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        resetSegueTimer()

        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        resetSegueTimer()

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func resetSegueTimer(){

        stopTimer()
        startTimer()

    }

    func startTimer(){
        print("@CheckInVC  startTimer() \(segueTimer)")
        if segueTimer == nil{
            segueTimer = Timer.scheduledTimer(timeInterval: fireTime, target: self, selector: #selector(unwindToSplash), userInfo: nil, repeats: false)
         }
    }

    func stopTimer(){
        print("@CheckInVC  stopTimer() \(segueTimer)")
        if segueTimer != nil {
            segueTimer!.invalidate()
            segueTimer = nil
        }
    }

    func unwindToSplash(){
        self.performSegue(withIdentifier: "UnwindViewControllers", sender: self)
    }

}

CheckInViewControllerDelegate

protocol CheckInViewControllerDelegate {
    var todaysGuests: NSMutableArray? { get set }
    var currentGuest: NSMutableDictionary? { get set }
    var guestRegisteredInKlik: Bool! { get set }
}

RegisterViewController

class RegisterViewController: UIViewController, CheckInViewControllerDelegate, UITextFieldDelegate {

    var segueTimer: Timer?
    var fireTime = TimeInterval(20)

    var currentGuest: NSMutableDictionary?
    var todaysGuests: NSMutableArray?
    var guestRegisteredInKlik: Bool!

    @IBOutlet weak var registerView: RegisterVisitorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.registerView.companyTextField.delegate = self
        self.registerView.hostTextField.delegate = self
    {

    override func viewWillDisappear(_ animated: Bool) {

        registerView.nameLabel.text = ""
        registerView.companyTextField.text = ""
        registerView.hostTextField.text = ""

        stopTimer()
    }

    override func viewDidAppear(_ animated: Bool) {

        resetSegueTimer()

    }

    //delegate method to differntiate between multiple textfields that have the VC as their delegate
    func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if textFieldToChange == self.registerView.companyTextField {
            resetSegueTimer()

            return true

        } else if textFieldToChange == self.registerView.hostTextField {
            resetSegueTimer()

            return true
        }

        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        resetSegueTimer()

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        return true
    }

    func resetSegueTimer(){

        stopTimer()
        startTimer()

    }

    func startTimer(){
        print("@RegisterVC  startTimer() \(segueTimer)")
        if segueTimer == nil{
            segueTimer = Timer.scheduledTimer(timeInterval: fireTime, target: self, selector: #selector(unwindViewControllers), userInfo: nil, repeats: false)
        }
    }

    func stopTimer(){
        print("@RegisterVC  stopTimer() \(segueTimer)")
        if segueTimer != nil {
            segueTimer!.invalidate()
            segueTimer = nil
        }
    }

}

The problem I am having involves the last two viewControllers, one of custom type CheckInViewController, and the other RegisterViewController. I have print statements in two delegated methods, textFielDidBeginEditing, one in each viewController. When I am in RegisterViewController and I switch to a different textfield, I see that the print statement of the textFieldDidBeginEditing function of the first viewController is called instead of the function of the viewController I am in.

The print statement just shows me the incorrect behavior. The actual problem is that the resetSegueTimer() function of the firstViewController is being called when I change textFields in the second viewController. Also, the textField(shouldChangeCharactersIn range: ) function called in the second viewController never invalidates the segueTimer in it's viewController, so the segue back to the splash isn't reset when a user edits the textfield.

I imagine this is an issue with me making two viewControllers conform to the same delegate protocol, while also making the second viewController the first viewController's delegate. But, I'm not sure how to fix this.

**Edit: Added keyBoardWillShow() function to CheckInViewController description, as it was contributing to the problem... that function was being called by RegisterViewController. Still not sure how, though.


问:
python eval() to only accept conditions
I have text input in this form from a textbox:

gzip == True

gzip == False and count >= 100

gzip == True or msg == "Hello!"

I use eval() to get the result of the condition. However there are the obvious "security concerns" with eval like code injection.

Is there any way I can limit it to conditions? I dont need it for anything else.

答:
pyparsing is a great option. If you don't want to define a grammar and all that jazz though, another option you could try is this:

```<code>safe_variables = {} # use this to define safe functions and variables
code = "...."
eval(code, {"__builtins__": None}, safe_variables)
</code>```

By passing a dictionary with the builtins explicitly set None, you are ensuring that the code has NO access to the builtin functions of Python e.g. (abs, open, filter, etc...). If it's not explicitly set to None then the current globals will be copied.

That locks down the code alot. Next, explicitly list the variables and functions that you want the code to have access to in the safe_variables dictionary.

Title: python eval() to only accept conditions

Body:
pyparsing is a great option. If you don't want to define a grammar and all that jazz though, another option you could try is this:

safe_variables = {} # use this to define safe functions and variables
code = "...."
eval(code, {"__builtins__": None}, safe_variables)

By passing a dictionary with the builtins explicitly set None, you are ensuring that the code has NO access to the builtin functions of Python e.g. (abs, open, filter, etc...). If it's not explicitly set to None then the current globals will be copied.

That locks down the code alot. Next, explicitly list the variables and functions that you want the code to have access to in the safe_variables dictionary.


问:
ask the user for the maximum number to print out to and then print each multiple of the base number starting from the base to the maximum
```<code>System.out.print("Please enter the max number:");
int max = input.nextInt();

System.out.print("Please enter the base:");
int base = input.nextInt();

for (int i = 0; i <= max; max % base == 0;) {
    System.out.println("Number is " + i);
}
</code>```

How do I get it to print the multiples of a number?

答:
Although Diabolus already has a solution, here's the same using a for loop:

```<code>for(int i = base; i <= max; i++)
{
    if(i % base == 0)
        System.out.println("Number is - " + i);
}
</code>```

The number iterates from the base to the maximum number (if you start from zero, 0 too will be printed, as it divides completely by any number)

Note that even the base number will be printed. If you wish to avoid this, set i = base to i = base + 1.

Body:
System.out.print("Please enter the max number:");
int max = input.nextInt();

System.out.print("Please enter the base:");
int base = input.nextInt();

for (int i = 0; i <= max; max % base == 0;) {
    System.out.println("Number is " + i);
}

How do I get it to print the multiples of a number?

Body:
Although Diabolus already has a solution, here's the same using a for loop:

for(int i = base; i <= max; i++)
{
    if(i % base == 0)
        System.out.println("Number is - " + i);
}

The number iterates from the base to the maximum number (if you start from zero, 0 too will be printed, as it divides completely by any number)

Note that even the base number will be printed. If you wish to avoid this, set i = base to i = base + 1.


问:
openGL moving camera
I m trying to move my camera. I am using gluLookAt function. I have some variables for this.

```<code>float x,y,z ==> is camera location
float lx,ly,lz ==> is point that camera looks.
</code>```

I try to move on x axis

```<code>x= x+0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);
</code>```

it is work.

When i try to move on z axis as same as above

```<code>z = z +0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);
</code>```

nothing  change. Also when i invoke this function several times, first half of object dissapear (corners of object) and after next calling gluLookAt object dissapear completely.

I want the object looks bigger when camera move forward and smaller when camera move backward. But any changes is occured when i move camera on z axis.

What is the problem? Why object dissapear? How can i achieve that object get bigger when moving camera forward.

I know i can solve it by glTranslate or increasing size of object. But i want to use  gluLookAt.

Thanks you for answers.

答:
Your default projection matrix is probably an orthographic projection matrix, meaning that objects do not get bigger when they are near the camera.

The object finally disappears if the camera gets through it (crosses the zNear plane).

As Michael mentionned, you should install a perspective projection matrix, by using gluPerspective.

ContentLicense: CC BY-SA 2.5

Title: openGL moving camera

Body:
I m trying to move my camera. I am using gluLookAt function. I have some variables for this.

float x,y,z ==> is camera location
float lx,ly,lz ==> is point that camera looks.

I try to move on x axis

x= x+0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);

it is work.

When i try to move on z axis as same as above

z = z +0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);

nothing  change. Also when i invoke this function several times, first half of object dissapear (corners of object) and after next calling gluLookAt object dissapear completely.

I want the object looks bigger when camera move forward and smaller when camera move backward. But any changes is occured when i move camera on z axis.

What is the problem? Why object dissapear? How can i achieve that object get bigger when moving camera forward.

I know i can solve it by glTranslate or increasing size of object. But i want to use  gluLookAt.

Thanks you for answers.


问:
C++: How does a getter return a pointer to a dynamically allocated array without giving direct acces to it?
So the question is:

If I have a program something like:

```<code>class Ticket
{
 private:
    char* concertName;
 public:
    Ticket(char* name="Concert");
    char* getConcertName();
}
int main()
{
   char* test;
   Ticket t1;
   test=t1.getConcertName();
   test[1]='A';
}
Ticket::Ticket(char* name)
{
   this->concertName=new char[strlen(Concert)+1];
   strcpy(this->concertName,name);
}
Ticket::getConcertName()
{
  return this->concertName;
}
</code>```

What would the getter return? My intuition says that it returns the pointer to the first element of the memory block that I allocated earlier for concertName, and so I can change the array's values without using the setter, directly from main like I did in the example.

It works to change it, but the idea of the private area is for restricting the access from outside the object to it's attributes if a setter or a getter isn't used.

What if we had a static field like: static unsigned int* arrayI; and a static method that worked like a getter returning the value from arrayI?

答: You could allocate a new char* and then return that address so that if the user changes the thing they received then it doesn't change the private field in your class. </p>

Body:
So the question is:

If I have a program something like:

class Ticket
{
 private:
    char* concertName;
 public:
    Ticket(char* name="Concert");
    char* getConcertName();
}
int main()
{
   char* test;
   Ticket t1;
   test=t1.getConcertName();
   test[1]='A';
}
Ticket::Ticket(char* name)
{
   this->concertName=new char[strlen(Concert)+1];
   strcpy(this->concertName,name);
}
Ticket::getConcertName()
{
  return this->concertName;
}

What would the getter return? My intuition says that it returns the pointer to the first element of the memory block that I allocated earlier for concertName, and so I can change the array's values without using the setter, directly from main like I did in the example.

It works to change it, but the idea of the private area is for restricting the access from outside the object to it's attributes if a setter or a getter isn't used.

What if we had a static field like: static unsigned int* arrayI; and a static method that worked like a getter returning the value from arrayI?


问:
Cython Precompiler decision making
I am looking for a solution to add pre-compiler logic in a cython file.

I have written a cython wrapper for a hardware device API that is in C++. This is a cython project that is typically compiled using MSVC for python 2.7 and 3.6. The entire package is written in cython without need for an external c++ or header file.

Initially, I have written this software for use on a windows machine, so I have used a number of base winapi functions to help access a kernel event loop and winapi error messages. It works very well, but I would like to also add in functionality for cross-platform compilation. This requires me to completely replace several key functions to make it work on a linux machine. For example, the hardware API even has different event handling functions depending on the OS. Also, the winapi event handling would need to be replaced.

Right now, I compile the whole project together into a single module to simplify import. All code resides in the same pyx file that compiles into a hwmodule.pyd file. However, to accomplish the goal of cross-platform compilation, I need to patch the file together from several small pyx files at setup time. This solution is not elegant and difficult to maintain. Not to mention, this is more difficult to train others who may want to add to the project.

Ideally, I would be able to write cython to c compile time flags that get interpretted and compiled depending on flags or variables. Is there any solution  in cython that can accomplish my goal? Alternatively, is there a different organization that would be elegant and easy to maintain for this?

Some examples of plausible syntax (that may or may-not exist) that is similar to syntax found in c or python:

using an #ifdef or similar statement

```<code>#ifdef __WINAPI
def foo():
    print('bar win')
#else
def foo():
    print('bar linux')
#endif
</code>```

using a python-like with block

```<code>with ifdef('__WINAPI'):
    def foo():
        print('bar win')
</code>```

ending a function with a cython-like line-ending

```<code>def foo() ifdef('__WINAPI'):
    print('bar win')

def foo() ifndef('__WINAPI'):
    print('bar win')
</code>```

答:
A brief answer expanded from a comment: this is a feature that Cython supports. It allows you to define compile time constants

```<code>DEF a = 5
</code>```

and conditionally include code depending on those constants:

```<code>IF a==5:
    cdef f():
        return 1
ELSE:
    cdef f():
        return 2
</code>```

It also defines some helpful constants: UNAME_SYSNAME lets you pick between Windows, OS X and Linux for example.

These expressions are evaluated at the point Cython is run on your .pyx file - therefore the generated C code is different on Windows vs Linux, and so if you want to compile on another platform you'll need to re-run Cython, rather than just recompiling the C files.

There is no direct equivalent of C #ifdef/#ifndef in Cython - testing whether a compile time constant is defined is not a supported feature.

Title: Cython Precompiler decision making

Body:
I am looking for a solution to add pre-compiler logic in a cython file.

I have written a cython wrapper for a hardware device API that is in C++. This is a cython project that is typically compiled using MSVC for python 2.7 and 3.6. The entire package is written in cython without need for an external c++ or header file.

Initially, I have written this software for use on a windows machine, so I have used a number of base winapi functions to help access a kernel event loop and winapi error messages. It works very well, but I would like to also add in functionality for cross-platform compilation. This requires me to completely replace several key functions to make it work on a linux machine. For example, the hardware API even has different event handling functions depending on the OS. Also, the winapi event handling would need to be replaced.

Right now, I compile the whole project together into a single module to simplify import. All code resides in the same pyx file that compiles into a hwmodule.pyd file. However, to accomplish the goal of cross-platform compilation, I need to patch the file together from several small pyx files at setup time. This solution is not elegant and difficult to maintain. Not to mention, this is more difficult to train others who may want to add to the project.

Ideally, I would be able to write cython to c compile time flags that get interpretted and compiled depending on flags or variables. Is there any solution  in cython that can accomplish my goal? Alternatively, is there a different organization that would be elegant and easy to maintain for this?

Some examples of plausible syntax (that may or may-not exist) that is similar to syntax found in c or python:

using an #ifdef or similar statement

#ifdef __WINAPI
def foo():
    print('bar win')
#else
def foo():
    print('bar linux')
#endif

using a python-like with block

with ifdef('__WINAPI'):
    def foo():
        print('bar win')

ending a function with a cython-like line-ending

def foo() ifdef('__WINAPI'):
    print('bar win')

def foo() ifndef('__WINAPI'):
    print('bar win')

Body:
A brief answer expanded from a comment: this is a feature that Cython supports. It allows you to define compile time constants

DEF a = 5

and conditionally include code depending on those constants:

IF a==5:
    cdef f():
        return 1
ELSE:
    cdef f():
        return 2

It also defines some helpful constants: UNAME_SYSNAME lets you pick between Windows, OS X and Linux for example.

These expressions are evaluated at the point Cython is run on your .pyx file - therefore the generated C code is different on Windows vs Linux, and so if you want to compile on another platform you'll need to re-run Cython, rather than just recompiling the C files.

There is no direct equivalent of C #ifdef/#ifndef in Cython - testing whether a compile time constant is defined is not a supported feature.


问:
How can I display a more informative error message on mistyped ant targets?
When one of our developers mistypes an unrecognised ant target name the result is an unfriendly error message such as:

```<code>BUILD FAILED
Target "foo" does not exist in the project "bar".
</code>```

What I would prefer is that it instead run a target that displays the list of available targets. Is there a way to capture the ant error message and instead run another target, or some kind of custom error message?

Thanks.

答: ant -p will display a list of targets in your build.xml file. Is that good enough?

Body:
When one of our developers mistypes an unrecognised ant target name the result is an unfriendly error message such as:

BUILD FAILED
Target "foo" does not exist in the project "bar".

What I would prefer is that it instead run a target that displays the list of available targets. Is there a way to capture the ant error message and instead run another target, or some kind of custom error message?

Thanks.


问:
How do I select this check box using Selenium/Java
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

```<code><td class="normal">
    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer
</td>
</code>```

答:
It depends how the whole html looks lets say

Now you first need to get the Number of inputs tag inside td tag for that use

```<code>     <td class="normal">

     <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer
     Flow Designer/>
     <input name="anything new" type="checkbox" value="0">Another text/>
     <input name="anything new" type="checkbox" value="0">Another text/>
     <input name="anything new" type="checkbox" value="0">Another text/>
     .
     .
     and last 50th
     <input name="anything new" type="checkbox" value="0">Another text/>
     </td>
</code>```

iterate them like below and get the text as well from each elements

```<code>        List<WebElments> tdtagselements=driver.findElement(By.xpath("//td[1]//input"));

      for(int i=1;i<tdtagselements.size();i++){
      String textInputtag=driver.findelement(by.xpath("//td[1]//input["+i+"]")).gettext();
}
</code>```

use this string to compare with the text you want to verify your text
let me know how exactly your html code looks like

Body:
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer

Body:
It depends how the whole html looks lets say

Now you first need to get the Number of inputs tag inside td tag for that use

     <td class="normal">

     <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer
     Flow Designer/>
     <input name="anything new" type="checkbox" value="0">Another text/>
     <input name="anything new" type="checkbox" value="0">Another text/>
     <input name="anything new" type="checkbox" value="0">Another text/>
     .
     .
     and last 50th
     <input name="anything new" type="checkbox" value="0">Another text/>
     </td>

iterate them like below and get the text as well from each elements

        List<WebElments> tdtagselements=driver.findElement(By.xpath("//td[1]//input"));

      for(int i=1;i<tdtagselements.size();i++){
      String textInputtag=driver.findelement(by.xpath("//td[1]//input["+i+"]")).gettext();
}

use this string to compare with the text you want to verify your text
let me know how exactly your html code looks like


问:
Repeating a function in a background thread every N seconds
I know this sounds a lot like this similarly-worded question, but there are differences, so bear with me.

I'm trying to create a reusable "Timer" class which calls a specified callback every N seconds, until you call stop. As inspiration, I used the link above, with a built-in event wrapped in a stop method. Here's how the basic class looks:

```<code>import time
import threading
from threading import Thread
from threading import Event

# Mostly inspired by https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds
class RepeatingTimer(Thread):
    def __init__(self, interval_seconds, callback):
        Thread.__init__(self)
        self.stop_event = Event()
        self.interval_seconds = interval_seconds
        self.callback = callback
        self.setDaemon(True)

    def start(self):
        while not self.stop_event.wait(self.interval_seconds):
            self.callback()
            time.sleep(0) # doesn't seem to do anything

    def stop(self):
        self.stop_event.set()
</code>```

Looks good, even includes time.sleep(0) based on this question.

It doesn't do what I thought; the call to start never seems to return or yield, ever. Consider this use-case:

```<code>def print_status(message):
  print(message)

def print_r1():
  print_status("R1")

def print_r2():
  print_status("R2")

r1 = RepeatingTimer(1, print_r1)
r2 = RepeatingTimer(0.5, print_r2)

r1.start()
r2.start()
</code>```

The call to r1.start never terminates. It continues on forever. The output on the console, after four seconds, is:

R1

R1

R1

R1

This prompted me to introduce the time.sleep(0) call, although that doesn't seem to do anything.

I also tried with and without self.setDaemon(True), but that also seems to have no effect.

I also tried converting this into two classes: one with just the event wrappers (a StoppableTimer class), and another that simply creates and recreates the StoppableTimer in the callback, but that doesn't work either.  Here's what it looks like:

```<code>class StoppableTimer(Thread):
    def __init__(self, interval_seconds, callback):
        Thread.__init__(self)
        self.stop_event = Event()
        self.interval_seconds = interval_seconds
        self.callback = callback
        self.setDaemon(True)

    def start(self):
        time.sleep(self.interval_seconds)
        self.callback()

    def stop(self):
        self.stop_event.set()

class RepeatingTimer:
    def __init__(self, interval_seconds, callback):
        self.interval_seconds = interval_seconds
        self.callback = callback
        self.timer = StoppableTimer(interval_seconds, self.refresh_timer)

    def start(self):
        self.timer.start()

    def stop(self):
        self.timer.stop()

    def refresh_timer(self):
        self.stop()
        self.callback()
        self.timer = StoppableTimer(self.interval_seconds, self.refresh_timer)
        self.timer.start()
</code>```

I'm completely at a loss on how to make this work. I'm also mostly a beginner to Python, so please add sufficient explanation to your answer so I can grasp what the fundamental issue is.

I also read a bit about the Global Interpreter Lock on SO, but I don't understand how that could be an issue.

For reference, I'm running Python 3.6.3 on Ubuntu 17.10

答:
Short answer :

Don't override start(). Override run() instead.

Long answer because you're asking for details :

With the class definition in your first snippet, you've created a class which inherits from Thread, however you've overriden the start() method supposed to start your thread by a new method which is looping until the stop_event is set, that is to say, the method supposed to actually start your thread doesn't do this anymore.

So, when you try to start your thread, you actually run the loop calling your callback function in your current and only thread. And since it's an infinite loop, your second "thread" is not started, and you have no way to "stop" it.

You mustn't override start (well not in this way). Instead, override the run method. This is the method that will be run by your thread when you start it.

Also, you should do super().__init__() instead of Thread.__init__(self). The first one is the proper way to call an inherited method in Python.

```<code>class RepeatingTimer(Thread):
    def __init__(self, interval_seconds, callback):
        super().__init__()
        self.stop_event = Event()
        self.interval_seconds = interval_seconds
        self.callback = callback

    def run(self):
        while not self.stop_event.wait(self.interval_seconds):
            self.callback()

    def stop(self):
        self.stop_event.set()
</code>```

And with the functions you've defined you can do :

```<code>r1 = RepeatingTimer(1, print_r1)
r2 = RepeatingTimer(0.5, print_r2)

r1.start()
r2.start()
time.sleep(4)
r1.stop()
r2.stop()
</code>```

Here is the relevant documentation for Thread.

Body:
I know this sounds a lot like this similarly-worded question, but there are differences, so bear with me.

I'm trying to create a reusable "Timer" class which calls a specified callback every N seconds, until you call stop. As inspiration, I used the link above, with a built-in event wrapped in a stop method. Here's how the basic class looks:

import time
import threading
from threading import Thread
from threading import Event

# Mostly inspired by https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds
class RepeatingTimer(Thread):
    def __init__(self, interval_seconds, callback):
        Thread.__init__(self)
        self.stop_event = Event()
        self.interval_seconds = interval_seconds
        self.callback = callback
        self.setDaemon(True)

    def start(self):
        while not self.stop_event.wait(self.interval_seconds):
            self.callback()
            time.sleep(0) # doesn't seem to do anything

    def stop(self):
        self.stop_event.set()

Looks good, even includes time.sleep(0) based on this question.

It doesn't do what I thought; the call to start never seems to return or yield, ever. Consider this use-case:

def print_status(message):
  print(message)

def print_r1():
  print_status("R1")

def print_r2():
  print_status("R2")

r1 = RepeatingTimer(1, print_r1)
r2 = RepeatingTimer(0.5, print_r2)

r1.start()
r2.start()

The call to r1.start never terminates. It continues on forever. The output on the console, after four seconds, is:

R1

R1

R1

R1

This prompted me to introduce the time.sleep(0) call, although that doesn't seem to do anything.

I also tried with and without self.setDaemon(True), but that also seems to have no effect.

I also tried converting this into two classes: one with just the event wrappers (a StoppableTimer class), and another that simply creates and recreates the StoppableTimer in the callback, but that doesn't work either.  Here's what it looks like:

class StoppableTimer(Thread):
    def __init__(self, interval_seconds, callback):
        Thread.__init__(self)
        self.stop_event = Event()
        self.interval_seconds = interval_seconds
        self.callback = callback
        self.setDaemon(True)

    def start(self):
        time.sleep(self.interval_seconds)
        self.callback()

    def stop(self):
        self.stop_event.set()

class RepeatingTimer:
    def __init__(self, interval_seconds, callback):
        self.interval_seconds = interval_seconds
        self.callback = callback
        self.timer = StoppableTimer(interval_seconds, self.refresh_timer)

    def start(self):
        self.timer.start()

    def stop(self):
        self.timer.stop()

    def refresh_timer(self):
        self.stop()
        self.callback()
        self.timer = StoppableTimer(self.interval_seconds, self.refresh_timer)
        self.timer.start()

I'm completely at a loss on how to make this work. I'm also mostly a beginner to Python, so please add sufficient explanation to your answer so I can grasp what the fundamental issue is.

I also read a bit about the Global Interpreter Lock on SO, but I don't understand how that could be an issue.

For reference, I'm running Python 3.6.3 on Ubuntu 17.10

Body:
Short answer :

Don't override start(). Override run() instead.

Long answer because you're asking for details :

With the class definition in your first snippet, you've created a class which inherits from Thread, however you've overriden the start() method supposed to start your thread by a new method which is looping until the stop_event is set, that is to say, the method supposed to actually start your thread doesn't do this anymore.

So, when you try to start your thread, you actually run the loop calling your callback function in your current and only thread. And since it's an infinite loop, your second "thread" is not started, and you have no way to "stop" it.

You mustn't override start (well not in this way). Instead, override the run method. This is the method that will be run by your thread when you start it.

Also, you should do super().__init__() instead of Thread.__init__(self). The first one is the proper way to call an inherited method in Python.

class RepeatingTimer(Thread):
    def __init__(self, interval_seconds, callback):
        super().__init__()
        self.stop_event = Event()
        self.interval_seconds = interval_seconds
        self.callback = callback

    def run(self):
        while not self.stop_event.wait(self.interval_seconds):
            self.callback()

    def stop(self):
        self.stop_event.set()

And with the functions you've defined you can do :

r1 = RepeatingTimer(1, print_r1)
r2 = RepeatingTimer(0.5, print_r2)

r1.start()
r2.start()
time.sleep(4)
r1.stop()
r2.stop()

Here is the relevant documentation for Thread.


问:
Java equivalent to #region in C#
I want to use regions for code folding in Eclipse; how can that be done in Java?

An example usage in C#:

```<code>#region name
//code
#endregion
</code>```

答:
On Mac and Android Studio follow this sequence:

Highlight the source code to fold

Press Alt+Command+t

Select <editor-fold>

Also you can select other options:

Title: Java equivalent to #region in C#

Body:
I want to use regions for code folding in Eclipse; how can that be done in Java?

An example usage in C#:

#region name
//code
#endregion


问:
Spring JPA : Query one column from the table without where clause
I am new to JPA and Spring Boot and trying to write a custom query which returns only one column from the table when the API is triggered. But I get an error doing so. It would be helpful if someone could guide me to a correct way of writing this custom query. </p>

```<code>// Controller class
@Autowired
private UserTestInstanceDao usertestdao;

List<String> usertestinst = usertestdao.tempQuery();

// DAO class

public interface UserTestInstanceDao extends CrudRepository<UserTestInstance, Long> {

@Query("SELECT ti.test_name FROM test_instance ti")
public List<String> tempQuery();

}
</code>```

答:
It's ok but you have two options :

You must put your name class in the from clause @Query("SELECT ti.testName FROM UserTestInstance ti")

Use a native query whith the real name of Database @Query(value="SELECT ti.test_name FROM test_instance ti",nativeQuery=true)

Body:
I am new to JPA and Spring Boot and trying to write a custom query which returns only one column from the table when the API is triggered. But I get an error doing so. It would be helpful if someone could guide me to a correct way of writing this custom query.

// Controller class
@Autowired
private UserTestInstanceDao usertestdao;

List<String> usertestinst = usertestdao.tempQuery();

// DAO class

public interface UserTestInstanceDao extends CrudRepository<UserTestInstance, Long> {

@Query("SELECT ti.test_name FROM test_instance ti")
public List<String> tempQuery();

}


问:
How do I change the name of a custom policy in Azure AD B2C?
I want to use multiple base policies, so how do I upload a new base policy with a different name without overriding the old one?</p>

答:
You can’t change the prefix (B2C_1A), but to change the “TrustFrameworkBase” part of it, update the attribute below (should be at the top of the policy file)</p>

```<code>PolicyId="B2C_1A_TrustFrameworkBase"
</code>```

Body:
You can’t change the prefix (B2C_1A), but to change the “TrustFrameworkBase” part of it, update the attribute below (should be at the top of the policy file)

PolicyId="B2C_1A_TrustFrameworkBase"


问:
How do I create a console application which manipulates text in system.out?
For example, instead of printing

```<code>/
-
\
/
</code>```

on a new line make it so it stays on one line and is an animation of a spinner?

答:
If you need text cursor positioning, the solution will need to be through JNI. You will need some C cursor positioning software, which will be non portable. Curses was a popular application some 15-20 years ago.

The question is do you really need this trip to the past?

Body:
For example, instead of printing

/
-
\
/

on a new line make it so it stays on one line and is an animation of a spinner?


问:
Check whether a cell contains a substring
Is there an in-built function to check if a cell contains a given character/substring?

It would mean you can apply textual functions like Left/Right/Mid on a conditional basis without throwing errors when delimiting characters are absent.

答:
This is an old question but a solution for those using Excel 2016 or newer is you can remove the need for nested if structures by using the new IFS( condition1, return1 [,condition2, return2] ...) conditional.

I have formatted it to make it visually clearer on how to use it for the case of this question:

```<code>=IFS(
ISERROR(SEARCH("String1",A1))=FALSE,"Something1",
ISERROR(SEARCH("String2",A1))=FALSE,"Something2",
ISERROR(SEARCH("String3",A1))=FALSE,"Something3"
)
</code>```

Since SEARCH returns an error if a string is not found I wrapped it with an ISERROR(...)=FALSE to check for truth and then return the value wanted. It would be great if SEARCH returned 0 instead of an error for readability, but thats just how it works unfortunately.

Another note of importance is that IFS will return the match that it finds first and thus ordering is important. For example if my strings were Surf, Surfing, Surfs as String1,String2,String3 above and my cells string was Surfing it would match on the first term instead of the second because of the substring being Surf. Thus common denominators need to be last in the list. My IFS would need to be ordered Surfing, Surfs, Surf to work correctly (swapping Surfing and Surfs would also work in this simple example), but Surf would need to be last.

Body:
This is an old question but a solution for those using Excel 2016 or newer is you can remove the need for nested if structures by using the new IFS( condition1, return1 [,condition2, return2] ...) conditional.

I have formatted it to make it visually clearer on how to use it for the case of this question:

=IFS(
ISERROR(SEARCH("String1",A1))=FALSE,"Something1",
ISERROR(SEARCH("String2",A1))=FALSE,"Something2",
ISERROR(SEARCH("String3",A1))=FALSE,"Something3"
)

Since SEARCH returns an error if a string is not found I wrapped it with an ISERROR(...)=FALSE to check for truth and then return the value wanted. It would be great if SEARCH returned 0 instead of an error for readability, but thats just how it works unfortunately.

Another note of importance is that IFS will return the match that it finds first and thus ordering is important. For example if my strings were Surf, Surfing, Surfs as String1,String2,String3 above and my cells string was Surfing it would match on the first term instead of the second because of the substring being Surf. Thus common denominators need to be last in the list. My IFS would need to be ordered Surfing, Surfs, Surf to work correctly (swapping Surfing and Surfs would also work in this simple example), but Surf would need to be last.


问:
When to convert a categorical variable into a numerical variable for machine learning?
I am new to machine learning and I am running a classification algorithm (xgboost) on my data, using the caret package in R.

However, I am confused regarding the conversion of some categorical variables into numerical variables for the purpose of machine learning. I have scoured the web but I cannot find a specific rule, if it exists, on the subject.

The xgboost vignette at the following url (xgboost) mentions that "Xgboost manages only numeric vectors." Doesn't that mean that all my features (variables) need to contain only numeric values? However, I've seen some tutorials using xgboost where the variables were categorical variables.

Any help on the subject would be highly appreciated.

答:
The primary way categorical features are treated in statistics/machine learning is through a mechanism called one-hot encoding.

Take the following data, for example:

```<code>outcome    animal
      1       cat
      1       dog
      0       dog
      1       cat
</code>```

Say you wanted to predict outcome (whatever that is) based on the type of animal a given case (observation/row/subject/etc.). The way to do this is to encode animal in a one-hot fashion, like this:

```<code>outcome  is_dog   is_cat
      1       0        1
      1       1        0
      0       1        0
      1       0        1
</code>```

Where the animal column of cardinality k has been encoded into k new columns indicating the presence or absence of a particular category/attribute given the value for animal for that row.

From there, you can use whatever model you want to predict outcome based off of (the now differently-encoded) animal column. But make sure to leave one animal (one group) out of the model as the control group. In this case, you might fit a logistic regression model outcome ~ is_dog and interpret the slope coefficient for is_dog as the increase or decrease in likelihood of the 1 outcome for a dog in comparison to a cat.

Body:
The primary way categorical features are treated in statistics/machine learning is through a mechanism called one-hot encoding.

Take the following data, for example:

outcome    animal
      1       cat
      1       dog
      0       dog
      1       cat

Say you wanted to predict outcome (whatever that is) based on the type of animal a given case (observation/row/subject/etc.). The way to do this is to encode animal in a one-hot fashion, like this:

outcome  is_dog   is_cat
      1       0        1
      1       1        0
      0       1        0
      1       0        1

Where the animal column of cardinality k has been encoded into k new columns indicating the presence or absence of a particular category/attribute given the value for animal for that row.

From there, you can use whatever model you want to predict outcome based off of (the now differently-encoded) animal column. But make sure to leave one animal (one group) out of the model as the control group. In this case, you might fit a logistic regression model outcome ~ is_dog and interpret the slope coefficient for is_dog as the increase or decrease in likelihood of the 1 outcome for a dog in comparison to a cat.


问:
How to visualize a Regression Tree in Python
I'm looking to visualize a regression tree built using any of the ensemble methods in scikit learn (gradientboosting regressor, random forest regressor,bagging regressor).
I've looked at this question which comes close, and this question
which deals with classifier trees. But these questions require the 'tree' method, which is not available to the regression models in SKLearn.

but it didn't seem to yield a result.
I'm running into issues because there is no .tree method for the regression versions of these trees (the method only exists for the classification versions).
I'd like an output resembling this but based on a sci kit learn-constructed tree.

I've explored the methods associated with the objects but just cannot produce an answer.

答:
After much searching, I found software offered by Turi that models a regression tree, not to be confused with a decision tree.
Hope this helps

For what its worth, a regression tree looks like this:

While a decision/classifier tree looks like this:

And tho they look the same, the attribute needed to create this is tree_ which is only available to classifiers, not regressors.


问:
Object extending using javascript
I have a source object and I want to update its property value with a new target object and return the source object with modified property. Is there any predefined way in java script I have do this.

var sourceObj = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {},
        weight: 0
    }
}

var targetObj = {
    name: "3",
    street: "4"
}

var result = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {
            name: "3",
            street: "4"
        },
        weight: 0
    }
}```

答:
You can shallow copy object with Object.assign() and then alter the to value by directly accessing the key to.

var sourceObj = { context: { from: { name: "1", street: "2" }, to:{}, weight: 0 }};
var targetObj = { name: "3", street: "4" };
var result = Object.assign({},sourceObj);
result.context.to = Object.assign({},targetObj);
console.log(result);```
</div>
</div>
</p>

<p>Alternatively, you can directly update the <code>to</code> key of <code>sourceObj</code>. But that will modify your <code>sourceObj</code> object.</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sourceObj = { context: { from: { name: "1", street: "2" }, to:{}, weight: 0 }};
var targetObj = { name: "3", street: "4" };
sourceObj.context.to = targetObj;
console.log(sourceObj);</code>```

Title: Object extending using javascript

Body:
You can shallow copy object with Object.assign() and then alter the to value by directly accessing the key to.

var sourceObj = { context: { from: { name: "1", street: "2" }, to:{}, weight: 0 }};
var targetObj = { name: "3", street: "4" };
var result = Object.assign({},sourceObj);
result.context.to = Object.assign({},targetObj);
console.log(result);

Alternatively, you can directly update the to key of sourceObj. But that will modify your sourceObj object.

var sourceObj = { context: { from: { name: "1", street: "2" }, to:{}, weight: 0 }};
var targetObj = { name: "3", street: "4" };
sourceObj.context.to = targetObj;
console.log(sourceObj);


问:
Delete a dictionary item based on a value from a list iteration
I have tried the following:

```<code>losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)
</code>```

This just returns the error:

TypeError: list indices must be integers or slices, not str

I would like to iterate over losers and delete every item in candidates_and_fp_votes which has a key in losers

I expect an output of:

```<code>{'a': 24, 'c': 17, 'd': 23}
</code>```

How can I solve this problem?

Thanks in advance.

答:
your index i is a string, not an integer.
You could do something like this:

```<code>losers = ['e', 'b']

candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

for i in losers:

     if i in candidates_and_fp_votes:
          del candidates_and_fp_votes[i]

print(candidates_and_fp_votes)
</code>```

Body:
I have tried the following:

losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
    del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)

This just returns the error:

TypeError: list indices must be integers or slices, not str

I would like to iterate over losers and delete every item in candidates_and_fp_votes which has a key in losers

I expect an output of:

{'a': 24, 'c': 17, 'd': 23}

How can I solve this problem?

Thanks in advance.

Body:
your index i is a string, not an integer.
You could do something like this:

losers = ['e', 'b']

candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

for i in losers:

     if i in candidates_and_fp_votes:
          del candidates_and_fp_votes[i]

print(candidates_and_fp_votes)


问:
Compare DateTime unix time stamp
I'm trying to compare the date pass from previous page with the date (unix timestamp format) stored in database. My code as below.
Error : Recoverable fatal error: Object of class DateTime could not be converted to string in C:\xampp\htdocs\check.php on line 14

How should I modify it to be able to compare with the "datetime2" and store as the 10 digit unixtime.

Basically I do not want to convert it to normal date. just store as it is, 10 digit unixtimestamp.

Please help to look into the foreach loop as well. I want to check if the selected date has appeared in database.

Thank you

<?PHP
 session_start();

 $userid = $_SESSION['userid'];
 $datetime = $_POST['datetime'];
 $available = 0;

 $date = $datetime; $datetime2 = new DateTime($date); echo $datetime2->getTimestamp();

 $con = mysqli_connect('localhost', 'root', 'abc123');

 $query = "SELECT COUNT * FROM reservation WHERE InstallDate='" . $datetime2 . "'";

     if (!$con)
       {
       die('Could not connect: ' . mysqli_error($con));
      }

     mysqli_select_db($con, 'btr');

     foreach(mysqli_query($con, $query )as $row)
 {
  if($row <=1)
  {
   $available = 1;
   echo $available;
  }

 }

     mysqli_close($con);

?>```

答:
Instead of using object of class DateTime, try convert it to string in a propriate way as follows:

```<code>$query =
"SELECT COUNT * FROM reservation WHERE InstallDate='"
.$datetime2->format('d/m/Y')
."'";
</code>```

Also adjust d/m/Y separators for your database, e.g.MySQL uses d.m.Y separation.

Title: Compare DateTime unix time stamp

Body:
Instead of using object of class DateTime, try convert it to string in a propriate way as follows:

$query =
"SELECT COUNT * FROM reservation WHERE InstallDate='"
.$datetime2->format('d/m/Y')
."'";

Also adjust d/m/Y separators for your database, e.g.MySQL uses d.m.Y separation.


问:
How to prevent Jquery append line more than one time
my code is looking for any forms and add a new token ID line.
I need to prevent adding the new line,  if I have this line.

```<code><SCRIPT LANGUAGE = "JavaScript" >
          $(document).ready(function() {
                $("form").append('<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">');<br>
            });
    </script>
</code>```

 Please, advise me:

 Thank you .

答:
Try checking if the value is all ready there using includes</p>

```<code>$("form").each(function(){
   if!($(this).html().includes("<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">")){
       $(this).append('<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">');<br>
   }
});
</code>```

Body:
my code is looking for any forms and add a new token ID line.
I need to prevent adding the new line,  if I have this line.

 Please, advise me:

 Thank you .

Body:
Try checking if the value is all ready there using includes

$("form").each(function(){
   if!($(this).html().includes("<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">")){
       $(this).append('<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">');<br>
   }
});


问:
Using AMD OpenCL with mingw
I have downloaded and installed AMD APP SDK 3.0. When I try using it with mingw I get an error because CL/cl.hpp has #include <intrin.h> in it (this header is exclusive to VC++).

Is there a different set of header files for mingw? How do I fix it?

答:
I use both MSVC and MinGw 5.3.0 (bundled with QtCreator) to build OpenCL apps on both Intel and AMD Windows 10 systems using AMD APP SDK 3.0 and I have never experienced a build problem that wasn't in my own code!

However, I use the standard C CL/cl.h header file, not the C++ CL/cl.hpp header file...

The cl.hpp and cl2.hpp files provide C++ bindings for the standard C functions, see OpenCL C++ Bindings. If you don't require C++ bindings, the AMD APP SDK 3.0 CL/cl.h header file works fine.

If you want to use C++ Bindings then note that cl.hpp is obsolete; you should use cl2.hpp instead (which doesn't try to include intrin.h unless _MSC_VER is defined)...

An alternative OpenCL C++ binding (that also compiles with MinGw and AMD APP SDK 3.0) is boost compute.

Title: Using AMD OpenCL with mingw


问:
how to get a textview to autoscroll down when theres a new line
in swift 4.0 for cocoa applications

how do you get a textview to autoscroll down when theres a new line
of text added into it?

is there a built in function for this?

i can't seem to find a way to do this.

```<code>chatplace.scroll(<#T##point: NSPoint##NSPoint#>)
</code>```

答:
Here's a simple example that works:

```<code>import UIKit

class ViewController: UIViewController {

    var count = 0
    var timer:Timer?
    @IBOutlet weak var textView: UITextView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.isScrollEnabled = true
        textView.becomeFirstResponder()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        timer = Timer(timeInterval: 0.125, repeats: true, block: { (timer) in
            self.count += 1
            self.textView.text.append("\n\(self.count) This is another line")
        })
        if let timer = timer {
            RunLoop.current.add(timer, forMode: .commonModes)
        }
    }
}
</code>```

The result:

If you want to scroll programmatically this should do it:

```<code>func scrollToEnd(_ someTextView:UITextView) {
    let bottom = NSMakeRange(someTextView.text.lengthOfBytes(using: .utf8)-1, 1)
    someTextView.scrollRangeToVisible(bottom)
}
</code>```

Body:
in swift 4.0 for cocoa applications

how do you get a textview to autoscroll down when theres a new line
of text added into it?

is there a built in function for this?

i can't seem to find a way to do this.

chatplace.scroll(<#T##point: NSPoint##NSPoint#>)

Body:
Here's a simple example that works:

import UIKit

class ViewController: UIViewController {

    var count = 0
    var timer:Timer?
    @IBOutlet weak var textView: UITextView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.isScrollEnabled = true
        textView.becomeFirstResponder()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        timer = Timer(timeInterval: 0.125, repeats: true, block: { (timer) in
            self.count += 1
            self.textView.text.append("\n\(self.count) This is another line")
        })
        if let timer = timer {
            RunLoop.current.add(timer, forMode: .commonModes)
        }
    }
}

The result:

If you want to scroll programmatically this should do it:

func scrollToEnd(_ someTextView:UITextView) {
    let bottom = NSMakeRange(someTextView.text.lengthOfBytes(using: .utf8)-1, 1)
    someTextView.scrollRangeToVisible(bottom)
}


问:
Removing white space in `script output` in SQL Developer Oracle
I would like to know how to remove white space from my script out string. I am getting two tab(8 space) white space while prints two variable concatenated. But the when I remove the last variable then I get a normal script out on my SQL developer. How to remove white space for printing two variable concatenated with a string?
Here is the code I am running.

```<code>SET SERVEROUTPUT ON
DECLARE
  SUBTYPE name IS CHAR(20);
  SUBTYPE MESSAGE IS VARCHAR2(100);
  salutation name;
  greetings MESSAGE;
BEGIN
  salutation := 'Reader ';
  greetings  := 'Welcome to the World of PL/SQL';
  SYS.DBMS_OUTPUT.PUT_LINE('Hello ' || salutation || greetings);
END;
/
</code>```

Here is the screenshot of the script output.

How would I remove the white space I marked with red pen on the image?

答: Use VARCHAR2 instead of CHAR.  CHAR variables get right-padded to the defined length while VARCHAR2 variables only contain the value you assign.</p>

Body:
I would like to know how to remove white space from my script out string. I am getting two tab(8 space) white space while prints two variable concatenated. But the when I remove the last variable then I get a normal script out on my SQL developer. How to remove white space for printing two variable concatenated with a string?
Here is the code I am running.

SET SERVEROUTPUT ON
DECLARE
  SUBTYPE name IS CHAR(20);
  SUBTYPE MESSAGE IS VARCHAR2(100);
  salutation name;
  greetings MESSAGE;
BEGIN
  salutation := 'Reader ';
  greetings  := 'Welcome to the World of PL/SQL';
  SYS.DBMS_OUTPUT.PUT_LINE('Hello ' || salutation || greetings);
END;
/

Here is the screenshot of the script output.

How would I remove the white space I marked with red pen on the image?


问:
Finding max value using reduce
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

```<code>{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
</code>```

This is what I have so far:

```<code>(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
</code>```

This produces the outcome:

```<code>{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
</code>```

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

答:
You need some function that will convert the sales values from strings to numbers. For now assuming the sales numbers are indeed numbers, this should do the trick:

```<code>(->> table
     (group-by :product)
     (map (fn [[k v]]
            [k (first (sort-by (comp - identity :sales) v))]))
     (into {})
     vals
     (map (comp #(apply vector %)
                vals
                #(select-keys % [:product :city])))
     (into {}))
</code>```

Replace identity with your string->number function.

No doubt this function can be improved...

Title: Finding max value using reduce

Body:
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])

This is what I have so far:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)

This produces the outcome:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

Body:
You need some function that will convert the sales values from strings to numbers. For now assuming the sales numbers are indeed numbers, this should do the trick:

(->> table
     (group-by :product)
     (map (fn [[k v]]
            [k (first (sort-by (comp - identity :sales) v))]))
     (into {})
     vals
     (map (comp #(apply vector %)
                vals
                #(select-keys % [:product :city])))
     (into {}))

Replace identity with your string->number function.

No doubt this function can be improved...


问:
Replacing letters at certain indices
I'm currently making a hangman program. It starts out and asks you for a letter, and then if you get it right, it replaces a dash at that word, with the letter.

For example:

If the word is jazz, and you choose an a, it would come out

```<code>-a--
</code>```

now when you guess a z, it's supposed to come out as

```<code>-azz
</code>```

but instead, it only prints the z at the first index that the letter z shows up.

```<code>-az-
</code>```

Here's my code so far:

```<code>secret_word = "jazz"
dashes = "----"

def get_guess():
    while True:
        print dashes
        guess = input("Guess: ")
        if len(guess) > 1:
            print "Your guess must have exactly one character!"
        elif guess.isupper():
            print "Your guess must be a lowercase letter!"
        elif guess.isdigit():
            print "Your guess must be a letter!"
        else:
            return guess
            break

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
            return dashes

while True:
    user_guess = get_guess()
    dashes = update_dashes(secret_word, dashes, user_guess)
    if user_guess in secret_word:
        print "That letter is in the secret word!"
    else:
        print "That letter is not in the secret word!"
</code>```

答:
You perform a return dashes inside the for loop (well inside an if in the for loop). So that means that from the moment the if "fires" you will return the result.

You should return after the for loop:

```<code>def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            dashes = dashes[:i] + guess + dashes[i + 1:]
    <b>return dashes</b>  # for loop ended, all possible replacements done</code>```

A more Pythonic version is probably to work with zip (and use str.join):

```<code>def update_dashes(secret_word, dashes, guess):
    return ''.join(guess if guess == real else old
                   for real, old in zip(secret_word, dashes))</code>```

Here we iterate in parallel over the secret_word and dashes. In case the character of secret_word (the real) is equal to the guess, we emit guess, otherwise we emit the old character. We join then all these characters together in a string.

Title: Replacing letters at certain indices

Body:
I'm currently making a hangman program. It starts out and asks you for a letter, and then if you get it right, it replaces a dash at that word, with the letter.

For example:

If the word is jazz, and you choose an a, it would come out

-a--

now when you guess a z, it's supposed to come out as

-azz

but instead, it only prints the z at the first index that the letter z shows up.

-az-

Here's my code so far:

secret_word = "jazz"
dashes = "----"

def get_guess():
    while True:
        print dashes
        guess = input("Guess: ")
        if len(guess) > 1:
            print "Your guess must have exactly one character!"
        elif guess.isupper():
            print "Your guess must be a lowercase letter!"
        elif guess.isdigit():
            print "Your guess must be a letter!"
        else:
            return guess
            break

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
            return dashes

while True:
    user_guess = get_guess()
    dashes = update_dashes(secret_word, dashes, user_guess)
    if user_guess in secret_word:
        print "That letter is in the secret word!"
    else:
        print "That letter is not in the secret word!"

Body:
You perform a return dashes inside the for loop (well inside an if in the for loop). So that means that from the moment the if "fires" you will return the result.

You should return after the for loop:

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            dashes = dashes[:i] + guess + dashes[i + 1:]
    return dashes  # for loop ended, all possible replacements done

A more Pythonic version is probably to work with zip (and use str.join):

def update_dashes(secret_word, dashes, guess):
    return ''.join(guess if guess == real else old
                   for real, old in zip(secret_word, dashes))

Here we iterate in parallel over the secret_word and dashes. In case the character of secret_word (the real) is equal to the guess, we emit guess, otherwise we emit the old character. We join then all these characters together in a string.