How do I get a background location update every n minutes in my iOS application?

Question: I'm looking for a way to get a background location update every n minutes in my iOS application.  I'm using iOS 4.3 and the solution should work for non-jailbroken iPhones.
I tried / considered following options:

CLLocationManager startUpdatingLocation/startMonitoringSignificantLocationChanges: This works in the background as expected, based on the configured properties, but it seems not possible to force it to update the location every n minutes
NSTimer: Does work when the app is running in the foreground but doesn't seem to be designed for background tasks
Local notifications: Local notifications can be scheduled every n minutes, but it's not possible to execute some code to get the current location (without the user having to launch the app via the notification).  This approach also doesn't seem to be a clean approach as this is not what notifications should be used for.
UIApplication:beginBackgroundTaskWithExpirationHandler:  As far as I understand, this should be used to finish some work in the background (also limited in time) when an app is moved to the background rather than implementing "long-running" background processes.

How can I implement these regular background location updates?
Comment: If you are trying to make it work on iOS 7, you may try this solution here: http://stackoverflow.com/questions/18946881/background-location-services-not-working-in-ios-7/21966662#21966662 If you have any question, you are welcomed to join us for a discussion here: http://mobileoop.com/background-location-update-programming-for-ios-7
Comment: All your findings are correct (the four bullet points). Valuable information that is then, knowing what does not match you use case? And yes, when in SUSPENDED MODE or NOT RUNNING, there is no ultimate method for updating every n-minutes.
Comment: possible duplicate of [to run app continously in the background](http://stackoverflow.com/questions/3947785/to-run-app-continously-in-the-background)
Comment: useful follow-up: http://stackoverflow.com/questions/10235203/getting-user-location-every-n-minutes-after-app-goes-to-background?rq=1
Answer: I found a solution to implement this with the help of the Apple Developer Forums:

Specify location background mode
Create an NSTimer in the background with UIApplication:beginBackgroundTaskWithExpirationHandler:
When n is smaller than UIApplication:backgroundTimeRemaining it will work just fine. When n is larger, the location manager should be enabled (and disabled) again before there is no time remaining to avoid the background task being killed.

This works because location is one of the three allowed types of background execution.
Note: I lost some time by testing this in the simulator where it doesn't work. However, it works fine on my phone.
Comment: do you happen to have the link to the forum. I'm looking to implement the same type of location mapping and haven't been able to get it to work. Or some sample code would be greatly appreciated.
Comment: For all those interested in seeing some actual code reflecting what is being discussed here, check http://stackoverflow.com/questions/10235203/getting-user-location-every-n-minutes-after-app-goes-to-background
Comment: Can you please explain why the background task is not killed after 10 mins (maximum allowed time) if you just stop and start the location manager? is it some sort of intended functionality? it sounds more like a bug in Apple SDK if it happens like that. Which iOS version you were trying it on?
Comment: @all: Yes, our app is available in the AppStore.  I am not gonna post all the code, all mentioned bulletpoints are clearly documented features.  In case you are having a specific problem, post your own question explaining what you have tried and what goes wrong.
Comment: @user836026: Yes, that's what I mean by specifying background mode.  After stopping the location update, it should be started again within 10 minutes to avoid the app from being terminated.
Comment: @user836026:  If you don't stop the location manager, your app won't be terminated.  That works as designed.  In my scenario, I stop the location manager.
Comment: on my test there is not such a difference. I've done a test comparing: my code with this method, mylocus (on appStore) and the "always On" method.
Comment: there is some problem with this approach on iOS 7, take a look at http://stackoverflow.com/questions/18901583/start-location-manager-in-ios-7-from-background-task
Comment: @saurabh: As per my understanding, it works as designed since location updates is a valid background processing mode.  It does work on different iOS versions (4.X, 5.X), don't think it's a bug.
Comment: If n is larger than 10 mins(which is the extra time the iOs gives you)
you will end up sending the coordinates after that 10 mins, as you said, "in case n is larger, the location manager should be enabled (and disabled) " wich produces "didUpdateLocation" to execute.
Im sure it works for you but could you post some code so I can get a better picture of what you did?, this EXACTLY what Im looking for.
Comment: @wjans I'm not getting your solutions ... If I get you right you are running NSTimer in beginBackgroundTaskWithExpirationHandler scheduling to startUpdateLocation every n minutes right ? But what you do if n is larger than backgroundTimeRemaining ? Where do you enable and disable locationManager ? Shall the NSTimer work at all if n > backgroundTimeRemaining ???
Comment: Yes,I tested it & it works as you described. Basically if you started " [locationManager startUpdatingLocation];" in "beginBackgroundTaskWithExpirationHandler" it works forever, it doesn't stop as excepted. I'm just worried that this could be a bug and Apple might fix it in future.
Comment: do you guys have any test of the battery consumption of this method?
Comment: it think (I haven't seen the implementation of course) it uses background location update + NSTimer
Comment: @wjans hey .. .can you post your code somewhere as if I am also looking for similar things.Thanks
Comment: Anyone figured out how to use a larger interval than the background task?
Comment: @cwieland: The forum post doesn't mention any more information but all individual "steps" are clearly explained in the Apple docs.  In case you run into specific problems, I suggest you post your own question.
Comment: @DavidShaikh: I literally implemented it like this: `[self.locationManager startUpdatingLocation]; [self.locationManager stopUpdatingLocation];`.  In `didUpdateToLocation` I just check whether or not I'm interested in the update.
Comment: @deimus: No, that's right.  In case `n` is larger, scheduling a timer every `n` minuties won't work.  Therefor you have to make sure to enable it sooner, before `backgroundTimeRemaining` becomes zero.
Comment: @wjans I'm really cluttered in your solution ... just couple of my questions 1. Has your code ever worked for you if n is larger than backgroundTimeRemaining ? 2. How you have used NSTimer with UIApplication:beginBackgroundTaskWithExpirationHandler: particularely i'm insterested how you have scheduled NSTimer ?
Comment: @deimus: 1. Yes, by enabling and immediately disabling the location mgr as described. 2. When using `UIApplication:beginBackgroundTaskWithExpirationHandler`, you specificy a block of code to be executed.  In that block, you can simply start a timer as described in the Apple documentation.
Comment: @wjans I'm really interested only in case when n is larger than backgroundTimeRemaining... I guess NSTimer will not work work... you suggested to enable it sooner ... actually no one knows when user will send application to background ... what do you mean under "sooner" ?
Comment: @wjans let say n is 14 mins and backgroundTimeRemaining is 10 mins ... Can you please describe the workflow of you code. When NSTimer will fire the scheduled method, starting from the point when application goes to background.
Comment: Finally after more than hour of thinking got the code working... I simply couldn't understand why the background task was not killed after 10 mins (backgroundTimeRemaining) ... as also @saurabh mentioned in his comment ... So my last question to you, have your app passed Apple submission, this is not the violation of app acceptance guideline ?
Comment: @wjans can anybody provide me the `sample code` for that `Background process` work flow at a `time`. i get location at particular time. not at a `didupdatelocation` method. i really need to work out as the asked question
Comment: I wonder if anybody could post the code. also as demus asked. did this pass Apple submission .
Comment: @wjans do you mean by "Specify location background mode" to set UIBackgroundModes=location in Info.plist file?
Comment: Works nice, however I don't like very much that the user is prompted to allow user location. Any way thanks :).
Comment: So correct me if i'm wrong. for this to work, you need to start/stop location update "every 10 minutes".
Comment: @wjans, it works fine now with me ... just for fine tuning, I only turn on location update for short period of time - only 2 seconds - to save battery. do you think 2 seconds is OK, or too short to get high accuracy location update.
Comment: this compared to "always On" location update is much better, i didn't notice battery leaking. However, I didn't do through testing.
Comment: @luka: do you know how mylocus app works? does it use background location update or significant change only?
Comment: Did you test mylocus app? does it drain battery, or there is no noticable effect on battery.
Comment: @All which solution this or below samthui7's explained solution should I prefer to save the device battery or both will affect the same? And can these both solutions will work on iOS 7 and iOS 8?
Comment: Here's a great location framework for iOS that does it all for you: https://github.com/IngeoSDK/ingeo-ios-sdk
Comment: Can anyone share the code regarding this solution?

Is that the timer start, and every time it trigger and check the value of n to toggle the state of the LocationManager? If it is the case, how can we avoid the timer being killed when the app is at the background?
Comment: @wjans. WhenInUse service user moves from online to offline will it return correct coordinates ? till what time? if user offline is it good idea to call "StartUpdatingLocation" if user moving?
Comment: @wjans How do you remove the status bar location icon during the "cooldown" (betweeen the stopUpdatingLocation to the next startUpdatingLocation)? It stays there even after the calling to stopUpdatingLocation. The icon is only get disappeared after explicitly calling stopUpdatingLocation (from a ViewController or something like that)
Comment: Is this answer still valid on iOS 13? I'm trying your solution but cant get it to works.
Answer: On iOS 8/9/10 to make background location update every 5 minutes do the following:

Go to Project -> Capabilities -> Background Modes -> select Location updates
Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)
To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.

I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.
@interface LocationManager () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;

@end

@implementation LocationManager

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        LocationManager *instance = sharedInstance;
        instance.locationManager = [CLLocationManager new];
        instance.locationManager.delegate = instance;
        instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
        instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
    });

    return sharedInstance;
}

- (void)startUpdatingLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.locationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.locationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *mostRecentLocation = locations.lastObject;
    NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));

    NSDate *now = [NSDate date];
    NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;

    if (!self.lastTimestamp || interval >= 5 * 60)
    {
        self.lastTimestamp = now;
        NSLog(@"Sending current location to web service.");
    }
}

@end

Comment: Does this work for more than a few hours? It seems like even if the app is not terminated, the device stops pushing location updates after an hour or so of the app going to the background.
Comment: Background Fetch is disabled in my project (it should not matter if it is off or on). However pausesLocationUpdatesAutomatically must be set to NO for above example to work properly. It will NOT resume automatically once you start moving again if it was paused by the system previously. That is why in above example I set this property to NO.
Comment: @LeszekS you need to add below code for iOS 9 support for background -

    `if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}`
Comment: What's the convenience of doing this? You're still draining the battery by having a constant high accuracy. The only thing you don't do is you don't actually use the **already received** location until you reach an interval of 5 minutes...
Comment: I think you are absolutely right. Found some more information about the issue here: http://stackoverflow.com/q/17484352/1048331
Comment: @AdrianHoe in your view controller just call [[LocationManager sharedInstance] startUpdatingLocation]; and location update will start working.
Comment: @Honey yes you are absolutely right about battery life, but still I can see reasons why someone would need only 1 location reading per x minutes and that was the question asked here so above code is the answer to this question. I also mentioned in the comment above that kCLLocationAccuracyHundredMeters can be used for better battery life.
Comment: I got it working for 20 hours in background and did not notice any problems. Are you sure you did set everything like above?
Comment: Interesting. I have `pausesLocationUpdatesAutomatically` set to `YES`, but I'm guessing it should resume once I start moving again, which it does not seem to be doing. Do you have Background Fetch checked too, under Capabilities -> Background Modes?
Comment: Hi @LeszekS,

I'm learning about background process and am also looking for similar example. Your solution is very close to what I'm looking for. I wonder how can I attach the LocationManager to a UIViewController or AppDelegate?

I have no slightest idea how to execute the codes in your example. Can you please provide some ideas how to execute your codes?

Thanks,
Comment: Any specific reason why this should not work in iOS 7?
Comment: Did not test it on iOS 7 but probably it should also work fine.
Comment: Of course the code above is only the content of .m file. I assumed it will be obvoius that you also need to create an interface declaration in .h file to make it work. Also you must add declarations of sharedInstance and startUpdatingLocation methods in your interface (.h) file to be able to call it from AppDelegate.
Comment: Is this the same for iOS9?  Also, Is it possible to get location every 5 minutes while the app is terminated? Say, a service that starts automatically when the device is started?
Comment: @SMKS that's not possible.
Comment: @LeszekS from where are you taking `lastTimestamp` ?
Comment: @LeszekS : please let me know how to get current location even though app is killed or terminated , i have tried using significantlocation but didn't work?
Answer: I did this in an application I'm developing. The timers don't work when the app is in the background but the app is constantly receiving the location updates. I read somewhere in the documentation (i can't seem to find it now, i'll post an update when i do) that a method can be called only on an active run loop when the app is in the background. The app delegate has an active  run loop even in the bg so you dont need to create your own to make this work.
[Im not sure if this is the correct explanation but thats how I understood from what i read]
First of all, add the location object for the key UIBackgroundModes in your app's info.plist. Now, what you need to do is start the location updates anywhere in your app:
    CLLocationManager locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;//or whatever class you have for managing location
    [locationManager startUpdatingLocation];

Next, write a method to handle the location updates,
say -(void)didUpdateToLocation:(CLLocation*)location, in the app delegate. Then implement the method locationManager:didUpdateLocation:fromLocation of CLLocationManagerDelegate in the class in which you started the location manager (since we set the location manager delegate to 'self'). Inside this method you need to check if the time interval after which you have to handle the location updates has elapsed. You can do this by saving the current time every time. If that time has elapsed, call the method UpdateLocation from your app delegate:
NSDate *newLocationTimestamp = newLocation.timestamp;
NSDate *lastLocationUpdateTiemstamp;

int locationUpdateInterval = 300;//5 mins

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {

        lastLocationUpdateTiemstamp = [userDefaults objectForKey:kLastLocationUpdateTimestamp];

        if (!([newLocationTimestamp timeIntervalSinceDate:lastLocationUpdateTiemstamp] < locationUpdateInterval)) {
            //NSLog(@"New Location: %@", newLocation);
            [(AppDelegate*)[UIApplication sharedApplication].delegate didUpdateToLocation:newLocation];
            [userDefaults setObject:newLocationTimestamp forKey:kLastLocationUpdateTimestamp];
        }
    }
}

This will call your method every 5 mins even when your app is in background.
Imp: This implementation drains the battery, if your location data's accuracy is not critical you should use [locationManager startMonitoringSignificantLocationChanges]
Before adding this to your app, please read the Location Awareness Programming Guide
Comment: That way the location services are constantly enabled (indeed battery draining), I don't want that.  I want to enable the location service every n minutes and immediately disable it when I have a good fix (just noticed that I didn't explain that clearly in my question).  I can achieve this behaviour in the solution I described.
Comment: You can set location manager accuracy to 1km - this will leave your battery almost intact. After 5min you set accuracy to 1m. When you get satisfying location (normally after 5s) just set accuracy back to 1km.
Comment: knagode, I tried your suggested solution for battery draining issue, but even after increase accuracy after N minutes, locationManager:
didUpdateLocations method is not called again.
I tried startUpdating and stopUpdating, instead of increase and decrease accuracy, it is called successfully delegate locationManager:
didUpdateLocations method, after N minutes, but is not working in Background MODE...
Comment: As for the links of documentation. See [here](https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate): "The methods of your delegate object are called from the thread in which you started the corresponding location services. That thread must itself have an active run loop, like the one found in your application's main thread."
Answer: Now that iOS6 is out the best way to have a forever running location services is...
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
 Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
 Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
 */

NSLog(@"to background");

app.isInBackground = TRUE;

UIApplication *app = [UIApplication sharedApplication];

// Request permission to run in the background. Provide an
// expiration handler in case the task runs long.
NSAssert(bgTask == UIBackgroundTaskInvalid, nil);

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    // Synchronize the cleanup call on the main thread in case
    // the task actually finishes at around the same time.
    dispatch_async(dispatch_get_main_queue(), ^{

        if (bgTask != UIBackgroundTaskInvalid)
        {
            [app endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }
    });
}];

// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // Do the work associated with the task.

    locationManager.distanceFilter = 100;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [locationManager startMonitoringSignificantLocationChanges];
    [locationManager startUpdatingLocation];

    NSLog(@"App staus: applicationDidEnterBackground");
    // Synchronize the cleanup call on the main thread in case
    // the expiration handler is fired at the same time.
    dispatch_async(dispatch_get_main_queue(), ^{
        if (bgTask != UIBackgroundTaskInvalid)
        {
            [app endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }
    });
});

NSLog(@"backgroundTimeRemaining: %.0f", [[UIApplication sharedApplication] backgroundTimeRemaining]);

}

Just tested it like that:
I started the app, go background and move in the car by some minutes. Then I go home for 1 hour and start moving again (without opening again the app). Locations started again. Then stopped for two hours and started again. Everything ok again...
DO NOT FORGET USING the new location services in iOS6
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *loc = [locations lastObject];

    // Lat/Lon
    float latitudeMe = loc.coordinate.latitude;
    float longitudeMe = loc.coordinate.longitude;
}

Comment: If the app crashes or is killed, the system doesn't restart, right?
Comment: For more readable code, you can do a [locations lastObject]; instead of the
[locations objectAtIndex:[locations count] - 1]
Comment: your method is only at ios6?
Comment: Do we have to use this? I thought just have the location manager code in viewDidLoad of a class, and have set a background key in the plist file that the app registers for Location updates should be good enough? Can you please help me with this!
Comment: Yes, it will work like charm nithinreddy but it will stop working after 10 minutes since iOS kills long threads after that period. My solution is perfect if you want to have those services started forever. I made some tests two days ago and it drains 6% battery each hour. Using [locationManager startUpdatingLocation] instead will drain 17%
Comment: When using your code, I need to move the `[locationManager startUpdatingLocation];` call to be outside of the `dispatch_async()` block (so it ends up between the `bgTask` and `dispatch_async()`). Otherwise I won't receive any location updates (`locationManager: didUpdateLocations:`). Am I doing something wrong?
Comment: @Jonathan have you enabled location services on background? Please check your plist file. My code should work without modification. I have used it on two apps
Comment: @AlejandroLuengo Yeah, my [plist file](http://pastebin.com/3zycNe6V) is right. I have a class that manages the location updates. In the `applicationWillResignActive:` method in my AppDelegate I call a [method](http://pastebin.com/yAMNmu9b) from this class, to start the updates. When using the first `startUpdatingLocation:` call, everything works (forever). However, when using the second call (as in your example), location updates stop after ten minutes. Thanks!
Comment: @Jonathan please note you must add this interface on the code where do receive locationManager updates.
(@)interface AppDelegate : UIResponder
+ (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
(@)end
Also you need TWO location methods: one for regular updates and one for bg updates, like this: - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
and - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
Comment: @Jonathan send me an email if you want more help. I will be glad helping you. You can reachme at www.atomstudios.es website, find contact. I don't want to put the email here to avoid spam spiders
Comment: @AlejandroLuengo thanks for your answer. I am doing an ios app which tracks user locations. I need to send the new location co ordinates to the server every 30 seconds and need to update the location again once I get response from the server. The problem is sometimes didUpdateToLocation is not called and in that method only I am sending request to the server. I am really helpless here. Do you have any suggestion ? If you have, let me know.
Comment: didUpdateToLocation only gets called when location changes. You should send the last location received every 30 seconds since if you don't move you won't receive a new location
Comment: I'm not sure how this is any different from enabling significant change monitoring by itself. That's supposed to wake your app up and make it monitor location changes when you move 500m+ (which sounds like what you did). The rest seems kind of meaningless to me. Am I missing something?
Answer: To someone else having nightmare figure out this one. I have a simple solution.

look this example from raywenderlich.com-> have sample code, this works perfectly, but unfortunately no timer during background location. this will run indefinitely.
Add timer by using :
-(void)applicationDidEnterBackground {
[self.locationManager stopUpdatingLocation];

UIApplication*    app = [UIApplication sharedApplication];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

 self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate
                                              target:self.locationManager
                                            selector:@selector(startUpdatingLocation)
                                            userInfo:nil
                                             repeats:YES];

}

Just don't forget to add "App registers for location updates" in info.plist.
Comment: Does this get the location for more than 3 minutes?
Comment: Must set location in Capabilities -> Background Mode.
Comment: It's not working!! ?I have checked on iOS 8 ans iOS 10
Comment: Correct me if I'm wrong. Based on what I read, you start locationManager only once. After that all intervals are redundant. Since it's already been started
Comment: it is working but it is getting stopped after 170 seconds. i want to run my task in background for  unlimited time
Answer: Here is what I use:
import Foundation
import CoreLocation
import UIKit

class BackgroundLocationManager :NSObject, CLLocationManagerDelegate {

    static let instance = BackgroundLocationManager()
    static let BACKGROUND_TIMER = 150.0 // restart location manager every 150 seconds
    static let UPDATE_SERVER_INTERVAL = 60 * 60 // 1 hour - once every 1 hour send location to server

    let locationManager = CLLocationManager()
    var timer:NSTimer?
    var currentBgTaskId : UIBackgroundTaskIdentifier?
    var lastLocationDate : NSDate = NSDate()

    private override init(){
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.activityType = .Other;
        locationManager.distanceFilter = kCLDistanceFilterNone;
        if #available(iOS 9, *){
            locationManager.allowsBackgroundLocationUpdates = true
        }

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
    }

    func applicationEnterBackground(){
        FileLogger.log("applicationEnterBackground")
        start()
    }

    func start(){
        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
            if #available(iOS 9, *){
                locationManager.requestLocation()
            } else {
                locationManager.startUpdatingLocation()
            }
        } else {
                locationManager.requestAlwaysAuthorization()
        }
    }
    func restart (){
        timer?.invalidate()
        timer = nil
        start()
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        switch status {
        case CLAuthorizationStatus.Restricted:
            //log("Restricted Access to location")
        case CLAuthorizationStatus.Denied:
            //log("User denied access to location")
        case CLAuthorizationStatus.NotDetermined:
            //log("Status not determined")
        default:
            //log("startUpdatintLocation")
            if #available(iOS 9, *){
                locationManager.requestLocation()
            } else {
                locationManager.startUpdatingLocation()
            }
        }
    }
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if(timer==nil){
            // The locations array is sorted in chronologically ascending order, so the
            // last element is the most recent
            guard let location = locations.last else {return}

            beginNewBackgroundTask()
            locationManager.stopUpdatingLocation()
            let now = NSDate()
            if(isItTime(now)){
                //TODO: Every n minutes do whatever you want with the new location. Like for example sendLocationToServer(location, now:now)
            }
        }
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        CrashReporter.recordError(error)

        beginNewBackgroundTask()
        locationManager.stopUpdatingLocation()
    }

    func isItTime(now:NSDate) -> Bool {
        let timePast = now.timeIntervalSinceDate(lastLocationDate)
        let intervalExceeded = Int(timePast) > BackgroundLocationManager.UPDATE_SERVER_INTERVAL
        return intervalExceeded;
    }

    func sendLocationToServer(location:CLLocation, now:NSDate){
        //TODO
    }

    func beginNewBackgroundTask(){
        var previousTaskId = currentBgTaskId;
        currentBgTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            FileLogger.log("task expired: ")
        })
        if let taskId = previousTaskId{
            UIApplication.sharedApplication().endBackgroundTask(taskId)
            previousTaskId = UIBackgroundTaskInvalid
        }

        timer = NSTimer.scheduledTimerWithTimeInterval(BackgroundLocationManager.BACKGROUND_TIMER, target: self, selector: #selector(self.restart),userInfo: nil, repeats: false)
    }
}

I start the tracking in AppDelegate like that:
BackgroundLocationManager.instance.start()

Comment: I've tried this code but it seems like it's not working on iOS11? (I haven't test it on any other versions.)
Comment: Thanks. Our project needs to track user location + send PubNub events in the background and your solution is working really well.
Comment: Hi Hmitkov,
Where I Can Call sendLocationToServer method to send user location on server
Comment: @AmanGupta007 You can call sendLocationToServer in func locationManager(manager: didUpdateLocations:). Notice the //TODO comment in the code.
Comment: @hmitkov Is it possible to start and stop Location Services with this while app is in the background? Example, start location service from a push notification grab some lat/long, send to webservice, then stop updating location. Do this each time the 'content-available' = 1 is included in the push body.
Comment: @DookieMan You don't need to do it this way. The purpose of the code above is to keep the app alive in the background at all times. While in your case you don't need your app to stay active in the background. When your app receives a PN with 'content-available' = 1, it is automatically activated in the background and the  method application.didReceiveRemoteNotification is called. All you need to do inside that method is to start the location manager for a fresh location update, send it to your server and call the completion handler.
Answer: Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.
The CLLocationManager will only call locationManager:didUpdateToLocation:fromLocation: when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.
A few other things that might help inform further solutions:

Starting & Stopping the services causes the didUpdateToLocation delegate method to be called, but the newLocation might have an old timestamp.
Region Monitoring might help
When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed startMonitoringSignificantLocationChanges as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.

Good Luck!
UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.
Comment: In the situation you describe, the app is most likely using the startMonitoringSignificantLocationChanges approach. Here, the phone gets temporarily 'woken up' when it receives a location update, but there's no interval that you can set to 'ping' this service in the background. When the phone moves (or switches from Cellular to GPS or to Wifi), it triggers an update. The Stanford iTunes U lecture on the topic was really helpful for me - hopefully it can help you find a workaround: http://itunes.apple.com/us/itunes-u/iphone-application-development/id384233225#
Comment: Thx for the pointer.  However, I still don't understand what the app is doing though.  Even if my phone is at my desk, not moving at all, I can see the location service being triggered every 10 minutes (exactly).  If I understand correctly, `startMonitoringSignificantLocationChanges` wouldn't give any update in that case.
Comment: There are apps available in the AppStore (like for instance "My Locus") that do make it possible to get a location update in the background.  They don't keep the location service active but it just gets enabled shortly as per the interval defined.  How do they do this?
Comment: @wjans how is your phone battery consumption, did you notice it drain quicly maybe due to Mylocus app?
Answer: I did write an app using Location services, app must send location every 10s.
And it worked very well.
Just use the "allowDeferredLocationUpdatesUntilTraveled:timeout" method, following Apple's doc.
What I did are:
Required: Register background mode for update Location.
1. Create LocationManger and startUpdatingLocation, with accuracy and filteredDistance as whatever you want:
-(void) initLocationManager
{
    // Create the manager object
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    _locationManager.delegate = self;
    // This is the most important property to set for the manager. It ultimately determines how the manager will
    // attempt to acquire location and thus, the amount of power that will be consumed.
    _locationManager.desiredAccuracy = 45;
    _locationManager.distanceFilter = 100;
    // Once configured, the location manager must be "started".
    [_locationManager startUpdatingLocation];
}

2. To keep app run forever using allowDeferredLocationUpdatesUntilTraveled:timeout method in background, you must restart updatingLocation with new parameter when app moves to background, like this:
- (void)applicationWillResignActive:(UIApplication *)application {
     _isBackgroundMode = YES;

    [_locationManager stopUpdatingLocation];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [_locationManager setDistanceFilter:kCLDistanceFilterNone];
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    [_locationManager startUpdatingLocation];
 }

3. App gets updatedLocations as normal with locationManager:didUpdateLocations: callback:
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//  store data
    CLLocation *newLocation = [locations lastObject];
    self.userLocation = newLocation;

   //tell the centralManager that you want to deferred this updatedLocation
    if (_isBackgroundMode && !_deferringUpdates)
    {
        _deferringUpdates = YES;
        [self.locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
    }
}

4. But you should handle the data in then locationManager:didFinishDeferredUpdatesWithError: callback for your purpose
- (void) locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error {

     _deferringUpdates = NO;

     //do something
}

5. NOTE: I think we should reset parameters of LocationManager each time app switches between background/forground mode.
Comment: I did try both solutions you mention, and saw that @wjans's one is a little bit more save battery. But, after the coming of iOS 8, it seems that that solution does not work properly anymore. For more detail: most of time, app cannot have long live in background mode.
Comment: @All which solution this or above wjans's explained solution should I prefer to save the device battery or both will affect the same?
Comment: @samthui7 Why do you set pausesLocationUpdatesAutomatically = false ?
Comment: My app's requirement is to keep sending userLocation every 10s, while `pausesLocationUpdatesAutomatically = true` tells location manager to pause updates if there is seemly no location change ([Apple's doc](https://developer.apple.com/reference/corelocation/cllocationmanager/1620553-pauseslocationupdatesautomatical)). Anyway, I did not explicitly test the case of `location manager pauses updates` yet :D.
Comment: @CedricSoubrie: Setting `pausesLocationUpdatesAutomatically = true` causes my app to stop updating location.
Answer: if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}

This is needed for background location tracking since iOS 9.
Comment: This saved my day!       using iOS8 deployment target, with iOS9 device
Answer: I used xs2bush's method of getting an interval (using timeIntervalSinceDate) and expanded on it a little bit. I wanted to make sure that I was getting the required accuracy that I needed and also that I was not running down the battery by keeping the gps radio on more than necessary.
I keep location running continuously with the following settings:
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
locationManager.distanceFilter = 5;

this is a relatively low drain on the battery. When I'm ready to get my next periodic location reading, I first check to see if the location is within my desired accuracy, if it is, I then use the location. If it's not, then I increase the accuracy with this:
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 0;

get my location and then once I have the location I turn the accuracy back down again to minimize the drain on the battery. I have written a full working sample of this and also I have written the source for the server side code to collect the location data, store it to a database and allow users to view gps data in real time or retrieve and view previously stored routes. I have clients for iOS, android, windows phone and java me. All clients are natively written and they all work properly in the background. The project is MIT licensed.
The iOS project is targeted for iOS 6 using a base SDK of iOS 7. You can get the code here.
Please file an issue on github if you see any problems with it. Thanks.
Comment: does the solution you posted in the above comment kill the battery life, or are you still doing some optimization for that?
Comment: I tried your solution, but is not working...
when app goes to background then, even after increase accuracy, app does not gettign called didUpdateToLocation method in my case
Comment: @HardikDarji important question. Are you moving? If not, location updates may stop. Try taking your phone out for a walk or a drive and see if that fixes it.
Comment: Thanks for your quick response.
But I want location updates in every 2 min, without care of my phone is moving or not. In this scenario didUpdateToLocation method is not called.
I am looking here for :
How do I get location update every n minutes !!!
Comment: try setting the timeIntervalInSeconds to 120 and uncomment this line:

locationManager.pausesLocationUpdatesAutomatically = NO;
Comment: I also tried with locationManager.pausesLocationUpdatesAutomatically = NO; aslo set Location_Update_Interval = 120.
I am calling reduceTrackingAccuracy method, in locationManager:didUpdateLocations delegate, and also schedule for calling increaseTrackingAccuracy method after delay of 115 seconds.
increaseTrackingAccuracy is calling, but after increase accuracy,
locationManager:didUpdateLocations delegate method is not getting called..
Comment: its working nick !!!
if i am not moving, but move with minimum distance filter, its getting called locationManager:didUpdateLocations method.
thanks:)
Answer: It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:
     [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
     [self.locationManager setDistanceFilter:99999];

which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:
- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}

All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device
Answer: There is a cocoapod  APScheduledLocationManager that allows to get background location updates every n seconds with desired location accuracy.
let manager = APScheduledLocationManager(delegate: self)
manager.startUpdatingLocation(interval: 170, acceptableLocationAccuracy: 100)

The repository also contains an example app written in Swift 3.
Comment: do you have anything like this in objective c ?
Comment: i used to use this, but it does not update while in background anymore and this is not maintained for the last 5 years or more. Here on this page to update or find a better solution.
Answer: In iOS 9 and watchOS 2.0 there's a new method on CLLocationManager that lets you request the current location: CLLocationManager:requestLocation(). This completes immediately and then returns the location to the CLLocationManager delegate.
You can use an NSTimer to request a location every minute with this method now and don't have to work with startUpdatingLocation and stopUpdatingLocation methods.
However if you want to capture locations based on a change of X meters from the last location, just set the distanceFilter property of CLLocationManger and to X call startUpdatingLocation().
Answer: Attached is a Swift solution based in:
Define App registers for location updates in the info.plist
Keep the locationManager running all the time
Switch kCLLocationAccuracy between BestForNavigation (for 5 secs to get the location) and ThreeKilometers for the rest of the wait period to avoid battery drainage
This example updates location every 1 min in Foreground and every 15 mins in Background.
The example works fine with Xcode 6 Beta 6, running in a iOS 7 device.
In the App Delegate (mapView is an Optional pointing to the mapView Controller)
func applicationDidBecomeActive(application: UIApplication!) {
    if appLaunched! == false { // Reference to mapView used to limit one location update per timer cycle
        appLaunched = true
        var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var window = appDelegate.window
        var tabBar = window?.rootViewController as UITabBarController
        var navCon = tabBar.viewControllers[0] as UINavigationController
        mapView = navCon.topViewController as? MapViewController
    }
    self.startInitialPeriodWithTimeInterval(60.0)
}

func applicationDidEnterBackground(application: UIApplication!) {
    self.startInitialPeriodWithTimeInterval(15 * 60.0)
}

func startInitialPeriodWithTimeInterval(timeInterval: NSTimeInterval) {
    timer?.invalidate() // reset timer
    locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("getFirstLocationUpdate:"), userInfo: timeInterval, repeats: false)
}

func getFirstLocationUpdate(sender: NSTimer) {
    let timeInterval = sender.userInfo as Double
    timer?.invalidate()
    mapView?.canReportLocation = true
    timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: Selector("waitForTimer:"), userInfo: timeInterval, repeats: true)
}

func waitForTimer(sender: NSTimer) {
    let time = sender.userInfo as Double
    locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    finalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("getLocationUpdate"), userInfo: nil, repeats: false)
}

func getLocationUpdate() {
    finalTimer?.invalidate()
    mapView?.canReportLocation = true
}

In the mapView (locationManager points to the object in the AppDelegate)
override func viewDidLoad() {
    super.viewDidLoad()
    var appDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
    locationManager = appDelegate.locationManager!
    locationManager.delegate = self
    canReportLocation = true
}

  func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if canReportLocation! {
            canReportLocation = false
            locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        } else {
            //println("Ignore location update")
        }
    }


What is a good progression to using a dip/pull up belt

Question: I do 5 sets of 10-15 reps of pull ups using a 20lb weight vest. I'm looking to focus on strength and just ordered a dip/pull up belt to add plates.  What's a good progression to add strength? Should I aim for 5x5 and increase weight until I can just about complete?
Comment: Possible useful reddit thread on why we generally go for reps before adding weight with pull-ups: http://www.reddit.com/r/Fitness/comments/12p1vb/why_dont_more_people_train_pullups_like_a/
Answer: The standard progression I've seen is to add weight once you can do fifteen or twenty unweighted. One then does three or more sets with added weight. One should be able to do at least five and no more than twelve reps--as long as the weight is within those bounds, it's the right weight. This keeps both volume and strength up. If you can't do five, reduce the weight. If you can do ten or twelve each set, add five pounds.
All numbers assume dead-hang, full range of motion, no kip, chin over the bar and hopefully chest touching the bar.
Comment: +1. Yeah I've seen people (myself included) rush to put the weight belt on but proper dead-hanging between reps for 10-20 reps is HARD. Chances are if you can dead hang between reps for 20 reps you have a pretty great physique!


How to use Visual Studio Code on an Android device?

Question: I have Samsung Galaxy Tab S6 and it has cool features to replace laptops, but it is unfortunately running Android OS, and not many development apps are available for Android.
Is there an option to run VS Code at least on an Android device?
Answer: The open-source version of VS Code is called code-server. To run it on Android (without root) you will need:
Termux from F-Droid as changes to the Google Play Store policies are no longer compatible with Termux releases.
2023 Update
For an easier install use the Termux-User-Repository
From: https://github.com/coder/code-server/issues/5745

pkg install tur-repo
pkg install code-server

Old Instructions
Once running Termux you will need to install a bunch of packages as code-server is an Electron app and needs support from nodejs.
pkg install nodejs

pkg install yarn

Per the Termux NodeJS wiki you should probably have installed:
pkg install build-essential

pkg install python

As they are needed for building native extensions.
And finally install code-server itself.
yarn global add code-server

warning installing code-server takes a while
code-server is now installed and will be the back-end for your front-end which will be a Chromium based browser, like Chrome for Android or Microsoft Edge.
code-server

You'll probably want to run the server in the background like code-server &. The ampersand puts the process in the background.
At that point you'll get some logs about where to find the password.
Open up a browser, as I was using Samsung DeX I used Samsung Internet, connect to 127.0.0.1:8080 and enter password.
In my case I used cat ~/.config/code-server/config.yaml to find out what was configured.

As you can see in the screenshot, even the MS Python plugin seems to work (for now).
A Few Caveats

code-server is not Microsoft Visual Studio Code The summary is that not all plugins are supported, YMMV.

I'm using Termux and code-server with Samsung DeX so I don't have any keyboard issues that others have encountered.
Answer: VS Code does not yet exist for Android, so there's no way to run it for now. There are some other good editors though, such as CodeAnywhere that you may be able to use in the meantime.
Answer: There are two ways to use Linux on Android so we can use VS Code :

First easy way (Virtual Network Computing) (VNC):
1. Install a Linux distro via "Termux"
 pkg update -y && pkg install proot wget tar pulseaudio  -y &&  wget https://raw.githubusercontent.com/AndronixApp/AndronixOrigin/master/Rootfs/Ubuntu19/ubuntu19.sh && chmod +x ubuntu19.sh && ./ubuntu19.sh
2. Install Linux GUI desktop environment like "Xfce".
sudo apt-get install xfce4 xfce4-goodies -y
3. start a VNC server on your linux.
sudo apt-get install tightvncserver -y
4. Open "VNC Viewer" on android to start hacking.
you may need to do command vncserver -list to list the port
5. Install vscode for ARM64
6. Optional: Install NodeJS for ARM64.
apt install nodejs

Second hacky way (Linux Natively):

more info:
https://medium.com/@quantvc/running-debian-on-android-device-natively-73545c9b0757
Helpful Resources:
https://play.google.com/store/apps/details?id=studio.com.techriz.andronix
https://play.google.com/store/apps/details?id=com.termux
https://play.google.com/store/apps/details?id=com.realvnc.viewer.android
List of some ARM64 Hackers:
@Lemon1I @boby2001820 @NTAuthority @gus33000
Worth mentioning:
https://github.com/WOA-Project
Comment: The question was not to use but to run VS Code on Android.
Comment: Is there another way to run vscode on android device?
Comment: That worth mentioning link is for advertisement or somehow related to the question or answer?
Comment: Related to ARM64 hackers and projects


Unable to mount btrfs volume

Question: Recently my file server stops working (Centos 7.7).
The btrfs vol "clouddata" unable to mount. The server hangs during mounting it in read-write mode.
I thought space exhausted on it:
<code>    [root@cloud auto]# btrfs fi show
    Label: 'clouddata'  uuid: 90224df7-9d85-48f7-8cb5-a6689fc4f0a5
    Total devices 1 FS bytes used 12.42TiB
    devid    1 size 14.45TiB used 12.84TiB path /dev/sda5
</code>
14.45 TB disk is hardware RAID10 on DELL R740xd. All drives are OK.
Mount options:
<code>    /dev/sda5 /data01 btrfs compress=lzo,discard,clear_cache,subvol=data01   0 2
</code>
I can mount it in read-only.
Other partitions using ext4 file system.
Btrfs was chosen for "clouddata" because of snapshots .
Server log-files:
<code>    [  169.678015] BTRFS: error (device sda5) in maybe_insert_hole:4859: errno=-17 Object already exists
    [  169.678102] BTRFS info (device sda5): forced readonly
    [  169.678168] BTRFS warning (device sda5): Skipping commit of aborted transaction.
    [  169.678178] BTRFS: error (device sda5) in cleanup_transaction:1851: errno=-17 Object already exists

    [root@cloud cifs]# btrfs --version
    btrfs-progs v4.9.1
</code>
The command "btrfs check --repair /dev/sda5" failed with:
<code>    Feb  2 22:58:09 cloud kernel: Out of memory: Kill process 2321 (btrfs) score 946 or sacrifice child
    Feb  2 22:58:09 cloud kernel: Killed process 2321 (btrfs), UID 0, total-vm:23160652kB, anon-rss:15259688kB, file-rss:176kB, shmem-rss:0kB
</code>
Is it free space problem? How to delete all snapshots on unmounted volume?
There were no power outage.
Answer: Zero-log resolved this situation. However btrfs-wiki not recommend using it.
I'm switching back to zfs on FreeBSD.

Unable to mount btrfs volume


Unable to login User credentials -Eucalyptus

Question: We are trying to download user credentials by entering into Eucalyptus management console but couldn't do so.As we are entering USERNAME and PASSWORD as admin into the management console ,its not accepting it and showing the error "Invalid user/account name and/or password". All the ports are Listening. So please anyone tell what valid data to give input for Account name, username and password.Thanks in advance.Unable to login Eucalyptus management console
Answer: You would have entered password during eucalyptus installation. The default is eucalptus, admin and password. You will have the credentials at eucarc file too. Hope it helps !!


how to draw automata in java

Question: i want to draw an automata with edges and circulaire states, something like this                                                http://pop-art.inrialpes.fr/~girault/Cours/Automates/td5.html, have u an example for that
Comment: @DanRedux: so? I translated it into German, and it was "Kugelspiel", which is the common name for that kind of automaton.
Comment: Another option: generate a .dot file from java, and let http://www.graphviz.org do the rendering in whatever image format you like.
Comment: I translated this to english and the second link said "Set of balls"..
Comment: what I wanna do is draw an automata like this http://www.google.com/imgres?hl=en&biw=1280&bih=643&tbm=isch&tbnid=q62yfBg-2QjZ5M:&imgrefurl=http://pop-art.inrialpes.fr/~girault/Cours/Automates/td5.html&docid=6Ro8kL90vJ_XYM&imgurl=http://pop-art.inrialpes.fr/~girault/Cours/Automates/determine-solution.gif&w=404&h=317&ei=nDmbT634GunH0QX_2_SYDw&zoom=1&iact=hc&vpx=190&vpy=148&dur=321&hovh=199&hovw=254&tx=151&ty=114&sig=100406407692710228905&page=1&tbnh=137&tbnw=175&start=0&ndsp=16&ved=1t:429,r:0,s:0,i:68
Comment: The graphs are probably drawn using LaTeX, so maybe you can use that: generate a `.tex` file from Java and let `latex` do the hard work.
Answer: JGraph is a library you can use that is native to Java and fairly easy to use, or you can generate a <code>.dot</code> file and let GraphViz take care of it for you.
Answer: If you dont want to carry for things like representing the graph in a correct way such you try to not cross the lines, or to not have two or more nodes in the same position then i suggest you to use grail graph library so you can see the graph using yed works (I can provide you an example of it just write the regular expression you in comment), or if you want to draw the graph by yourself then you probably is good to learn about Layered graph drawing :
http://en.wikipedia.org/wiki/Layered_graph_drawing
and Coffman Graham algorithm
http://en.wikipedia.org/wiki/Coffman%E2%80%93Graham_algorithm
Comment: Aha, i think you have a lot of work to do here. I have done something like that in this way: first I have created an ANTLR specification grammar for valid regular expressions, and the AST as well. Then using the parser and lexer i got from antlr i got a specific CommonTree for each regular expression, I have traversed that tree and built the NFA first (using the Thompson algorithm). When you have NFA, using the subset construction algorithm you can create the DFA graph.
Comment: thank you for your answer, in fact, im trying to parse an XMl file , and after that l have to generate the regular expression for the XML file , after that i have to draw the automata, there is an example in this post http://stackoverflow.com/questions/10395825/create-a-regular-expression-using-data-extracted-from-an-xml-file

how to draw automata in java


Preparing a fresh bag of spinach: To Stem or Not To Stem

Question: In the past I have always de-stemmed my fresh spinach leaves.  But I am wondering, is that necessary?  I'd like to prepare as-is.
Comment: I concur with Wayfaring Stranger, so I'd say that usually it's best to remove the stems. If you want to avoid the waste *and* avoid stringiness you could remove the stems and dice them up. Add the diced stems with the leaves to whatever you're making.
Comment: It will depend upon the spinach. The size and toughness of the stems varies even more than the leaves. It's certainly not *necessary* to remove the stems, but if the stems are tough, they are very noticeable.
Comment: I only wonder if anyone else here has had success in not removing them.  I've read elsewhere online that [de-]stemming is unnecessary.
Answer: In my experience, stems can be rather stringy even after cooking. Likely varies by time of year, age/size of leaves, soil type, cultivar etc.
Best adivice is probably to check a few stems (raw, steamed, whatever) and see.
I always cut stems off at the base of the leaf, and have yet to have a complaint about the stem bits within the leaves.
Answer: When I cook wilted spinach with garlic and lime, I never remove the stems…  The thought never even crossed my mind.
Answer: For 2 people I use a large box of baby spinach. To take the stems if that much spinach would take more time than I have or am willing to spend. I don't notice the stems at all when eaten. For salad, I do take off stems.
Comment: Where I live that older spinach is never being sold in the shops. If it is used at all it is used to make frozen spinach, so that may be the reason for the different answers.
Comment: Baby spinach tends to have tender stems.  It's the larger, older spinach where it's more significant


Can I use long reach calipers on my cyclocross bike?

Question: I've got cx bike(Centurion Cyclocross 4000) which I currently use only for commuting and riding long distances on a road. Is it possible to use some longreach caliper brakes on it (e.g. Shimano BR-650 or Tektro R538)?
Comment: Does the frame (and fork) have mounting holes for caliper brakes?
Comment: http://www.cx-sport.de/sites/default/files/Centurion%20Cyclo%20Cross%204000_2012.jpg - seems to indicate drilling for caliper on fork, hard to tell if it is drilled on the frame.
Comment: There are holes both on the frame and the fork.
Answer: I've just looked at the Centurion website and it's not clear from the pics or the German specs whether the frame and forks have caliper mounting holes. Look for a hole in the centre of the fork to take the caliper, and a corresponding one in the centre of the rear cross-brace above the wheel.
If those are there you can use caliper brakes of some kind, if you can get ones with the appropriate reach.
Bear in mind that you may also need to change the levers to pull a different amount of cable, or use some kind of adapter.
Comment: Thanks for your reply. There are holes both on the frame and the fork, that is why I'm asking.


How do I multi-entry Column Default Values in SharePoint 2013 Document Library?

Question: There are 12 monthly folders, one for each month. I want to set default values in each for automation operations. Current method I am using:

Go into the Library Setting
Click in Column Default Value Setting
Select one folder at a time and enter default values

What I want to know:
Is there a way to select all folders and enter their respective default values?
Background reference:
I know it is easy to create multiple folders using windows command lines; by writing "md 'folderName1' 'folderName2' etc, I save time from individually creating each folder in the file explorer. I want to know if similar shortcut approach is available for managing Column Default Values in Document Library of SharePoint 2013.
Answer: No, there is no API or way that I have found to make this painful, but albeit important, process better or faster.


Bridge hand Combination/Permutation

Question: A Bridge hand consists of 13 cards from a deck of 52 cards. In how many ways can a (bridge) hand
consisting of 5 spades(♠), 4 hearts(♥), 4 diamonds(♦) and 0 clubs(♣) be selected?
Answer: There are $13 \choose 5$ ways of choosing $5$ spades.
There are $13 \choose 4$ ways of choosing $4$ hearts.
There are $13 \choose 4$ ways of choosing $4$ diamonds.
So there are $13 \choose 5$$\times$$13 \choose 4$$\times$$13 \choose 4$ ways of selecting a bridge hand with $5$ spades, $4$ hearts, $4$ diamonds, and $0$ clubs.
Answer: A slightly different answer is also possible, depending on whether the question is "how many ways can a (bridge) hand ... be selected", or whether it means how many possible different hands there are. The previous answer is how many possible different hands there are. But how many ways you can select those hands would be 13P5 * 13P4 * 13P4  (not 13C5 * 13C4 * 13C4).
Edit 20160416: Thanks for the comment Thomas - silly mistake by me. It is indeed (13C5*13C4*13C4)*13C1 as you noted.
Comment: This is in error, the number of ways of selecting a hand is $13!$ times the other hands, while your answer is $5!4!4!$ times the original answer.

Bridge hand Combination/Permutation


Change Windows sound volume via the command line

Question: Is it possible to change the volume in Windows XP via the command line?
Comment: AutoHotkey can do this, which you could compile and call from the command line
Comment: Needing a third party tool to set volume. I'm totally affraid.
Answer: NirCmd is an application that does that and more.
Example of use:

Increase the system volume by 2000 units (out of 65535)
nircmd.exe changesysvolume 2000
Decrease the system volume by 5000 units (out of 65535)
nircmd.exe changesysvolume -5000
Set the volume to the highest value
nircmd.exe setsysvolume 65535
Mute
nircmd.exe mutesysvolume 1
Unmute
nircmd.exe mutesysvolume 0
Comment: Was hoping there was a standard Windows method, but this looks very handy. Will accept this if no-one supplies one in the next day or two. Thanks, Harry.
Comment: This apparently also works on Windows 7, as a few now deleted non-answers pointed out earlier.
Comment: NirCmd looks very cool and very handy. Thanks for the tip.
Comment: NirCmd is also great for getting a laptop to mute on every logon - this way it won't accidentally keep making the "ding" sound on the train (which I don't notice because of the headphones until an embarrassing moment when someone gets annoyed enough to point it out.....)
Comment: There's user-friendly interactive [script](https://github.com/elvin-aslanov/Sound/blob/master/sound.bat) I made for simplification that depends on `nircmd`.
Comment: @user373230 page not found
Comment: See more about NirCmd in the [answer below](https://superuser.com/questions/42039/change-windows-sound-volume-via-the-command-line/1736410#1736410)
Answer: Having read these posts and having looked for alternatives I decided to write my own command line utility, called SetVol, to set the volume.  It works a little more simply than what is described in some of the other posts on this page, here are some examples that you would enter at the command prompt:
setvol 75
setvol -10
setvol +12
setvol mute
setvol unmute

There are other options too.  I've released it as freeware, and you are welcome to visit www.rlatour.com/setvol for more information and to download a copy.
Enjoy
Comment: Sure, I can do that - and in fact, just did!  The program has been updated to version 1.2 on the website, you may need to refresh your browser to see the changes. There is now a new parm 'report' that should give you what you want.  Help on the website and in the app explains it use.  Merry Christmas!
Comment: This is brilliant. Thanks very much for this tool !
Comment: Thanks!! However, I REALLY need this for setting the mic volume. (I'm using Java but I don't expect JavaSound to do this.) Can it be added?
Comment: Awesome, thank you!   Feature Request for future: ability to return *current* volume level as an `errorlevel` (so I can save current setting to later restore it)
Comment: (that it say return the current volume level as per ashleedawg's suggestion)
Comment: Thanks Rob for the utility and helping the community. It is just missing one important feature for me which is to control the Alert "Application" speaker. For some reasons, it is reseted on loud after logging in and I just want to quite this one.
Answer: Make the JavaScript files:
echo var oShell = new ActiveXObject("WScript.Shell"); >> volup.js

echo oShell.SendKeys(String.fromCharCode(0xAF)); >> volup.js

echo var oShell = new ActiveXObject("WScript.Shell"); >> voldown.js

echo oShell.SendKeys(String.fromCharCode(0xAE)); >> voldown.js

echo var oShell = new ActiveXObject("WScript.Shell"); >> togglemute.js

echo oShell.SendKeys(String.fromCharCode(0xAD)); >> togglemute.js

Show the volume control, so you can see what you're doing:
sndvol
(or maybe sndvol32)

Change the volume:
cscript voldown.js

Note: I've had this approach work reliably on machines that I've attempted to use it on.  Helen's answer to Sibo Lin's StackOverflow question about this indicates muting isn't reliable, but volume-changing may not be quite as reliable.  I suspect that the level of reliability may be different on different machines.  This approach is using the technology of mimicking a keystroke, and specifically a volume control key on an enhanced media keyboard.  At the time that Windows started supporting this, such a keyboard was basically a little-used frivolous feature that offered functionality that was previously available only with custom drivers.  It wouldn't surprise me if this code was less polished, and less likely to work on some of the various (perhaps older) hardware that's out there.  All that said, I haven't had troubles with it myself.
Credits:

This answer was heavily influenced by Ryan's answer to Sibo Lin's question about changing the volume on the command line.  (Having a good idea of how to do this, I looked for some example on how to get this done.)
I suspect that Ed Wilson's "Hey Scripting Guy!" blog on Microsoft: article about using a cheesy script to set speaker volume may have been the (direct or indirect) inspiration for many people who have suggested this approach.

One caveat: This question has been tagged with Windows XP.  I just tried this in Windows 10.  I know I've used this in Windows 7 (at least enough to test it out).  As I first started to see Microsoft's built-in support for these enhanced keyboards around the time of Windows ME, I would think this is likely to work well win WinXP too.  I don't recall if I actually tested this with that operating system.  Still, if this approach doesn't work well, I don't expect it to cause problematic side effects.
Comment: Thanks for sharing those keycodes! Since my computer already has python installed, I was able to use this on the command line: `pip install SendKeys` (pure Python package for emulating keystrokes), followed by `python -c "from SendKeys import playkeys; playkeys([(0xAE, True), (0xAE, False)])"`, which emulates a single press and release of the volume key. To emulate 100 distinct presses (for example), you can insert `* 100` after the closing `]` and before the final `)`.
Comment: The volup.js scrip never worked on my Windows 10. I suspect String.fromCharCode() does something weird about Unicode translation, and String.fromCodePoint() is not available in Windows Script host.

It worked nicely when I wrote the same thing in VBScript instead of JScript
Answer: Here's an awesome powershell script found here: (Tested on Windows 10 and 8.1 x64)

Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
   // f(), g(), ... are unused COM method slots. Define these if you care
   int f(); int g(); int h(); int i();
   int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
   int j();
   int GetMasterVolumeLevelScalar(out float pfLevel);
   int k(); int l(); int m(); int n();
   int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
   int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
   int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
   int f(); // Unused
   int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio
{
   static IAudioEndpointVolume Vol()
   {
       var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
       IMMDevice dev = null;
       Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
       IAudioEndpointVolume epv = null;
       var epvid = typeof(IAudioEndpointVolume).GUID;
       Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
       return epv;
   }
   public static float Volume
   {
       get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }
       set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); }
   }
   public static bool Mute
   {
       get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
       set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
   }
}
'@

Now to set volume:
[audio]::Volume = 0.4  # 40%
[audio]::Volume = 0.78 # 78%

And to (un)mute:
[audio]::Mute = $true  # Mute
[audio]::Mute = $false # Unmute

Answer: Owing and further simplifying Nircmd
@echo off
rem 65536 is 100%
rem device where zero is the default device
rem left and right
rem supports whole numbers only therefore throws "missing operator" error when specifying 655.36
set /a volume=%1 * 655
nircmd setvolume 0 %volume% %volume%

save it as a .bat file and execute by passing a parameter
eg: sound 60 will set the the sound volume 60%
make sure you put the bat file either next to the nircmd or in %windir% (or define its folder in %path%)
Answer: NirCmd has commands for a specific running app, like:
NirCmd.EXE SetAppVolume  EPyrus.EXE .25 & Rem Set    EPyrus volume to 25 percent
NirCmd.EXE MuteAppVolume EPyrus.EXE  2  & Rem Toggle EPyrus "mute" state

See the author's blogpost


Resolving only to correct subdomain

Question: I've asked this question previously at serverfault.com (what I believe to be the more appropriate site for this question, however, it was closed unanswered moments later and I was referred here.  My question, I have 5 services running on one server.  A webportal to a torrent client on port 8112, a Minecraft server on 25565, a Plex media server on 32400, and apache2 running on port 80.  I currently have a subdomain of a domain I own from godaddy, pointed to my home ip address.  Everything works fine that way.  However, I'd like to have multiple subdomains for each service, but not have them all resolve by just changing the port.  For example.  Right now, if I were to go to minecraft.myaddress.com:32400, I'd be forwared to the plex media server.  Is there a way to keep subdomains from resolving if not the correct name?
Comment: You want the same IP having several names? That can certainly be done, just do it the same way you did for the first one. If that isn't your question, please edit it to make clear what you are after.
Comment: The reason this is off-topic on SF is that SF is intended for _professional_ sysadmins; if it's not something someone would normally be paid to do, it's likely to be off-topic there.
Comment: @vonbrand: It seems fairly clear to me what he's after. He seems to be asking for port-dependent DNS resolution; for example, if you try to connect to minecraft.myaddress.com:32400, he doesn't want it to resolve to his home IP address. I assume what he's _really_ after is to make minecraft.myaddress.com:32400 not work to connect to the media server, so that you have to know to connect to `plex.` in order to reach the media server (for example)
Comment: @cpast, that is port-forwarding somewhere along the line, i.e., extra machines. And I believe that isn't what OP has in mind.  "Resolve to IP only for " just isn't anywhere near what DNS can do (no, it can't be fixed, DNS just doesn't get chapter and verse on _why_ a process is asking for a particular FQDN --> IP mapping, and has no control of what the process does with it afterwards).
Comment: @vonbrand, I think the confusing part is "multiple subdomains for each service". I think he meant "multiple subdomains, one for each service".
Answer: No, there is not. The way connections work is that the person connecting first looks up the IP address for that domain name, and only once they get the IP address do they make the connection attempt. The port number only comes into play on the second part; DNS maps domain names to IP addresses, and doesn't know or care what port you plan to connect to.
That said, depending on the protocol, you may be able to configure the server on your box to only serve to the "right" domain names. I know that Apache can be set up to serve different content from the same IP depending on what domain name was entered in, and I believe mail servers are similar. However, this is only possible because HTTP sends the domain name once the connection is established; in general, though, the domain name is only used to find the IP.
Comment: The HTTP protocol includes the target domain in its queries, that is the way a web server can answer to different domains on the same IP with different contents (result of early webhosting, where each domain had to have its own IP, and IPs were starting to get scarce...). The other protocols about which OP asks don't.
Comment: @vonbrand Also, HTTP's inclusion of the domain lets you run a website with multiple subdomains (I actually administer a server that does this: my school's single webserver serves `www.school.edu`, `newspaper.school.edu`, `directory.school.edu`, etc.) [and if you look at the second paragraph, I already said HTTP does this]
Comment: Well, let state this.  If I had three separate physical boxes. 192...1, 192...2, 192...3.  Each hosted a separate service. I.e. media server, web host, minecraft.  I could setup a virtual host file in apache to forward the request to the correct server. But the services are instead on one box.
Comment: @Nicholas: No, you can't set up Apache like that. Apache only handles HTTP requests. Anything using a different protocol can't be handled by Apache. For example, Minecraft uses its own protocol, and Apache can't handle that. Virtual hosts only work because of a very specific feature of HTTP, a feature which isn't present in all other protocols.

Resolving only to correct subdomain


Special method of solution for $A\vec x=\vec b$ where $A$ is a square matrix such that $A^tA$ is diagonal and has full rank?

Question: Is there any special shorter method of solution other than cramer's rule for solving a system of $n$ linear equations in $n$ unknowns $A\vec x=\vec b$ where the square matrix $A$ has the property that $A^tA$ is diagonal and has full-rank i.e. all the diagonal entries of $A^tA$ are non-zero ? ( The solution set is obviously unique , since $rank(A)=rank(A^tA)=n$ ) . Thanks in advance .
Answer: Sure. We have $A^tA=D$ where $D^{-1}$ is straightforward, so $Ax=b$ implies $A^tAx=A^tb$ and $x=D^{-1}A^tb$ right away.
Comment: Nice one , but can we do it without even doing $A^t$ ?
Answer: Cramer's rule is not preferred for the high computational cost, involving $n+1$ determinants of $n \times n$ matrix to calculate.
One standard method for solving a general system of linear equations is to compute its row reduced echelon form by Gaussian elimination.
If, in particular, the system is a square one, you can also perform the $LU$ factorization to obtain $PA = LU$ and use the so-called backward-and-forward substitution.
Moreover, if $D = A^tA$ is diagonal and full rank, we can solve directly $Dx = A^tb$ to obtain $x = D^{-1}(A^tb)$, where $D^{-1}c$ can easily be computed as
$$D^{-1}c = (\frac{c_1}{d_1}, \frac{c_2}{d_2}, \ldots, \frac{c_n}{d_n})^t$$


Bootstrap 3: toggle off-canvas navigation menu doesn't work

Question: I have the following issue. I am developing a website using the Bootstrap3 framework to give it a nice responsiveness. In some of the pages I use the off-canvas navigation menu (example can be found here: http://getbootstrap.com/examples/offcanvas/). When developing locally, it works perfectly (if I make the screen's width small, the menu disappears, a toggle button appears and when clicked, the menu slides from the right).
The problem is when I try to do the same on the server (web hosting: fatcow.com). The toggle button will not trigger the menu sliding. (here an example video: http://screencast.com/t/8dZoW4gK)
When I use 'Inspect element' on Google Chrome, I see that there is some additional code added to the source code of the page.
http://screencast.com/t/59vze3aZd3m
<code><script type="text/javascript" src="//ajax.cloudflare.com/cdn-cgi/nexp/abv=2545410587/cloudflare.min.js"></script>

<style type="text/css">.cf-hidden { display: none; } .cf-invisible { visibility: hidden; }</style>

<script data-module="cloudflare/rocket" id="cfjs_block_1313ed8fefd" onload="CloudFlare.__cfjs_block_1313ed8fefd_load()" onerror="CloudFlare.__cfjs_block_1313ed8fefd_error()" onreadystatechange="CloudFlare.__cfjs_block_1313ed8fefd_readystatechange()" type="text/javascript" src="http://esngreece.gr/cdn-cgi/nexp/abv=980862342/cloudflare/rocket.js"></script>
</code>
I have no idea why this code is added on the  section, but this is the only difference from the localhost, so I suppose there is a js conflict.
Thanks in advance
Answer: That looks like Rocket Loader is impacting it. Have you tried turning that off in your CloudFlare Performance Settings?
Comment: I also thought the same. The magic thing is that without deactivating it, it started working normally after some days. It could be some update on the server, or some cache, I have no idea..


How are thermonuclear weapons possible?

Question: Given the fact that thermonuclear devices are a mix of fission through enriched uranium whose energy initiates the fusion in surrounding deuterium. Question is (how come) fission raises temperature so high that, instead of expansion of gases (possible at few hundred degree Celsius ) fusion in (,ready to expand,) gases is obtained?
Answer:
Given the fact that thermonuclear devices are a mix of fission through
  enriched uranium whose energy initiates the fusion in surrounding
  deuterium

That's not how they are built - and as you surmised, it is unlikely this would work.
When you read the following, try to imagine the thought process that one needed to figure out that this could even work, let alone actually build one!
The key to the h-bomb is the arrangement of the secondary fuel. In early models, this was formed as a cylinder and placed very accurately within the bomb case. When the fisson bomb goes off the first thing that comes out is a burst of x-rays, which bounce around the inside of the bomb casing at the speed of light. The result is that the entire inside of the case begins to glow x-ray hot.
The fuel cylinder is normally coated with a layer of the same material as the bomb casing, or some other heavy metal (often depleted uranium). When this is heated by the x-rays in the case, it begins to explode outward (basic gas law here). Newton's Third Law now comes into play - heavy metal is exploding outward so light lithium deuteride fuel is crushed inward.
In the very center of the fuel is a thin rod of plutonium. As the secondary fuel mass is crushed, its density goes up. A lot. Like hundreds (millions?) of times. What was previously very much less than crititcal mass at normal density suddenly becomes very much fissile. A burst of neutrons is released. These travel into the surrounding lithium deuteride fuel. Neutrons+lithium = tritium. Tritium+Deuterium = fusion + another neutron. Rinse, repeat.
For all of this to work, a couple of things have to be true. Work out from the middle:

the rate that fission reactions in the "sparkplug" in the center of the secondary has to be rapid enough...
that they cause tritium production so that it's available and...
the fusion reactions have to occur fast enough...
that their neutrons complete the production cycle...
rapidly enough that the entire mass has time to explode...
after being compressed...
by the x-rays after they fill the casing...
in the time between the fission bomb going off and the entire bomb being blown apart by its explosion!

Basically, the entire heating, compression and fusion side has to occur much more rapidly than the fission side or the fission bomb would simply blow it apart. The compression is the key, if you don't compress the entire thing down, the density is too low so the travel times of all the bits kills you.
I mentioned that the outside of the fuel cylinder is often covered by depleted uranium, as opposed to lead or steel or something. There's a reason: remember that the fusion process is proceeding because the neutrons from the reactions is creating tritium from lithium and that allows for more fusion. So the explosion proceeds from the center of the fuel outward.
But what happens when it gets to the outer edge? Well, you still have all these fusion neutrons, but no more lithium. Now D-T neutrons are 14.1 MeV, much higher than needed to spark fission in U238. And what happens when neutrons hit uranium? Boom! So by using leftover waste uranium - you don't need to use the good stuff, with these neutrons even rocks will fizz - you get more boom for the buck using a material you need to put there anyway.
I also mentioned early bombs were cylindrical. With modern computers, we can simulate this stuff in 3D so now you're seeing shapes of the secondaries that are more egg-shaped to deal with the fact that one end is slightly further from the primary than the other and use that to conserve the x-rays better so you need a smaller primary and the entire thing fits into a smaller case. This is how you get 10 warheads onto an MX.
It really is quite fascinating.
Answer: This is possible because the fission reactions occur so fast that there is essentially no time for expansion to occur on the same time scale.
In addition, the X-ray-driven implosion reaction that is initiated by the radiation output of the initial fission process also happens so quickly that it too proceeds to completion (triggering the spark plug and hence the fusion processes) before the bomb case has a chance to expand.
In the case of a fission bomb, the expansion of the bomb case and tamper cause the density of the exploding core to fall enough to snuff out the fission, but by that time, the bulk of the energy in the bomb has already been unleashed.

How are thermonuclear weapons possible?


Cedeing a city in the trade screen is now useless

Question: Is there any purpose to having cede a city in the trade screen? Originally cities remained occupied forever until ceding but now they automatically become ceded when becoming a free city or ending a war. Is there any purpose to having cede a city in the trade screen now?
Comment: Are you sure that "ending a war" isn't just having them cede the city in the peace agreement? Otherwise there literally would be no reason to cede, but yes loyalty is one method to getting around this.
Comment: @Shelby115 exactly, "ending a war" automatcally cedes all cities. It never used to work that way, so now what is the point of having an option to cede cities in the trade screen it makes no sense??? I must be a) missing a scenario where this would be useful or b) they forgot to take it out sort of like how they removed defensive pact.
Comment: I mean I have ran into situations where the AI refused to cede a city in the peace agreement, that was before the expansion came out though so I'm not certain if it has changed since the expansion and I missed that part or if you mean Civ 5 when you say "used to work that way".
Comment: @Shelby115 all cities automatically cede when you make peace whether cede is in the trade screen or not. It definitely never used to work that way...
Comment: That must be a bug. Of course, cities I captured in my first game revolted due to loyalty in 3 turns (during the war) so it became useless to keep them at all. Burn, baby, burn!
Comment: @CodeCamper I do see what you mean now, played a game as Mapuche and conquered Poland. At one point I made peace just to check this and I did not notice any negative affects to not getting the cede. I tried to get her to cede a city for a comparison but apparently 62g/turn isn't worth a 2 population city lol.
Comment: @Shelby115 as a further test I reloaded a save of cedeing one city but leaving one unceded cedeing both and cedeing neither... the same thing happens and it appears all cities automatically cede when making peace...
Answer: This is a question that has long haunted Civ 6 players however I think now I may be able to piece together a definitive answer until/unless the mechanic is changed/fixed/removed.
According to Victoria from CivFanatics in this thread, having an AI cede their cities to you following a war has the effect of doubling the warmonger penalty with the only payoff being that the city will count towards your total score. Conversely, if you make a peace deal and do not explicitly demand the city be ceded, you will have the normal warmonger penalty but the city will not count towards your score for number of cities.
The following are paraphrased quotes from Victoria's posts:

I playtested this both in firetuner and the real game. The simple
  answer is that the mechanic is broken.

-

If you capture a city during a war, upon seeking peace
  there are three possible outcomes:

Give the city back and have the warmonger penalty removed for doing
  so
Do not demand the city be ceded: take the e.g. -8 warmonger penalty and keep the city, however the city does not count towards your total
  score
Get them to cede the city to you: the city counts towards your score, but you get an additional -8 warmonger penalty (for -16 total)

-

There is also a bug where if you accept a peace deal on the same turn
  as capturing a city, but before you choose to keep it, it will stay in
  occupied status regardless of whether it is ceded during the peace
  deal.

You will still have a penalty with that civilization for "You occupy one of our cities" whether or not it is ceded. This is an additional diplomatic penalty specific to the civilization to whom the city belongs, on top of the base warmonger penalty.
I can't say what the intended behaviour is for this mechanic; it is poorly explained ingame and penalising players for having a city ceded to them is certainly counterintuitive.
In its current state, it would seem that the optimum choice is to avoid accepting ceding of cities and instead taking more gold or resources as part of a peace deal. Players should also avoid making peace before choosing to 'keep' a city, to avoid a bug where cities are locked into 'occupied' status.
Comment: Amazing that they can't fix such an obvious issue.
Answer: This has been changed in Gathering Storm. Now there are two options:

The city is ceded and goes to the conquerer
The city is returned to the player it was taken from.

It is no longer possible to take a city without the owner ceding it, so the question is now moot.


how to make fft ignore phase shift when only interested in magnitude

Question: I have a signal that consists of a sine wave, on which I apply a rectangular window and then an FFT. I'm only interested in the magnitude of the sine wave, and I want it to stay the same even if the signal shifts a few samples to the right relative to the window (of course assuming the sine wave has the same amplitude from top to bottom). Is this possible and how can this be done best? The application is a kind of pitch detector where I have to detect a small group of different pitches.
Comment: Pitch detection algorithms (cepstrum,  YAAPT, RAPT, harmonic product, weighted autocorrelation, etc.,) usually don't require exact magnitudes independent of phase.
Answer: You can't make an FFT ignore phase (for strictly real input), except for signals which have frequencies that are exactly periodic in the FFT window length.
Otherwise, you will have to interpolate to get any between bin magnitude peaks.  And an accurate magnitude interpolation of any non-bin-centered frequency will depend on phase (easiest if you reference phase to the center of the data window), especially near the DC or Fs/2 bins, but to a much smaller extent, thru the rest of the FFT result as well.
Answer:
I'm only interested in the magnitude of the sine wave, and I want it
  to stay the same even if the signal shifts a few samples to the right
  relative to the window

The absolute magnitude of the DFT result will be independent of the phase shift. Each DFT bin will give you a complex number of the form $A \ e^{j \ \theta}$. Circularly shifting your tone will only affect $\theta$. If you take the absolute magnitude, you will end up with $|A|$, all the while ignoring the phase.


Roles only restrict data, while Profiles restricts most everything else?

Question: Is this a fair assessment to say that Role only restricts data, while Profiles can be used to restrict most everything else, like UI, Object and field permissions, functional capabilities?
Comment: NB - Salesforce uses a *permissive* sharing model, not a *restrictive* one. It is impossible to restrict access beyond the `Org-Wide Default` access level.
Answer: Roles :  Roles control Records
OWD is the foundation which decides whether our data is setup in Private / Public Read Only or Public Read Write. This is the most restrictive data setting.
When the OWD is Private, Sharing Rules become available to open up the OWD data restrictions to groups of users or roles and subordinates. These can either be ownership based or criteria based(with some limitations)
Another way to share data is through Apex sharing where you can programmatically insert share records based on custom logic too complex to encapsulate as Criteria Based Sharing Rules.
User Role Hierarchy
Profiles :
Profiles control what you can do with the data that is visible to you, certain administrative permissions and of course which objects in the schema you have access to.
Field Level security for example lets you control at a Profile Level which fields are visible or read only to certain profiles.
The View All Data and Modify All data permissions on the Profile are exceptions because they bestow 'SuperCow Powers' on the users with that Profile. Hence why they are normally granted only to Full System Admins.
See User Profile Permissions
Permissions sets:
Permissions sets are a way to provision profile permissions in a modular fashion so you can group a bunch of related permissions. Permission sets supplement the permissions already granted to a user by virtue of their user profile.
Additionally Profiles also control which Apex Classes and Visualforce pages you have access to.
Profiles and Permission Sets are essentially the same container with only one key difference - a user may have one and only one profile but that same user may have 0, 1, or many permission sets.
Comment: And, of course, in addition to apex sharing, sharing rules, and roles, there's implicit sharing, parent sharing, territory sharing, etc. It only takes one sharing reason to have access to a record, and that's not necessarily by ownership.
Comment: Thanks!  Okay I see it.  Roles grant, not restrict, and only for data, yes?  In the MVP scheme would it be too far a stretch to say Roles are used to control security of the model, and Profiles and Permission sets for the view and controller?
Answer: What? No.
Roles do not restrict anything they only grant you access. Think about a blank profile with nothing checked in object or UI things like API access or being able to email or run reports. You cannot do anything.
As you check more and more options and more and more objects and fields you can see and do more things so a profile gives you access to what you can do inside Salesforce.
The role with the role hierarchy is what you can see in Salesforce. Sure you can own a record and see it but what about the other people how can you see their records that they own? Based on your role and sharing settings it allows you to see more records.
There are no options in role or profile that restrict only allow. profile allows what you can do, role allows what you can see.
Comment: Your last sentence I think should be the header for trailhead on this subject: "profile allows what you can do, role allows what you can see".  Completely awesome ... clears up a lot.  Thanks!
Comment: Thank you ... I completely had that wrong when i worded the question (in fact I knew that, and should have said "granted permision" instead of "restricted").  Hindsight's 20/20.
Comment: No problem, I hope it cleared it up for you and others.


E, Z designation - what to do when substituents are identical on one side of the double bond?

Question:
Here, A has a greater atomic number than B, which has a greater atomic number than C. To assign E,Z designations you would divide the double bond into left and right portions and assign priorities. On the right side, A > C. However, on the left side, B = B. A (first priority on right side) is simultaneously on the same side and on opposite sides to B (first priority on left side). How would you class this compound then?
Comment: That's right (that is, if you throw away the triple bonds), but there's a catch. First and foremost, **any** nomenclature (not just E,Z) exists to tell apart _different_ things. Your molecule is _identical_, no matter which way you orient those A and C. There is nothing to tell apart.
Comment: How would you classify an ethylene molecule _without_ any substituents? Is it E or Z?
Comment: @IvanNeretin I take it that you mean E,Z nomenclature can permissibly fail to class a molecule?
Comment: How would you classify a _methane_ molecule without any substituents and without any double bonds? Is it E or Z?
Comment: @IvanNeretin I thought that E,Z nomenclature was used for compounds with double/triple bonds.
Answer: When both the substituents are identical on one side of the double bond, the compound does not show geometrical isomerism.
There is no point in using E-Z nomenclature in that case.


How to find people to play Magic the gathering with?

Question: I started playing Magic about six years ago, and I live in a very "Intelligence Deficient" Town. I have tried playing online and I Don't have a game shop nearby. Help me please??????
Answer: It's illegal, but you can always play for free on cockatrice or mws (never tried mws). Look the link in mtgsalvation.com forum (im typing from mobile).
You can also play on mtgo, which is legal, but i think doesn't worth it.
You can also ask your friends to play it too.
Good luck


Need help identifying an unopened LEGO bag - lime green and black pieces

Question: We found an unopened bag of lime green and black pieces. Son does not remember what or where it came from which is odd because he's always eager to assemble sets when he gets them. Looks like some sort of vehicle since there is a windshield, wheels and steering with pieces that are smooth on the outside.
Comment: I fixed the photo links - if I had done that first, it might have been easier to find, as I only went off the first photo.
Answer: 76899-1 Lamborghini Urus ST-X & Lamborghini Huracán Super Trofeo EVO
Based on

Black Brick 1 x 10
Lime Plate 1 x 6
Lime Slope, Curved 8 x 2