Quickies

[categories] [index] [all (457)] [latest]

Apache
  1. # apachectl graceful
    
  2. $ sudo apachectl start
    $ sudo apachectl stop
    $ sudo apachectl restart
    

    or use the LaunchDaemon to start Apache at startup

    $ sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist
    
AppleScript
  1. s.txt

    on f(a, b)
        set l to {}
        set end of l to a+b
        set end of l to a*b
        return l -- { a+b, a*b }
    end f
    
    on run
        set x to 2
        set y to 3
        set result to f(x,y)
        log result
    end run
    

    run the script

    $ osascript s.txt
    5, 6
    
  2. log class of myVariable
    
Bash
  1. no error

    $ echo hello
    $ echo $?
    0
    

    error

    $ asdfg
    $ echo $?
    -bash: 127: command not found
    
  2. $ echo -ne 'x41'
    
C
  1. int n = 1;
    int isLittleEndian = (*(char *)&n == 1);
    
  2. // $ gcc -m32 -fasm-blocks asm.c -o asm
    
    #include <stdio.h>
    
    int main (int argc, char *argv[]) {
    
        int espValue;
    
        _asm {
              mov [espValue], esp;
        }
    
        printf("espValue: %u\n", espValue);
    
        return 0;
    }
    
  3. void x() {
        void *returnAddress = __builtin_return_address(0);
        printf("%p\n", returnAddress);
    }
    

    The level argument is number of frames to scan up the call stack.

    See http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html.

  4. int a[3]= { 1, 2, 3 };
    int len = sizeof(a)/sizeof(*a);
    
Cocoa AppKit
  1. $ /System/Library/CoreServices/talagent -memory_pressure
    
  2. - (void)startPulsing {
        CABasicAnimation* a = [CABasicAnimation animation];
    
        a.keyPath = @"opacity";
        a.fromValue = [NSNumber numberWithFloat:1.0];
        a.toValue = [NSNumber numberWithFloat:0.8];
        a.duration = 1.0;
        a.repeatCount = HUGE_VALF;
        a.autoreverses = YES;
        a.timingFunction = [CAMediaTimingFunction
                            functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
        [self.layer addAnimation:a forKey:@"pulseAnimation"];
    }
    
  3. [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]
    
    [[NSProcessInfo processInfo] processName]
    
  4. NSImage *image = [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kAlertNoteIcon)];
    
  5. [CATransaction begin];
    
    [CATransaction setValue:(id)kCFBooleanTrue
                     forKey:kCATransactionDisableActions];
    
    myLayer.position = CGPointMake(x, y);
    
    [CATransaction commit];
    
  6. NSWorkspace * ws = [NSWorkspace sharedWorkspace];
    NSArray *runningApps = [ws valueForKeyPath:@"launchedApplications.NSApplicationName"];
    
  7. [NSImage imageNamed:NSImageNameComputer]
    
  8. [NSCursor hide];
    [NSCursor unhide];
    [NSCursor setHiddenUntilMouseMoves:YES];
    
  9. NSWorkspace *ws = [NSWorkspace sharedWorkspace];
    BOOL appDidLaunch = [ws launchApplication:@"AnotherApp"];
    
  10. URLNameTransformer.h

    #import <Cocoa/Cocoa.h>
    
    @interface URLNameTransformer : NSValueTransformer {
    
    }
    
    + (Class)transformedValueClass;
    + (BOOL)allowsReverseTransformation;
    - (id)transformedValue:(id)value;
    
    @end
    

    URLNameTransformer.m

    #import "URLNameTransformer.h"
    
    @implementation URLNameTransformer
    
    + (Class)transformedValueClass {
        return [NSString class];
    }
    
    + (BOOL)allowsReverseTransformation {
        return NO;
    }
    
    - (id)transformedValue:(id)value {
        if (value == nil) {
            return value;
        } else {
            NSURL *url = [NSURL URLWithString:(NSString *)value];
            return [url host];
        }
    }
    
    @end
    

    To use it:

    First, register the value transformer

    - (void)awakeFromNib {
        URLNameTransformer *urlTrans = [[[URLNameTransformer alloc] init] autorelease];
        [NSValueTransformer setValueTransformer:urlTrans
                                        forName:@"URLNameTransformer"];
    }
    

    Then, set the value transformer in Interface Builder

    NSValueTransformer

  11. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:myURLString]];
    
  12. - (void)drawRect:(NSRect)dirtyRect {
    
        NSGraphicsContext *context = [NSGraphicsContext currentContext];
    
        [context saveGraphicsState];
    
        [context setShouldAntialias:NO];
    
        // draw here
    
        [context restoreGraphicsState];
    
        [super drawRect:dirtyRect];
    }
    
  13. $ python -c "import AppKit; print AppKit.NSAppKitVersionNumber"
    

    1187.0

  14. [[NSWorkspace sharedWorkspace] selectFile:path inFileViewerRootedAtPath:path];
    
  15. if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_5) {
      /* On a 10.5.x or earlier system */
    } else if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_6) {
      /* On a 10.6 - 10.6.x system */
    } else {
      /* Lion or later system */
    }
    

    http://developer.apple.com/library/mac/#releasenotes/Cocoa/AppKit.html

  16. Download an Xcode demo project: CocoaPython.zip.

    #import
    #import

    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        
        /* initialization */
        
        Py_Initialize();
        
        PyObject *sysModule = PyImport_ImportModule("sys");
        PyObject *sysModuleDict = PyModule_GetDict(sysModule);
        PyObject *pathObject = PyDict_GetItemString(sysModuleDict, "path");
        PyObject_CallMethod(pathObject, "insert", "(is)", 0, "../../");
        
        Py_DECREF(sysModule); // borrowed reference
        
        /* import and instantiate Cat */
        
        // from Cat import *
        PyObject *CatModule = PyImport_ImportModule("Cat");
        
        // c = Cat()
        PyObject *Cat = PyDict_GetItemString(PyModule_GetDict(CatModule), "Cat");
        PyObject *cat = PyObject_CallObject(Cat, NULL);
        
        Py_DECREF(CatModule);
        Py_DECREF(Cat);
        
        /* use Cat instance methods */
        
        // c.scream()
        // c.set_name("charly")
        // c.print_family("jack", "cathy", 4)
        
        PyObject_CallMethod(cat,"scream",NULL);
        PyObject_CallMethod(cat,"set_name", "(s)", "charly");
        PyObject_CallMethod(cat,"print_family", "(ssi)", "jack", "cathy", 4);
        
        // c.is_asleep()
        PyObject *is_asleep = PyObject_CallMethod(cat,"is_asleep",NULL);
        BOOL isAsleep = (Py_True == is_asleep);
        Py_DECREF(is_asleep);
        NSLog(@"%d", isAsleep);
        
        // c.name()
        PyObject *name = PyObject_CallMethod(cat,"name",NULL);
        NSString *catName = [NSString stringWithCString: PyString_AsString(name)];
        Py_DECREF(name);
        NSLog(@"%@", catName);
        
        /* termination */
        
        Py_DECREF(cat);
        Py_Finalize();
        
        [pool release];
        return 0;
    }
Cocoa Foundation
  1. FILE *f = fopen("/bin/ssh", "r");
    if (f != NULL) {
        // jailbreak
    }
    fclose(f)
    
  2. Print some information about a block with the private function:

    char *_Block_dump (block_t block);
    

    sample output:

    ^0xbfffd53c (new layout) =
    isa: stack Block
    flags: HASHELP
    refcount: 0
    invoke: 0x4f85
    descriptor: 0x7ed0
    descriptor->reserved: 0
    descriptor->size: 32
    descriptor->copy helper: 0x4f1d
    descriptor->dispose helper: 0x4ed3
    
  3. static MyClass *sharedInstance = nil;
    
    + (MyClass)sharedInstance {
    
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
        }
    
        return sharedInstance;
    }
    
  4. NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
    
    [queue addOperationWithBlock:^{
        CGFloat n = [self resultOfSomeMassiveComputation];
    
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self updateOnMainThreadWithResult:n];
        }];
    }];
    
  5. // MyClass.h
    extern NSString * const kMyString;
    
    // MyClass.m
    NSString * const kMyString = @"xxx";
    
  6. #ifdef DEBUG
    #define MyLog(fmt, ...) NSLog((@"%@ [Line %d] %s " fmt), [self class], __LINE__, __FUNCTION__, ##__VA_ARGS__);
    #define MyLogError(fmt, ...) NSLog((@"[Error] %@ [Line %d] %s " fmt), [self class], __LINE__, __FUNCTION__, ##__VA_ARGS__);
    #else
    #define MyLog(fmt, ...)
    #define MyLogError(fmt, ...) NSLog((@"[Error] %@ [Line %d] %s " fmt), [self class], __LINE__, __FUNCTION__, ##__VA_ARGS__);
    #endif
    

    but also:

    NSLog(@"-[%@ %s]", isa, SELNAME(_cmd));
    

    -[NSKVONotifying_AppDelegate awakeFromNib]

  7. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        NSLog(@"--");
    });
    
  8. $ OBJC_PRINT_IMAGES=YES /Library/XcodeBuilds/Debug/HelloWorld 
    objc[39331]: IMAGES: processing 28 newly-mapped images...
    
    objc[39331]: IMAGES: loading image for /usr/lib/libobjc.A.dylib (supports GC)
    
    objc[39331]: IMAGES: loading image for /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (supports GC)
    
    objc[39331]: IMAGES: loading image for /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (supports GC)
    
    objc[39331]: IMAGES: loading image for /Library/XcodeBuilds/Debug/HelloWorld
    
  9. /Developer/Extras/64BitConversion/ConvertCocoa64 MyClass.m
    
  10. http://www.fscript.org/

    > NSApplication sharedApplication delegate managedObjectContext inspectWithSystem:sys
    

  11. - (NSString *)stringWithoutComments:(NSString *)string {
        NSArray *inputLines = [string componentsSeparatedByString:@"\n"];
        NSPredicate *commentsPredicate = [NSPredicate predicateWithFormat: @"SELF beginswith %@", @"--"];
        NSPredicate *notCommentsPredicate = [NSCompoundPredicate notPredicateWithSubpredicate:commentsPredicate];
        NSArray *filteredLines = [inputLines filteredArrayUsingPredicate:notCommentsPredicate];
        return [filteredLines componentsJoinedByString:@"\n"];
    }
    
  12. NSString *formattedDate = [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S"];
    

    2006-11-15 00:26:11

  13. [NSThread currentThread]
    
  14. +[NSThread callStackSymbols]
    
  15. NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"];
    
  16. NSString *desktop = [NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
  17. Cache the implementation pointer for -[NSString hasPrefix:]

    SEL hasPrefixSelector = @selector(hasPrefix:);
    BOOL (*hasPrefixIMP) (id, SEL, id) = (BOOL (*) (id, SEL, id))[@"" methodForSelector:hasPrefixSelector];
    

    Use the cached pointer instead of sending the message

    BOOL b = hasPrefixIMP (@"Europe", hasPrefixSelector, @"e");
    
  18. Set values for keys from a dictionary:

    [person setValuesForKeysWithDictionary:d];
    

    Don't raise exceptions when class is not key value coding-compliant for given keys:

    - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
        NSLog(@"-- unhandled key:%@", key);
    }
    
  19. Helps in diagnosing conflicts among classes:

    -OBJC_PRINT_REPLACED_METHODS YES
    
  20. - (instancetype)initWithParam:(id)param;
    - (instancetype)init __attribute__((unavailable("use initWithParam:")));
    
  21. NSDate *startDate = [NSDate date];
    // ...
    NSLog(@"%f seconds elapsed", [[NSDate date] timeIntervalSinceDate:startDate]);
    
  22. void Swizzle(Class class, SEL origSel, SEL newSel) {
        Method origMethod = class_getInstanceMethod(class, origSel);
        Method newMethod = class_getInstanceMethod(class, newSel);
    
        if(class_addMethod(class, origSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
            class_replaceMethod(class, newSel, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        } else {
            method_exchangeImplementations(origMethod, newMethod);
        }
    }
    

    from Mike Ash

    static IMP original_initWithString_;
    
    @implementation NSURL (Ext)
    
    + (void)swizzleMethods { // call this once, early
        original_initWithString_ = method_getImplementation(class_getInstanceMethod([self class], @selector(initWithString:)));
        Swizzle([self class], @selector(initWithString:), @selector(my_initWithString:));
    }
    
    // -[NSURL urlWithString:] will now execute this method
    - (NSURL *)my_initWithString:(NSString *)s {
        NSLog(@"-- my_initWithString: %@", s);
        return original_initWithString_(self, @selector(initWithString:), s);
    }
    
    @end
    
  23. #import <Foundation/Foundation.h>
    
    // gcc -g -Wall -framework Foundation -o nslog nslog.m
    
    int main (void) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        NSLog(@"Hello");
        [pool release];
        return (0);
    }
    
  24. NSArray *addresses = [[NSHost currentHost] addresses];
    NSString *hostName = [[NSProcessInfo processInfo] hostName];
    
  25. NSUInteger dayOfYear = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit
                                                                   inUnit:NSYearCalendarUnit
                                                                  forDate:[NSDate date]];
    
  26. NSProcessInfo *pi = [NSProcessInfo processInfo];
    
    NSLog(@"environment SHELL: %@", [[pi environment] objectForKey:@"SHELL"]);
    NSLog(@"globallyUniqueString: %@", [pi globallyUniqueString]);
    NSLog(@"hostName: %@", [pi hostName]);
    NSLog(@"processIdentifier: %d", [pi processIdentifier]);
    NSLog(@"processName: %@", [pi processName]);
    [pi setProcessName:@"MyProcessNewName"];
    NSLog(@"processName: %@", [pi processName]);
    NSLog(@"operatingSystem: %d", [pi operatingSystem]);
    NSLog(@"operatingSystemName: %@", [pi operatingSystemName]);
    NSLog(@"operatingSystemVersionString: %@", [pi operatingSystemVersionString]);
    NSLog(@"processorCount: %d", [pi processorCount]);
    NSLog(@"activeProcessorCount: %d", [pi activeProcessorCount]);
    NSLog(@"physicalMemory: %qu", [pi physicalMemory]);
    NSLog(@"args: %@", [pi arguments]);
    

    Output:

    environment SHELL: /bin/bash
    globallyUniqueString: F68E72F1-257C-4E93-B23D-BA3A0DD15603-47346-0001600092C640D8
    hostName: nst.local
    processIdentifier: 47346
    processName: Untitled
    processName: MyProcessNewName
    operatingSystem: 5
    operatingSystemName: NSMACHOperatingSystem
    operatingSystemVersionString: Version 10.5.4 (Build 9E17)
    processorCount: 2
    activeProcessorCount: 2
    physicalMemory: 2147483648
    args: (
        "/Library/XCodeBuilds/Debug/Untitled"
    )
    
  27. Show help

    $ export OBJC_HELP=YES
    
    $ /Applications/TextEdit.app/Contents/MacOS/TextEdit
    (...)
    OBJC_HELP: describe available environment variables
    OBJC_PRINT_IMAGES: log image and library names as they are loaded
    OBJC_PRINT_LOAD_METHODS: log calls to class and category +load methods
    OBJC_PRINT_INITIALIZE_METHODS: log calls to class +initialize methods
    OBJC_PRINT_RESOLVED_METHODS: log methods created by +resolveClassMethod: and +resolveInstanceMethod:
    

    Log Objective-C messages

    $ export NSObjCMessageLoggingEnabled=YES
    
    $ /Applications/TextEdit.app/Contents/MacOS/TextEdit
    
    $ tail -f /tmp/msgSends-<pid>
    - NSLock NSLock lock
    + NSThread NSThread currentThread
    - NSThread NSObject hash
    - NSCFArray NSCFArray countByEnumeratingWithState:objects:count:
    - NSLock NSLock unlock
    - NSLock NSLock lock
    + NSThread NSThread currentThread
    - NSThread NSObject hash
    - NSCFArray NSCFArray countByEnumeratingWithState:objects:count:
    - NSLock NSLock unlock
    
  28. NSDictionary *errors;
    NSAppleScript *quitApp;
    
    quitApp = [[NSAppleScript alloc] initWithSource:@"tell application \"AnotherApplication\" to quit"];
    [quitApp executeAndReturnError:&errors];
    [quitApp release];
    
    if(errors != nil) {
       // manage error
    }
    
  29. Random int between 0 and N

    NSUInteger r = arc4random_uniform(N);
    

    Random int between 1 and N

    NSUInteger r = arc4random_uniform(N - 1) + 1; // no modulo biais
    

    Random double between 0 and 1

    srand48(time(0));
    double r = drand48();
    

    Source: http://nshipster.com/random/

  30. NSString *s = @"Hello World!";
    NSString *re = @".*l{2}.*";
    NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", re];
    
    NSLog(@"Match: %d", [p evaluateWithObject:s]);
    
  31. Two methods to be added to a NSString category:

    -[NSString captureRegex:]

    - (NSString *)captureRegex:(NSString *)pattern {
    
        NSError *error = nil;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:&error];
        if(regex == nil) {
            NSLog(@"-- %@", error);
            return nil;
        }
    
        NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
        if(rangeOfFirstMatch.location == NSNotFound) return nil;
    
        return [self substringWithRange:rangeOfFirstMatch];
    }
    

    -[NSString matchRegex:]

    - (BOOL)matchRegex:(NSString *)pattern {    
    
        NSError *error = nil;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
        if(regex == nil) {
            NSLog(@"-- %@", error);
            return NO;
        }
    
        NSUInteger n = [regex numberOfMatchesInString:self options:0 range:NSMakeRange(0, [self length])];
        return n == 1;
    }
    
  32. http://regexkit.sourceforge.net/RegexKitLite/

    #import "RegexKitLite.h"
    

    -[NSString captureRegex:]

    - (NSString *)captureRegex:(NSString *)regex {
        NSRange searchRange = NSMakeRange(0, [self length]);
        NSError *error = nil;
        NSRange matchedRange = [self rangeOfRegex:regex options:(RKLMultiline|RKLDotAll) inRange:searchRange capture:1 error:&error];
        if(error) SQLogError(@"-- error: %@", error);
    
        NSString *result = nil;
        if( (matchedRange.location + matchedRange.length) <= [self length] ) {
            result = [self substringWithRange:matchedRange];
        }
    
        return result;
    }
    

    -[NSString matchRegex:]

    - (BOOL)matchRegex:(NSString *)regex {
        NSArray *matches = [self componentsMatchedByRegex:regex];
        return [matches count] == 1;
    }
    
  33. Remove the performSelector may cause a leak because its selector is unknown warning:

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:@selector(xxx)];
    #pragma clang diagnostic pop
    

    Remove the "Undeclared selector" warning:

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wundeclared-selector"
    [self performSelector:@selector(xxx)];
    #pragma clang diagnostic pop
    
  34. #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        CFUUIDRef uuid = CFUUIDCreate(NULL);
        NSString *uniqueString = (NSString *)CFUUIDCreateString(NULL, uuid);
        CFRelease(uuid);
    
        NSString *tempFile = [NSString pathWithComponents:
            [NSArray arrayWithObjects: NSTemporaryDirectory(), uniqueString, nil]];
        [fileManager createFileAtPath:tempFile contents:nil attributes:nil];
        NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath:tempFile];
    
        NSTask *task = [[NSTask alloc] init];
        [task setLaunchPath:@"/usr/bin/perl"];
        [task setArguments:
            [NSArray arrayWithObjects:@"/Users/nst/bin/iso2txt",
                                      @"/Users/nst/Desktop/asd.iso2709",
                                      nil]];
        [task setStandardOutput:file];
        [task launch];
        [task waitUntilExit];
        [task release];
    
        NSLog([NSString stringWithContentsOfFile:tempFile]);
    
        [fileManager removeFileAtPath:tempFile handler:nil];
    
        [pool release];
        return 0;
    }
    
  35. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_0) {
        // <= 6.0
    } else {
        // > 6.0
    }
    
  36. #include <Foundation/NSDebug.h>
    
    [NSAutoreleasePool showPools];
    

    the following function performs the same action:

    _CFAutoreleasePoolPrintPools();
    

    output:

    - -- ---- -------- Autorelease Pools -------- ---- -- -
    ==== top of stack ================
      0x583f3c0 (__NSDate)
      0x583f350 (Measure)
      0x5a24960 (UIWindow) (...)
    ==== top of pool, 23 objects ================
    ==== top of pool, 0 objects ================
    ==== top of pool, 0 objects ================
    - -- ---- -------- ----------------- -------- ---- -- -
    
  37. +(MyClass *)sharedInstance {
        static MyClass *sharedInstance = nil;
        static dispatch_once_t pred;
    
        dispatch_once(&pred, ^{
            sharedInstance = [[MyClass alloc] init];
        });
    
        return sharedInstance;
    }
    
  38. [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
    
  39. When encountering the error message

    "Variable is not assignable (missing __block type specifier)"
    

    consider actually using the __block type specifier, so that the variable always live in the scope of the blocks declared within the variable lexical scope, and also in the copies of these blocks. It also means that the address of the variable may change over time. See Blocks Programming Topics for more.

    + (NSString *)myMethodWithDictionary:(NSDictionary *)d {
    
        __block NSString *s = nil; // s lives in block storage
    
        [d enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {    
            if( /* condition here */ ) {
                *stop = YES;
                s = @"xxx";
            }
        }];
    
        return s;
    }
    
  40. Thread safe code to be run only once with all other thread waiting at the barrier:

    static dispatch_once_t onceToken;
    
    dispatch_once (&onceToken, ^{
        // ...    
    });
    
  41. $ NSObjCMessageLoggingEnabled=YES /Library/XcodeBuilds/Debug/HelloWorld 
    2009-02-04 10:54:41.728 HelloWorld[39133:10b] Hello, World!
    
    $ cat /tmp/msgSends-39133 
    + NSRecursiveLock NSObject initialize
    + NSRecursiveLock NSObject new
    + NSRecursiveLock NSObject alloc
    ...
    

    Tracing can be activated selectively in code:

    #import <objc/runtime.h>
    
    instrumentObjcMessageSends(YES);
    // messages will be traced here
    instrumentObjcMessageSends(NO);
    
  42. http://en.wikipedia.org/wiki/Universally_Unique_Identifier

    + (NSString *)randomString {
        CFUUIDRef cfuuid = CFUUIDCreate (kCFAllocatorDefault);
        NSString *uuid = (NSString *)CFUUIDCreateString (kCFAllocatorDefault, cfuuid);
        CFRelease (cfuuid);
        return [uuid autorelease];
    }
    

    CFC4B6BA-26C9-4149-89C1-77C2C4865A72

    See also $ uuidgen

  43. dump the headers

    $ class-dump /System/Library/Frameworks/InstantMessage.framework/Versions/A/InstantMessage > InstantMessage.h
    

    add the framework and the headers to the project

    #import "InstantMessage.h"
    

    class-dump

  44. SInt32 MacVersion = 0;
    BOOL isRunningSnowLeopard = NO;
    
    if (Gestalt(gestaltSystemVersionMinor, &MacVersion) == noErr) {
        isRunningSnowLeopard = (MacVersion == 6);
    }
    
    NSLog(@"isRunningSnowLeopard %d", isRunningSnowLeopard);
    
Cocoa UIKit
  1. #if TARGET_OS_IPHONE
    #import <UIKit/UIKit.h>
    #else
        @compatibility_alias UIColor NSColor;
    #endif
    
  2. [[NSUserDefaults standardUserDefaults] setObject:@YES forKey:@"UIUseLegacyUI"]
    

    https://twitter.com/stroughtonsmith/status/384679231730761728

  3. - (UIImage *)image {
        UIGraphicsBeginImageContext(self.frame.size);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
    }
    
  4. - (void)applicationDidFinishLaunching:(UIApplication *)application {
        application.statusBarHidden = YES;
        // ...
    }
    
  5. [UIApplication sharedApplication].idleTimerDisabled = YES;
    
  6. #ifdef DEBUG
    [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:application
                                   selector:@selector(_performMemoryWarning)
                                   userInfo:nil
                                    repeats:YES];
    #endif
    
  7. po [UIView recursiveDescription]
    

    results:

    <UIView: 0x4b4d3d0; frame = (0 20; 320 460); (...)
       | <MyView: 0x4b4b800; frame = (20 20; 237 243); (...)
       |    | <UIRoundedRectButton: 0x4b4e790; (...)
       |    |   | <UIButtonLabel: 0x4b4f190; (...)
    
CVS
  1. $ cvs co -r TagName ProjectName
    
  2. $ cvs status -v project.pbxproj
    
  3. $ cvs log -wnicolas -d"2006-04-01<2006-05-01" -S
    
  4. $ find -d . -name 'CVS' -exec rm -rf '{}' \; -print
    
DTrace
  1. $ cat objc_calls.d
    pid$target::*ClassDisplay*:entry {}
    pid$target::*ClassDisplay*:return {}
    

    Trace Objective-C messages on Class Display

    $ sudo dtrace -s objc_calls.d -F -c ./RuntimeBrowser
    dtrace: script 'objc_calls.d' matched 64 probes
    CPU FUNCTION
      0  -> +[ClassDisplay classDisplayWithClass:]
      0    -> -[ClassDisplay setRepresentedClass:]
      0    <- -[ClassDisplay setRepresentedClass:]
      0  <- +[ClassDisplay classDisplayWithClass:]
      0  -> -[ClassDisplay setDisplayPropertiesDefaultValues:]
      0  <- -[ClassDisplay setDisplayPropertiesDefaultValues:]
      0  -> -[ClassDisplay header]
      0    -> -[ClassDisplay setRefdClasses:]
      0    <- -[ClassDisplay setRefdClasses:]
    (...)
    
fink
  1. $ fink -b install <package_name>
    
gdb
  1. (gdb) inf files
    Symbols from "/private/tmp/hello".
    Mac OS X executable:
        /private/tmp/hello, file type mach-o-le.
        Entry point: 0x000000f4
        0x00000000 - 0x00000042 is LC_SEGMENT.__TEXT in /private/tmp/hello
        0x000000e8 - 0x00000128 is LC_SEGMENT.__TEXT.__text in /private/tmp/hello
    
  2. (gdb) break setPassword:
    (gdb) break -[Person setPassword:]
    
    (gdb) po self
    <Person: 0x10010c7a0>
    (gdb) po [invocation debugDescription]
    Some day, NSInvocation will have a useful debug
    (gdb) p (char *)_cmd
    $1 = 0x10fbb "setPassword:"
    
    (gdb) frame
    (gdb) info locals
    (gdb) info (classes|selectors) [regex]
    (gdb) list +[Person string]
    (gdb) call [self setPassword:@"welcome"]
    
    (gdb) where
    #0  0x0000b4b3 in -[AppDelegate application:didFinishLaunchingWithOptions:] (...)
    #1  0x00444c89 in -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] ()
    #2  0x00446d88 in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] ()'),
    
  3. (gdb) thread apply all where
    
  4. (gdb) info args
    self = (AppController *) 0x12b9f0
    _cmd = (SEL) 0x12f33
    aNotification = (NSNotification *) 0x264a320
    

    i386 - on the stack

    (int *)($ebp+8)     self
    (int *)($ebp+12)    cmd
    (int *)($ebp+16)    arg2
    (int *)($ebp+20)    arg3
    (int *)($ebp+24)    arg4
    (int *)($ebp+28)    arg5
    
    (int *)$eax         return address
    

    ex: (gdb) po *(int*)($ebp+8)

    i386 - in registers

    $esi       self
    $edx       cmd
    $ecx       arg2
    

    x86_64 - in registers

    $rdi          self
    $rsi          cmd
    $rdx          arg2
    $rcx          arg3
    $r8           arg4
    $r9           arg5
    
    $rax          return address
    

    ex: (gdb) po $rax

Git
  1. # Exclude the build directory
    build/*
    
    # Exclude temp nibs and swap files
    *~.nib
    *.swp
    
    # Exclude OS X folder attributes
    .DS_Store
    
    # Exclude user-specific Xcode 3 and 4 files
    *.mode1
    *.mode1v3
    *.mode2v3
    *.perspective
    *.perspectivev3
    *.pbxuser
    *.xcworkspace
    xcuserdata
    
  2. $ git add -u
    
  3. $ git shortlog -n -s
    
  4. $ git push --delete origin MY_TAG
    
  5. $ git commit --amend -m "new message"
    
  6. Works with GitHub:

    $ git pull
    $ git tag -d THE_TAG
    $ git push origin :refs/tags/THE_TAG
    $ git tag THE_TAG
    $ git push origin THE_TAG
    

    Source: http://www.nax.cz/2011/01/15/move-a-remote-git-tag/

  7. Add an alias to display pretty logs

    $ git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    

    Display pretty logs

    $ git lg
    

    Display the lines that changed

    $ git lg -p
    

    Source: http://coderwall.com/p/euwpig?i=3&p=1&t=git

  8. $ git reset --hard
    
  9. #!/usr/bin/sh
    
    ORIGIN=$HOME'/Dropbox/dropbox.git'
    CLONE=$HOME'/Projects/dropbox'
    
    mkdir -p "$ORIGIN"
    cd "$ORIGIN"
    git init --bare
    
    git clone "$ORIGIN" "$CLONE"
    
    cd "$CLONE"
    touch test.txt
    git add test.txt 
    git commit -m "Initial commit"
    git push origin master
    
  10. $ echo 'opendiff "$2" "$5" -merge "$5"' > ~/bin/opendiff-git.sh
    $ chmod a+x ~/bin/opendiff-git.sh
    $ git config --global diff.external ~/bin/opendiff-git.sh
    

    Now, git diff should open FileMerge:

    $ git diff
    
Gnuplot
  1. Gnuplot cumulative flow chart

    loc.txt

    # date      iphone  common  ipad    xxx
    2010-02-08  9370       0       0       0    # iphone 1.0
    2010-04-22  9602       0       0       0    # iphone 2.0
    2010-06-03  9602    1354    4820       0    # ipad 1.0
    2010-10-07  9602    1869    5536       0    # ipad 2.0
    2011-03-01  8892    4041    9356    6046    # xxx 1.0
    2011-05-06  8648    5973    6960    6046    # iphone 3.0
    

    loc.gp

    set terminal png size 600, 350
    
    set output "loc.png"
    
    set title "Projects Lines of Code"
    set key left
    
    set timefmt "%Y-%m-%d"
    set format x "%Y-%m-%d"
    set grid
    
    set xdata time
    set xtics rotate by -45
    set xrange ["2010-03-01":"2011-06-01"]
    
    plot "loc.txt" using 1:($5+$4+$3+$2) title "xxx" with filledcurves y1=0 lt rgb "#cc3333", \
         "loc.txt" using 1:($4+$3+$2) title "iPad" with filledcurves y1=0 lt rgb "#cc9933", \
         "loc.txt" using 1:($3+$2) title "Common Lib" with filledcurves y1=0 lt rgb "#669933", \
         "loc.txt" using 1:2 title "iPhone" with filledcurves y1=0 lt rgb "#336699"
    

    Drawing the chart

    $ gnuplot loc.gp && open loc.png
    
  2. gnuplot heatmap

    map.txt

    n_0_0   , n_0_1   , ..., n_0_100
    ...
    n_2682_0, n_2682_1, ..., n_2682_100
    

    heatmap.gp

    set terminal png
    set output "heatmap.png"
    set size ratio 0.5
    set title "USD/CHF: PnL following daily trend, in pips"
    
    set xlabel "SL/TP - 200"
    set ylabel "Days since 2007-01-01"
    
    set tic scale 0
    
    set palette rgbformulae 22,13,10
    set palette negative
    
    set cbrange [-10000:10000]
    #unset cbtics
    
    set xrange [0:99.5]
    set yrange [0:2683]
    
    set view map
    
    splot 'map.txt' matrix with image
    

    Drawing the map

    $ gnuplot heatmap.gp && open heatmap.png
    
Google
  1. Append the KML url to https://maps.google.com/maps?q=.

    Example: https://maps.google.com/maps?q=http://seriot.ch/temp/radars.kml

  2. $ sudo echo "127.0.0.1       pagead2.googlesyndication.com" >> /etc/hosts
    
GPG
  1. encrypt

    $ gpg -c file.txt
    

    decrypt

    $ gpg file.txt.gpg
    
iCal
  1. $ defaults write com.apple.iCal "Default duration in minutes for new event" 15
    
  2. $ defaults write com.apple.iCal IncludeDebugMenu YES
    
ImageMagick
  1. $ convert picture.jpg \
    \( +clone -background black -shadow 70x4+5+5 \) +swap \
    -background none -flatten -trim +repage picture.png
    
  2. $ convert foo.png -resize 500x400 -background white -flatten foo.jpg
    

    Source: http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=8359

iOS
    1. take a screenshot with cmd-alt-4-space
    2. open it in Acorn
    3. go to menu Image > Crop
    4. from 47 151
    5. size 320 460
  1. from PIL import Image
    
    LEFT = 38
    TOP = 146
    WIDTH = 320
    HEIGHT = 460
    
    img = Image.open('sc.png')
    box = (LEFT, TOP, LEFT+WIDTH, TOP+HEIGHT)
    area = img.crop(box)
    
    area.save('sc2.png')
    
  2. #import <QuartzCore/QuartzCore.h>
    ...
    view.layer.borderColor = [UIColor blackColor].CGColor;
    view.layer.borderWidth = 1;
    
  3. $ rvictl -s UDID
    $ sudo launchctl list com.apple.rpmuxd
    $ sudo tcpdump -n -t -i rvi0 -q tcp
    
  4. $ codesign -d --entitlements - MyApp.app
    

    the result should include:

    <key>aps-environment</key>
    <string>production</string>
    
  5. With an iPhone, dial and call:

    *3001#12345#*
    
  6. $ echo "mov r0, 0; bx lr" | llvm-mc -assemble -triple=armv7 -show-encoding
    .text
    mov r0, #0                  @ encoding: [0x00,0x00,0xa0,0xe3]
    bx  lr                      @ encoding: [0x1e,0xff,0x2f,0xe1]
    

    ARM Thumb mode:

    $ echo "mov r0, 0; bx lr" | llvm-mc -assemble -triple=thumbv7 -show-encoding
    .text
    mov.w   r0, #0                  @ encoding: [0x4f,0xf0,0x00,0x00]
    bx  lr                      @ encoding: [0x70,0x47]
    

    See also iOS binary patching: http://www.zdziarski.com/blog/?p=2172

  7. Add them into scheme > arguments

    -AppleLanguages (de)
    -AppleLocale fr_FR
    
  8. po [[[UIApplication sharedApplication] keyWindow] recursiveDescription]
    
  9. $ export CODESIGN_ALLOCATE=/usr/bin/codesign_allocate
    $ codesign -fs "MyName" MyBinary
    
  10. if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
        // ...
    }
    
iTunes
  1. $ defaults write com.apple.dock itunes-notifications -bool TRUE
    
Java
  1. String username = System.getProperty("user.name");
    
  2. InputStream is = this.class.getResourceAsStream("file.txt"); 
    
  3. $ jar xvf myjar.jar
    
LaTeX
  1. En mode mathématique.

    m(i) = \left\{
        \begin{array}{ll}
            c_{si} & \mbox{si } \{s,i\} \in E \\
            \infty & \mbox{sinon}
        \end{array}
    \right
    

    Exactement la même chose, mais avec le paquetage amsmath :

    m(i) = \begin{cases}
           c_{si} & \text{si } \{s,i\} \in E \\
           \infty & \text{sinon}
           \end{cases}
    
  2. En mode mathématique.

    n \cdot
    \underbrace{\ln \left( \frac{35}{36} \right)}_{\mbox{\footnotesize{toujours }}< 0}
    < \overbrace{\ln \left(\frac{1}{2} \right)}^{\simeq -0.693}
    
  3. Avec les paquetages algorithmic et algorithm.

    %%% francisation des algorithmes
    \renewcommand{\algorithmicrequire} {\textbf{\textsc{Entrées:}}}
    \renewcommand{\algorithmicensure}  {\textbf{\textsc{Sorties:}}}
    \renewcommand{\algorithmicwhile}   {\textbf{tantque}}
    \renewcommand{\algorithmicdo}      {\textbf{faire}}
    \renewcommand{\algorithmicendwhile}{\textbf{fin tantque}}
    \renewcommand{\algorithmicend}     {\textbf{fin}}
    \renewcommand{\algorithmicif}      {\textbf{si}}
    \renewcommand{\algorithmicendif}   {\textbf{finsi}}
    \renewcommand{\algorithmicelse}    {\textbf{sinon}}
    \renewcommand{\algorithmicthen}    {\textbf{alors}}
    \renewcommand{\algorithmicfor}     {\textbf{pour}}
    \renewcommand{\algorithmicforall}  {\textbf{pour tout}}
    \renewcommand{\algorithmicdo}      {\textbf{faire}}
    \renewcommand{\algorithmicendfor}  {\textbf{fin pour}}
    \renewcommand{\algorithmicloop}    {\textbf{boucler}}
    \renewcommand{\algorithmicendloop} {\textbf{fin boucle}}
    \renewcommand{\algorithmicrepeat}  {\textbf{répéter}}
    \renewcommand{\algorithmicuntil}   {\textbf{jusqu'à}}
    
    \floatname{algorithm}{Algorithme}
    
    \let\mylistof\listof
    \renewcommand\listof[2]{\mylistof{algorithm}{Liste des algorithmes}}
    
    % pour palier au problème de niveau des algos
    \makeatletter
    \providecommand*{\toclevel@algorithm}{0}
    \makeatother
    
    %\listofalgorithms % pour lister les algos (après la toc)
    

    ...

    \begin{algorithm}
    \caption{Algorithme d'Euclide}
    \begin{algorithmic}
    %%-----------------------------------------------
    \REQUIRE $a, b \in {\mathbb N}$         % demande le paq. amssymb
    \ENSURE le pgcd de $a$ et $b$
    
    \STATE $x \leftarrow \textrm{max}(a,b)$
    \STATE $y \leftarrow \textrm{min}(a,b)$
    
    \WHILE {$y \neq 0$}
       \STATE $x \leftarrow y$
       \STATE $y \leftarrow x \mod y$       % demande le paq. amsmath
    \ENDWHILE
    
    \STATE Retourner $x$.
    %%-----------------------------------------------
    \end{algorithmic}
    \end{algorithm}
    
  4. \begin{flushleft}
    Voie lactée ô soeur lumineuse \\
    Des blancs ruisseaux de Chanaan
    \end{flushleft}
    
    \begin{flushright}
    Et des corps blancs des amoureuses \\
    Nageurs morts suivrons-nous d'ahan
    \end{flushright}
    
    \begin{center}
    Ton cours vers d'autres nébuleuses
    \end{center}
    
  5. Avec le paquetage pst-tree.

    \pstree{\Tcircle{A}}
           {\pstree{\Tcircle{B}}
                   {\Tcircle{D}
                    \Tcircle{E}}
            \pstree{\Tcircle{C}}
                   {\Tcircle{F}
                    \Tcircle{G}}}
    
  6. Avec le paquetage pst-all (pas besoin de charger color).

    \definecolor{macouleur}{rgb}{0.75, 0.75, 1.0}
    

    ...

    \newcommand{\B}[1]{\Tr{\psframebox{#1}}} % boite
    \newcommand{\C}[1]{\Tcircle{#1}}         % cercle
    \newcommand{\N}[1]{\Tr{#1}}              % normal
    %\newcommand{\T}[1]{\Ttri{#1}}           % triangle
    % triangle qui s'accroche par le haut (sous-arbres...)
    \newcommand{\T}[2][]{\Tr[ref=t]{\pstribox[#1]{#2}}}
    % cercle coloré
    \newcommand{\CC}[1]{\Tcircle[fillstyle=solid,fillcolor=macouleur]{#1}}
    
    % syntaxe : \pstree{le père}{les fils}
    \pstree{\C{titi}}
        {
            \B{toto}
            \pstree[levelsep=1cm]{\CC{tata}}
                {
                    \B{tutu}
                    \N{pipo}
                    \T{tonton}
                }
        }
    
  7. Avec le paquetage pst-tree.

    \newcommand{\C}[1]{\Tr{\psframebox{#1}}} % carré
    \newcommand{\R}[1]{\Tcircle{#1}}         % rond
    \newcommand{\N}[1]{\Tr{#1}}              % normal
    % syntaxe : \pstree{le père}{les fils}
    \pstree[treemode=R]{\R{titi}}
        {
            \C{toto}
            \pstree{\R{tata}}
                {
                    \C{tutu}
                    \R{345}
                    \N{tonton}
                }
        }
    
  8. Avec les paquetage pst-tree.

    \newcommand{\N}{\Tcircle[fillstyle=solid,fillcolor=black]{ }}
    \newcommand{\B}{\Tcircle[fillstyle=solid,fillcolor=white]{ }}
    
    \pstree[treemode=R]{\Tr{}}
           {
                \pstree{\B^{3/5}}
                {
                    \pstree{\B^{2/4}}
                    {
                        \pstree{\B^{1/3}}
                        {
                            \N_{2/2}
                        }
                        \N_{2/3}
                    }
                    \N_{2/4}
                }
                \N_{2/5}}
    
  9. Avec le paquetage vaucanson-g:

    \MediumPicture\VCDraw{% 
    \begin{VCPicture}{(0,-4)(4,4)}
    % states
    \State[1]{(0,0)}{1}
    \State[2]{(8,0)}{2}
    \FinalState[3]{(4,0)}{3}
    \State[4]{(0,-4)}{4}
    \FinalState[5]{(4,-4)}{5}
    % initial--final
    \Initial{1}
    %\Final{10}
    % transitions 
    \EdgeL{1}{3}{a}
    \EdgeL{1}{4}{b}
    \EdgeL{1}{5}{c}
    \ArcL{2}{3}{a}
    \EdgeL{2}{5}{c}
    \LoopN{3}{a}
    \ArcL{3}{2}{b}
    \ArcL{3}{5}{c}
    \ArcL{4}{5}{c}
    \ArcL{5}{3}{a}
    \ArcL{5}{4}{b}
    \LoopS{5}{c}
    \end{VCPicture}
    }
    
  10. Une manière simple et élégante d'écrire les siècles, proposée par A. Chambert-Loir sur fr.comp.text.tex :

    Avec la macro code128:

    \def\siecle#1{\textsc{\romannumeral #1}\textsuperscript{e}~siècle}
    

    ...

    Depuis le \siecle{19}, tout va mal !
    
  11. Avec la police French Cursive, les paquetages color et frcursive.

    Police créée par Emmanuel Beffara.

    \renewcommand{\seyesDefault}{\color{blue}}
    

    ...

    \begin{document}
    

    ...

    \begin{cursive}
      Vive l'école maternelle !
    
      \textbf{Gras}
      \textit{Italique} 
      \textcal{Calligraphie} % \calserie Calligraphie
    \end{cursive}
    
    \begin{quote}
      \cursive
      \seyes{Lignes normales.}
    \end{quote}
    
    \begin{quote}
      \cursive\acadshape
      \seyes[\color{red}]{Lignes comme au tableau.}
    \end{quote}
    
  12. en mode mathématique

    \left\{ \begin{array}{rrrrr}
       -9a & -2b & +6c & = & 11a \\
        6a & -6b & +7c & = & 11b \\
        2a & +9b & +6c & = & 11c
       \end{array}
    \right
    
  13. \begin{eqnarray*}
    \cos 2\theta & = & \cos^2 \theta - \sin^2 \theta \\
                 & = & 2 \cos^2 \theta - 1
    \end{eqnarray*}
    
  14. Avec la macro code128.

    \input code128
    \codetext{021\ seriot.ch} % avec texte
    %\code{021\ seriot.ch} % sans texte
    
  15. Avec la macro ean.

    \input ean13
    \ISBN 2-88074-488-1  \EAN 9-782880-744885
    

    ...

    \input ean8
    \EAN 1234-5670
    
  16. Avec le paquetage scrtime.

    Nous sommes le \today, il est \thistime.
    

    Sans paquetage particulier.

    % ----------------------------------------------------------------------
    % TIME OF DAY - Nelson Beebe - http://www.math.utah.edu/~beebe/
    \newcount\hh
    \newcount\mm
    \mm=\time
    \hh=\time
    \divide\hh by 60
    \divide\mm by 60
    \multiply\mm by 60
    \mm=-\mm
    \advance\mm by \time
    \def\hhmm{\number\hh:\ifnum\mm<10{}0\fi\number\mm}
    % ----------------------------------------------------------------------
    

    ...

    Nous sommes le \today, il est \hhmm.
    
  17. Avec le paquetage example:

    \begin{example}
    $$
    \sum_{n=1}^{10} \cdot
    \int_a^b e^{x} ~ dx
    $$
    \end{example}
    
  18. Avec le paquetage graphicx:

    \begin{figure}
    \begin{minipage}[t]{.4\linewidth}
        \begin{center}
           \includegraphics[scale=0.5]{images/nb_abo.ps}
           \caption{nombre d'abonnements au téléphone}
           \label{nbabo}
        \end{center}
    \end{minipage}
    \hfill
    \begin{minipage}[t]{.4\linewidth}
        \begin{center}
           \includegraphics[scale=0.5]{images/croiss_nb_abo.ps}
           \caption{croissance du nombre d'abonnements au téléphone}
           \label{croissnbabo}
        \end{center}
    \end{minipage}
    \end{figure}
    
  19. (en mode mathématique)

    % http://www.ctan.org/tex-archive/macros/eplain/
    \def\fract#1/#2{\leavevmode
       \kern.1em \raise .5ex \hbox{\the\scriptfont0 #1}%
       \kern-.1em $/$%
       \kern-.15em \lower .25ex \hbox{\the\scriptfont0 #2}%
    }% 
    

    ...

    9\frac{1}{2}
    

    ...

    9\fract 1/2
    
  20. Avec les paquetages epic, eepic et eclbip.

    \begin{bipartite}
       {1cm} % largeur étiquettes gauches
       {2cm} % largeur graphe
       {3cm} % largeur étiquettes droites
       {3mm} % hauteur max entre 2 noeuds
       {5mm} % larg. entre noeud et étiq.
    
    \leftnode{a}
    \leftnode{b}
    \leftnode{c}
    \rightnode[1]{chien}
    \rightnode[2]{chat}
    \rightnode[3]{lapin}
    \rightnode[4]{renard}
    \brush{\drawline}
    \match{b}{2}
    \match{b}{3}
    \match{c}{4}
    \match{a}{1}
    \brush{\dottedline{3}}
    \match{a}{2}
    \end{bipartite}
    
  21. Avec le paquetage pst-node.

    \begin{psmatrix}[mnode=circle]
       &   & A         \\
     F &   & C &   & B \\
     D &   & E &   & G \\
       & J &   & K
    \end{psmatrix}
    
    \psset{arrows=->}
    \ncline{1,3}{2,1}
    \ncline{1,3}{2,3}
    \ncline{1,3}{2,5}
    \ncline{2,5}{2,3}
    \ncline{2,5}{3,5}
    \ncline{2,3}{2,1}
    \ncline{3,1}{2,3}
    \ncline{3,3}{2,3}
    \ncline{3,3}{3,1}
    \ncline{3,3}{4,2}
    \ncline{2,1}{3,1}
    \ncline{3,5}{2,3}
    \ncline{3,5}{3,3}
    \ncline{4,2}{3,1}
    \ncline{4,2}{4,4}
    \ncline{4,4}{3,3}
    \ncline{4,4}{3,5}
    
  22. Avec le paquetage pst-node.

    \begin{psmatrix}[mnode=circle] % pour réduire :
     A &   & B \\                  % [mnode=circle,colsep=1,rowsep=1]
       & E     \\                  % défaut : rowsep et colsep = 1.5
     C &   & D
    \end{psmatrix}
    
    \psset{arrows=-,
           shortput=nab} % pondéré
    
    \ncline{1,1}{1,3}^{1}
    \ncline{1,1}{2,2}^{1}
    \ncline{1,1}{3,1}^{4}
    \ncline{1,3}{3,3}^{2}
    \ncline{2,2}{1,3}^{1}
    \ncline{2,2}{3,3}^{1}
    \ncline{3,1}{2,2}^{2}
    \ncline{3,1}{3,3}^{1}
    
  23. Avec le paquetage pst-node.

    \begin{psmatrix}[mnode=circle]
         & {v2}        \\
    {v1} &      & {v4} \\
         & {v3} & 
    \end{psmatrix}
    
    \psset{arrows=->,
           shortput=nab}
    
    \ncline{2,1}{1,2}^{3} 
    \ncline{2,1}{3,2}^{1}
    \ncline{1,2}{2,3}^{2}
    \ncline{3,2}{2,3}^{3}
    
    \ncarc[arcangle=10]{1,2}{3,2}^{1}
    \ncarc[arcangle=10]{3,2}{1,2}^{1}
    
  24. Avec le paquetage pst-node.

    \begin{psmatrix}[mnode=circle]
             &   &   & C & E            \\
    $\alpha$ & A & B & D &   & $\omega$ \\
             &   &   & F
    \end{psmatrix}
    
    \psset{arrows=->,
           labelsep=1mm,
           shortput=nab}
    
    \ncline[linewidth=2pt]{2,1}{2,2}^{0} 
    \ncline[linewidth=2pt]{2,2}{2,3}^{2} 
    \ncline[linewidth=2pt]{2,3}{1,4}^{4} 
    \ncline{2,3}{2,4}^{4} 
    \ncline{2,3}{3,4}^{4}
    \ncline[linewidth=2pt]{1,4}{1,5}^{3}
    \ncline{2,4}{1,5}^{2}
    \ncline{3,4}{2,6}^{4}
    \ncline[linewidth=2pt]{1,5}{2,6}^{10}   
    

    Une autre manière de faire exactement la même chose :

    \begin{pspicture}(0,0)(14,8)
    \cnodeput(2,4){a}{$\alpha$}
    \cnodeput(4,4){A}{A}
    \cnodeput(6,4){B}{B}
    \cnodeput(8,6){C}{C}
    \cnodeput(8,4){D}{D}
    \cnodeput(8,2){F}{F}
    \cnodeput(10,6){E}{E}
    \cnodeput(12,4){o}{$\omega$}
    %%%
    \ncline[linewidth=2pt]{->}{a}{A} \Aput{0}
    \ncline[linewidth=2pt]{->}{A}{B} \Aput{2}
    \ncline[linewidth=2pt]{->}{B}{C} \Aput{4}
    \ncline               {->}{B}{D} \Aput{4}
    \ncline               {->}{B}{F} \Aput{4}
    \ncline[linewidth=2pt]{->}{C}{E} \Aput{3}
    \ncline               {->}{D}{E} \Aput{2}
    \ncline[linewidth=2pt]{->}{E}{o} \Aput{10}
    \ncline               {->}{F}{o} \Aput{4}
    \end{pspicture}
    
  25. Avec le paquetage setspace :

    \singlespace
    \onehalfspace
    \doublespace
    
  26. Just draw the symbol you are looking for.

    http://detexify.kirelabs.org/classify.html

  27. Sans paquetage particulier.

    \begin{itemize}
    \item chien
    \item chat
    \item renard
    \item canari
    \item éléphant
    \end{itemize}
    

    ...

    \begin{enumerate}
    \item chien
    \item chat
    \item renard
    \item canari
    \item éléphant
    \end{enumerate}
    

    ...

    \begin{description}
    \item[chien] habite dans une niche et mange des os
    \item[renard] habite dans la forêt et mange des poules
    \item[canari] habite dans une cage et mange des graines
    \end{description}
    
  28. Avec le paquetage enumerate :

    \begin{enumerate}[1 --]
    \item chien
    \item chat
    \item renard
    \item canari
    \item éléphant
    \end{enumerate}
    

    ...

    \begin{enumerate}[a)]
    \item chien
    \item chat
    \item renard
    \item canari
    \item éléphant
    \end{enumerate}
    

    ...

    \begin{enumerate}[{ani.} i :]
    \item chien
    \item chat
    \item renard
    \item canari
    \item éléphant
    \end{enumerate}
    
  29. \usepackage{color}
    \usepackage{listings}
    
    \definecolor{pink}  {rgb}{0.67, 0.05, 0.57} % keywords
    \definecolor{red}   {rgb}{0.87, 0.20, 0.00} % strings
    \definecolor{green} {rgb}{0.00, 0.47, 0.00} % comments
    \definecolor{violet}{rgb}{0.41, 0.12, 0.61} % classes
    \definecolor{blue}  {rgb}{0.21, 0.00, 0.44} % functions
    \definecolor{brown} {rgb}{0.39, 0.22, 0.13} % brown
    
    \lstdefinelanguage{Objective-C 2.0}[Objective]{C} {
        morekeywords={id, Class, SEL, IMP, BOOL, nil, Nil, NO, YES,
                      oneway, in, out, inout, bycopy, byref,
                      self, super, _cmd,
                      @required, @optional,
                      @try, @throw, @catch, @finally,
                      @synchronized, @property, @synthesize, @dynamic},
        moredelim=[s][color{red}]{@"}{"},
        moredelim=[s][color{red}]{<}{>}
    }
    
    \lstdefinestyle{Xcode} {
        language        = Objective-C 2.0,
        basicstyle      = footnotesizettfamily,
        identifierstyle = color{black},
        commentstyle    = color{green},
        keywordstyle    = color{pink},
        stringstyle     = color{red},
        directivestyle  = color{brown},
        extendedchars   = true,
        tabsize         = 4,
        showspaces      = false,
        showstringspaces = false,
        breakautoindent = true,
        flexiblecolumns = true,
        keepspaces      = true,
        stepnumber      = 0,
        xleftmargin     = 0pt}
    
    \lstset{
        style = Xcode,
        caption=lstname,
        breaklines=false,
        frame=single
    }
    

    Use it like this:

    \begin{lstlisting}[name=Sample code, label=SampleCode]
    NSLog(@"hello");
    \end{lstlisting}
    

    List the listings:

    \lstlistoflistings
    
  30. Avec le paquetage amsmath, et en mode mathématique.

    \begin{matrix} 
    a & b \\
    c & d 
    \end{matrix}
    \quad
    \begin{pmatrix} 
    a & b \\
    c & d 
    \end{pmatrix}
    \quad
    \begin{bmatrix} 
    a & b \\
    c & d 
    \end{bmatrix}
    \quad
    \begin{vmatrix} 
    a & b \\
    c & d 
    \end{vmatrix}
    \quad
    \begin{Vmatrix} 
    a & b \\
    c & d 
    \end{Vmatrix}
    
  31. \marginpar{Ben tiens !}
    
  32. On écrit $a\equiv b\pmod{c}$, \\
    mais aussi $a = b \bmod c$.
    
  33. Add an additional directory path for \includegraphics

    \graphicspath{{./images/}}
    
  34. Le Indian TeX Users Group propose une excellente introduction à PSTricks sous la forme de magnifiques fichiers PDF plein l'exemples et d'explications très bien choisis.

    Ça se télécharge sur Sarovar, le SourceForge du pays de Gandhi.

  35. Pour qu'une section (ou une sous-section, etc.) ne soit pas numérotée, il faut le signaler par une étoile.

    \section*{Introduction}
    

    Pour qu'elle apparaisse quand-même dans la table des matières, on peut ajouter la ligne suivante :

    \addcontentsline{toc}{section}{Introduction}
    
  36. \usepackage{eurosym}
    
    \euro
    
  37. Un tableau qui se redimensionne pour tenir sur une page.

    Avec le package tabularx.

    % les 'X' indiquent les colonnes dont la largeur peut être modifiée
    \begin{tabularx}{450pt}{|c|X|c|X|c|c|c|c|c|c|c|c|c|c|c|}
    \hline
    Tâche         & $\alpha$   & T1       & T2         & T9       & T3 & T4 & T6 & T7 & T5  & T8  & T10 & T11 & T12      & $\omega$   \\
    \hline
    Numéro $k$    & 1          & 2        & 3          & 4        & 5  & 6  & 7  & 8  & 9   & 10  & 11  & 12  & 13       & 14         \\
    \hline
    Durée $d_{k}$ & 0          & 3        & 2          & 14       & 4  & 1  & 3  & 2  & 6   & 2   & 6   & 4   & 3        & 0          \\
    \hline
    \hline
    $Pred(k)$     & --         & $\alpha$ & $\alpha$   & $\alpha$ & T1 & T2 & T4 & T2 & T2  & T7  & T5  & T9  & T10      & T12        \\
    \hline
    $t_{k}$       & 0          & 0        & 0          & 0        & 3  & 7  & 8  & 2  & 2   & 11  & 13  & 14  & 19       & 22         \\
    \hline
    \hline
    $Succ(k)$     & T1 T2 T9   & T3       & T4  T5  T7 & T11      & T4 & T6 & T8 & T8 & T10 & T10 & T12 & T12 & $\omega$ & --         \\
    \hline
    $T_{k}$       & 0          & 0        & 5          & 1        & 3  & 7  & 8  & 9  & 7   & 11  & 13  & 15  & 19       & 22         \\
    \hline
    \end{tabularx}
    
  38. Avec le paquetage array.

    \newcolumntype{t}{>{\ttfamily}l}
    \newcolumntype{m}{>{\scshape}c}
    \newcolumntype{g}{>{\Large}r}
    

    ...

    \begin{document}
    

    ...

    \begin{tabular}{|t|m|g|}
    Texte  & Texte  & Texte\\
    Gauche & Centré & Droite
    \end{tabular}
    
  39. \begin{table}[h!]
    \begin{minipage}[t]{.4\linewidth}
        \begin{tabular}{|c|c|c|c|c|}
        \hline
        \multicolumn{5}{|l|}{queue de priorité} \\
        \hline
        E & D & C &   &   \\
        1 & 2 & 4 &   &   \\
        \hline
        \end{tabular}
    \end{minipage}
    \hfill
    \begin{minipage}[t]{.4\linewidth}
        \begin{tabular}{|c|c|c|c|c|}
        \hline
        \multicolumn{5}{|l|}{tableau des pères} \\
        \hline
        A & B & C & D & E \\
        - & A & A & B & A \\
        \hline
        \end{tabular}
    \end{minipage}
    \end{table}
    
  40. Avec le paquetage ulem.

    \sout{texte barré}
    

    Avec le paquetage soul.

    \st{texte barré}
    
  41. Avec le paquetage color :

    \definecolor{orange}{rgb}{1.0, 0.5, 0.0}
    \definecolor{monbleu}{rgb}{0.25, 0.25, 0.75}
    

    ...

    \paragraph{}Je peux écrire en {\color{red}rouge}, en {\color{green}vert} et en {\color{blue}bleu}. \\
    Je peux aussi écrire en {\color{orange}orange} ou avec {\color{monbleu}mon bleu}. \\
    Ce n'est pas toujours \colorbox{monbleu}{\color{orange}très beau}.
    
  42. Avec le paquetage multicol.

    \begin{multicols}{3}
    

    ...

    \end{multicols}
    
  43. Avec les paquetages soul et color.

    \definecolor{bleuclair}{rgb}{0.7, 0.7, 1.0}
    \definecolor{rosepale}{rgb}{1.0, 0.7, 1.0}
    
    \newcommand{\hlrose}[1]{\sethlcolor{rosepale}\hl{#1}}
    
    \begin{document}
    
    On peut \hl{surligner un texte avec la couleur par défaut}.
    
    On peut choisir \hlrose{une autre couleur}.
    
    \sethlcolor{bleuclair}
    
    On peut aussi \hl{changer} la \hl{couleur} par \hl{défaut}.
    
  44. Avec les paquetage babel et l'option francais.

    \begin{tabular}{llll}
    M\up{me}, M\up{mes}    & Jean-Michel     & 1\ier\ 1\iere\ 1\ieres  & \og guillemets \fg          \\
    M\up{lle}, M\up{lles}  & pp.~12--15      & 2\ieme\ 2\iemes         & \nombre{1234,56}            \\
    M. \bsc{Dupont},       & --- en fait --- & \No 1, \no 2            & {\OE}uf, {\oe}ufs, \AE, \ae \\
    M\up{e}, M\up{gr}, MM. & $-1$ degrés     & 13\degres, 23~\degres C & À l'État.
    \end{tabular}
    

    Quelques liens :

    perso.wanadoo.fr résumé des règles typographiques de base (générales et scientifiques) listetypo.free.fr Orthotypographie [pdf], ouvrage posthume et inachevé, sur la page de Jean-Pierre Lacroux.

  45. Avec le paquetage url :

    \newcommand\email{\begingroup \urlstyle{rm}\Url}
    \newcommand\web{\begingroup \urlstyle{tt}\Url}
    

    ...

    \email{nicolas@seriot.ch}
    

    ...

    \web{http://seriot.ch}
    
Mac App Store
  1. To show applications opening JPEG files, search for uti:public.jpeg.

  2. Search for "extension:md" for instance.

Mac OS X
  1. $ defaults write -g ApplePressAndHoldEnabled -bool false
    
  2. $ defaults write com.apple.Mail DisableSendAnimations -bool YES
    $ defaults write com.apple.Mail DisableReplyAnimations -bool YES
    
  3. ie disable Resume per application:

    $ defaults write com.apple.Preview NSQuitAlwaysKeepsWindows -int NO
    
  4. $ defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool NO
    
  5. In column mode, double-clic on the ||.

  6. $ defaults write -g NSNavPanelExpandedStateForSaveMode -bool YES
    
  7. $ atos -o MyiPhoneBinary -arch armv7 0x00009f16
    -[AppDelegate application:didFinishLaunchingWithOptions:] (in MyiPhoneBinary) (AppDelegate.m:253)
    
  8. enable:

    $ sudo nvram boot-args="-v"
    

    disable:

    $ sudo nvram boot-args=
    
  9. $ defaults write /Library/Preferences/com.apple.loginwindow DesktopPicture /picture.jpg
    
  10. $ defaults write com.apple.screencapture location ~/Pictures
    $ killall SystemUIServer
    
  11. $ defaults write com.apple.screencapture type jpg
    $ killall SystemUIServer
    

    type may be jpg, pdf, tif or png

  12. $ defaults write com.apple.frameworks.diskimages skip-verify -bool true
    $ defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true
    $ defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true
    
  13. $ defaults write com.apple.dashboard mcx-disabled -boolean YES
    $ killall Dock    
    
  14. $ defaults write com.apple.mail DisableDataDetectors YES
    
  15. $ defaults write com.apple.iTunes disableGeniusSidebar YES
    
  16. $ defaults write NSGlobalDomain AppleEnableMenuBarTransparency -bool false
    
  17. $ launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist
    
    $ killall NotificationCenter
    
  18. $ defaults write -g NSScrollAnimationEnabled -bool false
    
  19. $ defaults write com.apple.dock workspaces-swoosh-animation-off -bool YES
    $ killall Dock
    
  20. $ defaults write com.apple.screencapture disable-shadow -bool true
    $ killall SystemUIServer
    
  21. $ defaults write com.apple.mail PreferPlainText -bool YES
    
  22. $ defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo SystemVersion 
    

    SystemVersion can be replaced by:

    SystemBuild
    SerialNumber 
    IPAddress 
    DSStatus 
    Time
    HostName
    
  23. $ /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -S
    

    See the help page:

    $ airport --help
    
  24. $ defaults write com.apple.dock no-glass -boolean YES
    
  25. $ defaults write com.apple.DiskUtility DUDebugMenuEnabled -bool true
    
  26. $ defaults write com.apple.appstore ShowDebugMenu -bool true
    

    Source: http://www.red-sweater.com/blog/1586/the-mac-app-store-debug-menu

  27. $ defaults write com.apple.finder QLEnableTextSelection -bool TRUE; killall Finder
    
  28. The simplest way:

    Start with cmd-S, then

    # mount /
    # rm /var/db/.AppleSetupDone
    # reboot
    

    and create a new admin account through the assistant.

  29. $ defaults write com.apple.dock mouse-over-hilte-stack -boolean YES
    
  30. ~/Library/Application Support/iLifeAssetManagement/assets/sub/
    
  31. $ defaults write com.apple.dock largesize -float 200
    $ killall Dock
    

    128 is the default

  32. $ hdiutil attach disk_image.dmg
    $ cd /Volumes/volume_name/
    $ sudo installer -pkg package_name.pkg -target "/"
    $ hditutil detach /Volumes/volume_name/
    
  33. LaunchServices holds the mapping between applications and documents.

    $ /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister
    

    explicitely register an application

    $ lsregister -f MyApp.app
    

    dump the database

    $ lsregister -dump
    

    rebuild the database

    $ lsregister -kill -r -domain local -domain system -domain user
    
  34. $ sw_vers -productVersion
    
  35. $ defaults write com.apple.mail AddressesIncludeNameOnPasteboard -bool NO
    
  36. $ /Developer/Tools/SetFile -a V my_file.txt
    
  37. $ defaults write com.apple.Dock showhidden -bool YES
    
  38. $ open -a Terminal `pwd`
    

    great with an alias in your ~/.profile

    alias new="open -a Terminal `pwd`"
    
  39. $ defaults write com.apple.dock launchanim -bool false
    
  40. $ sudo pmset lidwake 0
    
  41. $ defaults write com.apple.dashboard devmode YES
    $ killall Dock
    

    Press F12, start moving the widget and hit F12 again. Put the widget on the Desktop.

  42. cmd-R

  43. remove accounts:

    $ sudo defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array-add user1 user2 user3
    

    reset:

    $ sudo defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array-add
    
  44. Check the following directories:

    "~/Library/Developer/Xcode/iOS DeviceSupport/"
    "~/Library/Developer/Shared/Documentation/DocSets/"
    
  45. $ defaults write NSGlobalDomain NSSavePanelStandardDesktopShortcutOnly -bool YES
    
  46. $ defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
    
  47. $ defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES
    
  48. $ defaults write com.apple.addressbook ABShowDebugMenu -bool YES
    
  49. $ defaults write com.apple.dock static-only -bool TRUE
    $ killall Dock
    
  50. # dmesg
    
  51. $ defaults write com.apple.desktopservices DSDontWriteNetworkStores true
    

    see http://support.apple.com/kb/HT1629

  52. $ /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background
    
  53. $ codesign -dvvv TwitHunter.app
    

    result

    Executable=/Users/nst/TwitHunter.app/Contents/MacOS/TwitHunter
    Identifier=ch.seriot.TwitHunter
    Format=bundle with Mach-O thin (x86_64)
    CodeDirectory v=20100 size=589 flags=0x0(none) hashes=21+5 location=embedded
    Hash type=sha1 size=20
    CDHash=d92cea80efead38315b778b0a320db6fceb666fe
    Signature size=8514
    Authority=Developer ID Application: Nicolas Seriot
    Authority=Developer ID Certification Authority
    Authority=Apple Root CA
    Timestamp=Aug 24, 2012 8:07:40 AM
    Info.plist entries=19
    Sealed Resources rules=4 files=6
    Internal requirements count=2 size=292
    

    See also "Mac OS X Code Signing In Depth" http://developer.apple.com/library/mac/#technotes/tn2206/_index.html

  54. ~/Library/Caches/Metadata/app.bundle.identifier
    
Mac OS X - CLI
  1. $ sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* 'select LSQuarantineDataURLString from LSQuarantineEvent'
    

    you can delete the table with:

    $ sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* 'delete from LSQuarantineEvent'
    
  2. $ /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/AppleMobileDeviceHelper.app/Contents/Resources/AppleMobileBackup --help
    
  3. $ atos -o MyiPhoneBinary -arch armv7 0x00009f16
    -[AppDelegate application:didFinishLaunchingWithOptions:] (in MyiPhoneBinary) (AppDelegate.m:253)
    
  4. $ ioreg -l | grep Capacity
        | |           "MaxCapacity" = 4047
        | |           "CurrentCapacity" = 3901
        | |           "LegacyBatteryInfo" = {"Amperage"=18446744073709548440,
                                             "Flags"=4,"Capacity"=4047,
                                             "Current"=3901,
                                             "Voltage"=11976,
                                             "Cycle Count"=283}
        | |           "DesignCapacity" = 4600
    
    • MaxCapacity is capacity at full charge
    • DesignCapacity is the original capacity
    • "Cycle Count" is the number of recharge cycles
  5. $ install_name_tool -change libbz2.1.0.2.dylib @executable_path/../Frameworks/libbz2.1.0.2.dylib MyFunBinary 
    
  6. $ pmset -g
     sleep      0 (imposed by 6783)
    

    here, process 6783 is responsible

  7. $ sudo gcc_select 3.3
    $ sudo gcc_select 4.0
    
  8. This solution needs Apple Pages and pandoc.

    # in Pages, convert x.doc into x.rtf
    $ textutil -convert html x.rtf -output x.html
    $ pandoc -f html -t markdown x.html -o x.markdown
    
  9. $ plutil -convert xml1 foo.plist 
    $ plutil -convert binary1 bar.plist 
    
  10. $ sudo mdutil -E -i on /
    
  11. $ defaults write com.apple.LaunchServices LSQuarantine -bool NO
    

    on a file basis

    $ xattr -d com.apple.quarantine PATH
    
  12. $ sudo mdutil -E off -d /
    
  13. $ /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump
    
  14. $ defaults write com.apple.NetworkBrowser BrowseAllInterfaces 1
    
  15. $ codesign -dvvvv --extract-certificates /Applications/Mail.app
    

    The certificates are saved in DER format, named codesign0, codesign1, ...

    They can be displayed with OpenSSL :

    $ openssl x509 -inform DER -in codesign0 -text
    
  16. $ /System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc
    > 1+1
    2
    
  17. Prevent /usr/bin/login from searching the system logs so that it can display the date and time of your last login.

    $ touch .hushlogin
    
  18. $ sudo opensnoop -f /path/to/file
    $ sudo opensnoop -n Terminal
    $ sudo opensnoop -p <pid>
    
  19. $ sudo update_prebinding -root /
    
  20. End the directory name with .noindex

  21. $ defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences RememberedNetworks | grep SSID_STR
    
  22. Delete recursively starting from current directory.

    $ find . -name .DS_Store -ls -exec rm {} ;
    

    To be used through an alias such as rmDS, for instance.

    If you don't need to print the delete file names:

    $ find . -name ".DS_Store" -delete
    
  23. # diskutil repairPermissions /
    
  24. With sips, a built-in Mac OS X tool.

    $ sips -Z 640 *.jpg
    
  25. $ sudo periodic daily weekly monthly
    
  26. # softwareupdate -i -a
    

    no need to open Mac App Store

  27. $ otool -v -s __TEXT __objc_methname RuntimeBrowser 
    RuntimeBrowser:
    Contents of (__TEXT,__objc_methname) section
    0x000000010000b450  init
    0x000000010000b455  mainBundle
    0x000000010000b460  pathForResource:ofType:
    ...
    
  28. $ defaults write NSGlobalDomain InitialKeyRepeat -int 7
    $ defaults write NSGlobalDomain KeyRepeat -int 0
    

    Here, smaller is better.

  29. $ otool -L /Users/nst/Desktop/InstrumentServer.app/Contents/MacOS/InstrumentServer 
    /Users/nst/Desktop/InstrumentServer.app/Contents/MacOS/InstrumentServer:
            /System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa (compatibility version 1.0.0, current version 11.0.0)
            @executable_path/../Frameworks/NostromoSeries.framework/Versions/A/NostromoSeries (compatibility version 1.0.0, current version 1.0.0)
            @executable_path/../Frameworks/SenCC.framework/Versions/A/SenCC (compatibility version 1.0.0, current version 1.0.0)
            /Library/Frameworks/Python.framework/Versions/2.5/Python (compatibility version 2.5.0, current version 2.5.0)
            /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
            /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.3)
    
  30. Can replace unix find:

    $ mdfind -onlyin ~/Documents Leopard
    
  31. $ spctl --assess --verbose=4 /Applications/Notes.app
    /Applications/Notes.app: accepted
    source=Apple System
    
  32. update the database

    $ sudo /usr/libexec/locate.updatedb
    

    use the database

    $ locate my_report
    
  33. slow down traffic with apple.com

    sudo ipfw pipe 1 config bw 40kbit/s
    sudo ipfw add pipe 1 src-ip 17.149.160.49
    sudo ipfw add pipe 1 dst-ip 17.149.160.49
    

    delete rules

    sudo ipfw flush
    

    Thanks Cédric for this great tip!

    See also: Traffic Shaping in Mac OS X

  34. $ sudo xcode-select /Library/Developer/CommandLineTools/
    
    $ xcode-select --print-path
    /Library/Developer/CommandLineTools
    
Mac OS X - Finder
  1. $ chflags nohidden ~/Library
    
  2. $ defaults write com.apple.NetworkBrowser BrowseAllInterfaces 1 
    
  3. $ defaults write com.apple.finder QuitMenuItem -bool YES
    
  4. $ sudo mv Desktop Desktop_original
    $ ln -s Projects Desktop
    $ killall Finder
    
  5. $ defaults write com.apple.finder DisableAllAnimations -bool yes
    
  6. $ defaults write com.apple.finder AppleShowAllFiles TRUE
    
  7. hit the enter key

  8. $ defaults write com.apple.finder EmptyTrashSecurely -bool true
    
  9. $ defaults write com.apple.finder CreateDesktop -bool False
    
  10. Drop the directory on the Print Center.

  11. $ defaults read com.apple.desktop Background
    
  12. Achieves the same as in Finder Preferences.

    $ defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
    
matplotlib
  1. from pylab import *
    
    x = arange(0, 10, 0.2)
    y = sin(x)
    
    plot(x, y)
    show()
    
Mercurial
  1. [hostfingerprints]
    my.server.com = 07:a0:bd:32:6e:2f:81:58:92:e9:60:d4:e4:83:7a:48:43:d3:5a:c4
    
  2. [auth]
    repo.prefix = https://my.repository.com:444/hg/xxx/
    repo.username = nseriot
    repo.password = password
    
  3. [ui]
    username = Nicolas Seriot <nicolas.seriot@xxx.com>
    
  4. like git commit --amend

    $ hg rollback
    $ hg commit -m "new message"
    
  5. $ hg log --limit 3 --template '{node|short} | {date|isodatesec} | {author|user}: {desc|strip|firstline}\n'
    
    683a489bf341 | 2012-08-03 13:20:31 +0200 | nicolas: misc
    99de916e21d9 | 2012-08-02 11:10:28 +0200 | nicolas: misc
    a6a45f2e7ff6 | 2012-07-31 16:58:53 +0200 | nicolas: misc
    

    Even better with an alias in .hgrc

    [alias]
    shortlog = log --template '{node|short} | {date|isodatesec} | {author|user}: {desc|strip|firstline}\n'
    

    Now callable with:

    $ hg shortlog
    
  6. $ hg diff -r tag1:tag2
    
  7. $ hg pull --insecure https://server/repository
    
  8. hg tag -r 1220 new_tag
    hg tag --remove old_tag
    
  9. Create opendiff-w, an executable script in your path, with the following contents:

    # opendiff returns immediately, without waiting for FileMerge to exit.
    # Piping the output makes opendiff wait for FileMerge.
    opendiff "$@" | cat
    

    Set the following in your .hgrc file

    [extensions]
    hgext.extdiff = 
    
    [extdiff]
    cmd.opendiff = opendiff-w
    

    Now you can see the diff in FileMerge by calling:

    $ hg opendiff
    

    http://mercurial.selenic.com/wiki/ExtdiffExtension

mod_python
  1. raise `my_var`
    
MySQL
  1. mysql> ALTER TABLE my_table ADD FULLTEXT(my_col);
    

    This doesn't work on InnoDB tables, but only on MyIsam ones.

    SELECT *
    FROM my_table
    WHERE MATCH (my_col)
    AGAINST('my_text');
    
  2. mysql> ALTER TABLE nm_newsitem ADD CONSTRAINT unique_link UNIQUE (link(255));
    
  3. mysql> ALTER TABLE my_table ADD INDEX(my_col);
    
  4. mysql> ANALYZE TABLE my_table;
    
  5. mysql> USE my_db;
    
  6. $ mysql -u user_name -p
    
  7. mysql> DESCRIBE my_table;
    
  8. mysql> SHOW TABLES;
    
  9. $ mysqldump --opt --user=username --password database > dumpfile.sql
    
    $ mysqldump --user my_user --password=my_password database > dumpfile.sql
    
  10. $ mysqldump --no-data --opt --user=root --password news_memory > tables.sql
    
  11. $ mysql --user=username --password database < dumpfile.sql
    
  12. mysql> INSERT INTO my_table VALUES ('','France','fr');
    
  13. $ /usr/local/mysql/bin/mysqladmin -u root password xxxxxxxx
    
  14. mysql> UPDATE my_table SET my_table.my_row_1 = 'Lausanne' WHERE my_table.my_row_2 = 2338;
    
  15. mysql> OPTIMIZE TABLE my_table;
    
  16. ALTER TABLE my_table AUTO_INCREMENT=1;
    

    The value is the one that will be used next.

  17. update <table> set <champ> = replace(<champ>,'<avant>','<apres>');
    
  18. $ sudo mysqld_safe --user=root &
    
  19. $ mysqladmin -u root --password=xxxxxxxx shutdown
    
  20. Since version 4.1, MySQL stores password in a new way.

    Previous clients can't authenticate anymore.

    As a workaround, you can update user passwords in mysql.user table:

    mysql> UPDATE mysql.user SET password = OLD_PASSWORD('password') WHERE user = 'xxx' and host = 'xxx';
    mysql> FLUSH PRIVILEGES;
    
  21. Since MySQL 4.1 :

    mysql> ALTER TABLE ma_table MODIFY ma_colonne CHAR(150) CHARACTER SET utf8;
    
ncftp
  1. $ ncftp
    ncftp> open -u catane colons.seriot.ch 
    Password: 
    ncftp / > 
    
OmniGraffle
  1. In the Edit menu, you can copy any object as AppleScript.

    You can then edit the code according to what you want to draw.

    Let us say that the file draw.txt contains the following code:

    tell application "OmniGraffle Professional 5"
        tell canvas of front window
            make new shape at end of graphics with properties {corner radius: 15, size: {100, 30}, origin: {50, 50}}
        end tell
    end tell
    

    Here is how to run the script and draw the shape:

    $ osascript draw.txt
    

OpenSSL
  1. $ openssl s_client -connect twap.swissquote.ch:443
    

    To use Mac OS X Keychain certificates, export then in .pem format, then use the -CAfile flag:

    $ openssl s_client -connect twap.swissquote.ch:443 -CAfile Certificates.pem
    
PDF
  1. With GhostScript:

    $ gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf a.pdf b.pdf
    
  2. $ java -classpath Multivalent20040415.jar tool.pdf.Decrypt file.pdf
    

    Multivalent20040415.jar

PostgreSQL
  1. $ pg_dump -s DB_NAME -t TABLE_NAME
    
  2. $ postgres=# \l
    
Python
  1. #!/usr/bin/python
    # -*- coding: iso-8859-1 -*-
    __version__ = "$Revision: 0.1 $"
    __author__ = "Nicolas Seriot"
    __date__ = "2005-03-27"

    class Car:
        """
        This class represents a Car
        """

            
        # constructor
        def __init__(self, brand, color):        
            self.brand = brand
            self.color = color
            
        # a method
        def paint(self, color):
            self.color = color
        
        # string description
        def __str__(self):
            return self.brand + ", " + self.color
        
        # destructor
        def __del__(self):
            pass
            
    if __name__ == "__main__":
        
        c1 = Car("Ford", "blue")
        c2 = Car("Ferrari", "red")
        
        cars = [c1, c2]
        
        c2.paint("pink")
        
        for c in cars:
            print c
    $ python cars.py
    Ford, blue
    Ferrari, pink
    
  2. keys = ['a', 'b', 'c']
    values = [1, 2, 3]
    d = dict(zip(keys, values))
    

    {'a': 1, 'c': 3, 'b': 2}

  3. >>> dict((k, []) for k in ['a', 'b', 'c'])
    {'a': [], 'c': [], 'b': []}
    
  4. >>> import datetime
    
    >>> today = datetime.date.today()
    >>> today.replace(day=1)
    datetime.date(2007, 2, 1)
    >>> today.replace(month=today.month+1).replace(day=1)
    datetime.date(2007, 3, 1)
    
  5. import my_module
    f = getattr(my_module, 'my_function')
    result = f()
    

    or

    globals()["my_function"]()
    

    or

    locals()["my_function"]()
    
  6. class C:
    
        def foo(cls, y):
            print "classmethod", cls, y
        foo = classmethod(foo)
    
    C.foo(1)
    c = C()
    c.foo(1)
    

    Unifying types and classes in Python 2.2

  7. http://garethrees.org/2001/12/04/python-coverage/

    Here with a Django project:

    $ coverage.py -x manage.py test
    $ coverage.py -a app/models.py
    $ mate app/models.py,cover 
    
  8. Let the profiler execute the code

    import hotshot
    
    prof = hotshot.Profile("hotshot_stats.prof")
    prof.runcall(my_function)
    prof.close()
    

    Display results

    from hotshot import stats
    
    s = stats.load("hotshot_stats.prof")
    s.strip_dirs()
    s.sort_stats('time', 'calls')
    s.print_stats(20)
    
  9. >>> import datetime
    >>> import time
    >>> dt = datetime.datetime(2010, 2, 25, 23, 23)
    >>> time.mktime(dt.timetuple())
    

    1267136580.0

  10. s_latin1 = unicode(s_utf8, 'utf-8').encode('latin-1', 'replace')
    
  11. sum(1 for line in open('myfile.txt'))
    
  12. >>> import datetime
    >>> datetime.datetime.fromtimestamp(1294236000)
    

    datetime.datetime(2011, 1, 5, 15, 0)

  13. import os
    import datetime
    
    created_t = os.path.getctime("/etc/passwd")
    modified_t = os.path.getmtime("/etc/passwd")
    
    print datetime.datetime.fromtimestamp(created_t)
    print datetime.datetime.fromtimestamp(modified_t)
    

    2012-07-03 12:30:39 2012-07-03 12:30:39

  14. #!/usr/bin/python
    
    import thread
    import time
    
    def my_function():
        while 1:
            print "thread 2"
            time.sleep(0.6)
    
    print "-- will detach new thread"
    thread.start_new_thread(my_function, ())
    print "-- did detach new thread"
    
    while 1:
        print "thread 1"
        time.sleep(1)
    
  15. import locale
    import datetime
    
    locale.setlocale(locale.LC_ALL, 'fr_FR')
    now = datetime.datetime.now()
    now.strftime("%A %d %B %Y, %H:%M")
    #'Samedi 20 janvier 2007, 15:17'
    

    Another way:

    from time import strftime
    strftime("%Y-%m-%d %H:%M:%S")
    #'2008-09-28 20:33:09'
    
  16. $ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
    

    /Library/Python/2.5/site-packages

  17. Instead of writing:

    index = 0
    for element in my_list:
        print (index, element)
        index += 1
    

    use:

    for index, element in enumerate(my_list):
        print (index, element)
    
  18. class MyException(Exception):
        def __init__(self, value):
            self.value = value
    
        def __str__(self):
            return repr(self.value)
    
    def myFunction():
        raise MyException("myValue")
    
    def handleException():
        try:
            myFunction()
        except MyException as e:
            print("-- exception: %s" % e)
    
    handleException();
    
  19. import inspect
    

    from inside the object

    test_methods = inspect.getmembers(self, lambda f:inspect.ismethod(f) and f.__name__.startswith('test_'))
    
    for (f_name, f) in test_methods:
        f()
    
  20. >>> matrix = [[1,2,3], [4,5,6]]
    >>> [x for row in matrix for x in row]
    [1, 2, 3, 4, 5, 6]
    

    or

    >>> sum(matrix, [])
    [1, 2, 3, 4, 5, 6]
    
  21. import random
    random.sample(xrange(100), 3)
    

    [32, 49, 0]

  22. from random import randint
    randint(0, 2)
    

    0, 1 or 2

  23. import sys
    
    if sys.byteorder == "little":
        print "little-endian platform (intel, alpha)"
    else:
        print "big-endian platform (motorola, sparc)"
    
  24. import os
    
    for param in os.environ.keys():
        print "%20s %s" % (param, os.environ[param])
    
  25. import socket
    
    print socket.gethostbyname(socket.gethostname())
    

    192.168.0.231

  26. print f.__name__
    
  27. def webloc_url(path):
        f = open(path)
        s = f.read()
        f.close()
    
        data = NSData.dataWithContentsOfFile_(path)
        plist = NSPropertyListSerialization.propertyListWithData_options_format_error_(data, 0, None, None)
    
        return plist[0]['URL']
    
  28. #!/usr/bin/python
    
    import socket
    from urllib import urlopen
    
    socket.setdefaulttimeout(2) # secondes
    
    try:
        print urlopen("http://checkip.dyndns.org").readlines()
    except IOError:
        print "timeout"
    
  29. import socket
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("www.seriot.ch", 80))
    
    s.send("GET /index.php HTTP/1.1\nHost: seriot.ch\n\n")
    response = s.recv(1024)
    print response
    
  30. from os import curdir, sep
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
    
    class MyHandler(BaseHTTPRequestHandler):
    
        def do_GET(self):
            try:
                if self.path.endswith(".test"):
                    self.send_response(200)
                    self.send_header('Content-type',    'text/html')
                    self.end_headers()
                    #f = open(curdir + sep + self.path)
                    #self.wfile.write(f.read())
                    #f.close()
                    self.wfile.write("it works")
                    return
            except IOError:
                pass
    
            self.send_error(404,'File Not Found: %s' % self.path)
    
    def main():
        try:
            server = HTTPServer(('', 10000), MyHandler)
            print 'started HTTPServer...'
            server.serve_forever()
        except KeyboardInterrupt:
            print '^C received, shutting down server'
            server.socket.close()
    
    if __name__ == '__main__':
        main()
    
  31. #!/usr/bin/python
    
    import httplib
    
    def headers_and_contents(host, path, headers):
    
        conn = httplib.HTTPConnection(host)
        conn.request("GET", path, None, headers)
        r = conn.getresponse()
    
        if r.status != 200:
            print r.status, r.reason
    
        h = r.getheaders()
        s = r.read()
    
        conn.close()
    
        return (h, s)
    
    headers = {"Cookie" : "key=value;"}
    
    (h, s) = headers_and_contents("www.apple.com", "/index.html", headers)
    
  32. #!/usr/bin/python
    
    import os
    
    print "-- will kill"
    pid = os.getpid()
    print "-- pid:", pid
    os.kill(pid, 1)
    print "-- did kill"
    
  33. import popen2
    (stdout, stdin, stderr) = popen2.popen3("ping -q -c2 www.google.com")
    print stdout.readlines()
    
  34. import objc
    
    objc.loadBundle("InstantMessage", globals(),
                    bundle_path=objc.pathForFramework(u'/System/Library/Frameworks/InstantMessage.framework'))
    
    service = IMService.serviceWithName_('AIM')
    print service.peopleWithScreenName_('pikswiss')
    

    Since Mac OS X 10.5 :

    from AddressBook import *
    
    book = ABAddressBook.sharedAddressBook()
    print book.me()
    
  35. # -*- coding: iso-8859-1 -*-
    
    import string
    
    french = "Peut-être cet été à la mer."
    
    char_from = "éêà"
    char_to   = "eea"
    
    print french.translate(string.maketrans(char_from,char_to))
    

    Peut-etre cet ete a la mer.

  36. import re
    
    def strTr( text, dic ):
        """ Replaces keys of dic with values of dic in text.
            2005-02 by Emanuel Rumpf """
        pat = "(%s)" % "|".join( map(re.escape, dic.keys())  )
        return re.sub( pat, lambda m:dic[m.group()], text )
    
  37. #!/bin/env python
    
    from multiprocessing import Pool
    import time
    
    PARALLEL = 1
    
    def f(x):
        print "start sleeping"
        time.sleep(1)
        print "end sleeping"
        return x
    
    if __name__ == '__main__':
    
        l = xrange(15)
    
        if PARALLEL:
            pool = Pool()
            l2 = pool.map(f, l)
            pool.close()
            pool.join()
        else:
            l2 = map(f, l)
    
        print l2
    
  38. #!/usr/bin/python
    
    from AppKit import *
    
    WIDTH = 128
    HEIGHT = 64
    
    def draw_something():
        p = NSBezierPath.bezierPath()
    
        p.moveToPoint_((10, 10))
        p.lineToPoint_((50, 60))
        p.lineToPoint_((110, 10))
        p.lineToPoint_((10, 10))
    
        NSColor.redColor().set()
        p.fill()
    
        NSColor.blueColor().set()
        p.stroke()
    
    offscreenRep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(None, WIDTH, HEIGHT, 8, 4, True, False, NSCalibratedRGBColorSpace, 0, 4 * WIDTH, 32)
    
    context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(offscreenRep)
    
    NSGraphicsContext.setCurrentContext_(context)
    
    #NSGraphicsContext.saveGraphicsState()
    
    draw_something()
    
    #NSGraphicsContext.restoreGraphicsState()
    
    data = offscreenRep.representationUsingType_properties_(NSPNGFileType, None)
    
    result = data.writeToFile_atomically_("img.png", True)
    
  39. import DictionaryServices
    s = "love"
    print DictionaryServices.DCSCopyTextDefinition(None, s, (0,len(s)))
    

    love |lʌv| noun 1 a strong feeling of affection: ...

  40. from datetime import datetime
    from dateutil.parser import parse
    
    print parse("Tue, 22 Jul 2008 08:17:41 +0200")
    

    2008-07-22 08:17:41+02:00

    or

    from dateutil.parser import parse
    print parse("Tue, 22 Jul 2008 08:17:41 +0200")
    

    2008-07-22 08:17:41+02:00

  41. $ echo '{"foo": "lorem", "bar": "ipsum"}' | python -mjson.tool
    

    http://stackoverflow.com/questions/352098/how-to-pretty-print-json-script

  42. http://www.pythonware.com/products/pil/

    #!/usr/bin/python
    
    import Image, ImageDraw
    
    W = 255
    H = 128
    
    img = Image.new("RGB", (W, H), "black")
    draw = ImageDraw.Draw(img)
    
    for x in range(W):
        for y in range(H):
            color = (x % 255, y % 255, (x % (y+1)) % 255)
            draw.point((x,y), fill=color)
    
    draw.line((0, H/2, W, H/2), "yellow")
    draw.rectangle([(200, 60), (100, 120)], outline="#FF00FF")
    draw.text((20, 40), "quickies.seriot.ch")
    
    img.save("img.png", "PNG")
    
  43. import random
    random.choice(['a', 'b', 'c', 'd'])
    

    'b'

  44. fileinput reads lines sequentially, but doesn't keep them in memory.

    import fileinput
    
    for line in fileinput.input(['path']):
        print line
    
  45. import linecache
    linecache.getline('/etc/passwd', 4)
    
  46. >>> import datetime
    
    >>> datetime.datetime.strptime("20100225232300", "%Y%m%d%H%M%S")
    datetime.datetime(2010, 2, 25, 23, 23)
    

    docs.python.org format documentation

  47. Reading two 2-byte integers and one 4-byte integer in big-endian format from a file:

    import struct
    
    f = open(filename, "rb")
    s = f.read(8)
    x, y, z = struct.unpack(">hhl", s)
    

    The '>' in the format string forces big-endian data.

    The letter 'h' reads one "short integer" (2 bytes).

    The letter 'l' reads one "long integer" (4 bytes).

  48. and cheat where you can...

    #!/usr/bin/python
    # -*- coding: iso-8859-1 -*-
    
    import smtplib
    import time
    
    from_addr = "tintin@bluewin.ch"
    to_addrs  = ["milou@vtx.ch"]
    date = time.ctime(time.time())
    
    msg = """From: "Georges W. Bush" <bush@whitehouse.gov>
    Subject: Secret plan
    Date: %s
    To: "Donald Rumsfeld" <rumsfeld@whitehouse.gov>
    X-Mailer: Apple Mail (2.733)
    
    This is a test
    
    é à
    """ % date
    
    s = smtplib.SMTP('smtp.bluewin.ch')
    
    s.set_debuglevel(1)
    
    s.sendmail(from_addr, to_addrs, msg)
    
    s.quit()
    
  49. import paramiko # http://www.lag.net/paramiko/
    
    USERNAME = ""
    PASSWORD = ""
    PATH_LOCAL = ""
    PATH_REMOTE = ""
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=USERNAME, password=PASSWORD)
    
    ftp = ssh.open_sftp()
    ftp.put(PATH_LOCAL, PATH_REMOTE)
    ftp.close()
    
  50. class State:
        UNKNOWN, WAKE, SLEEP = range(3)
    
    state = State.UNKNOWN
    
  51. The following can be instanced several times, but all instances share the same state. Alex Martelli

    class Singleton:
        __shared_state = {}
        def __init__(self):
            self.__dict__ = self.__shared_state
    

    The following class returns the same instance for each instanciation.

    class Singleton(object):
        def __new__(type):
            if not '_the_instance' in type.__dict__:
                type._the_instance = object.__new__(type)
            return type._the_instance
    
  52. server.py

    import socket
    
    port = 8081
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("", port))
    print "waiting on port:", port
    while 1:
        data, addr = s.recvfrom(1024)
        print data
    

    client.py

    import socket
    
    port = 8081
    host = "localhost"
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("", 0))
    s.sendto("Holy Guido! It's working.", (host, port))
    

    Source : Jeff Bauer

  53. s = "1234567890"
    [s[i:i+3] for i in xrange(0, len(s), 3)]
    

    ['123', '456', '789', '0']

  54. $ python -m SimpleHTTPServer 8080
    
  55. class C:
    
        def foo(x, y):
            print "staticmethod", x, y
        foo = staticmethod(foo)
    
    C.foo(1, 2)
    c = C()
    c.foo(1, 2)
    

    Unifying types and classes in Python 2.2

  56. s = "asd"
    s.startswith(('a','b','c'))
    

    True

  57. Use this way, which takes a linear time:

    result = ''.join(strings)
    

    instead of this way, which takes a quadratic time:

    result = []
    for s in strings:
        result += s
    
  58. import sgmllib
    
    class Stripper(sgmllib.SGMLParser):
        def __init__(self):
            sgmllib.SGMLParser.__init__(self)
    
        def strip(self, some_html):
            self.theString = ""
            self.feed(some_html)
            self.close()
            return self.theString
    
        def handle_data(self, data):
            self.theString += data
    
    stripper = Stripper()
    print stripper.strip("<tag>asd</tag>")
    

    asd

  59. >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    
  60. #!/usr/bin/python

    """
    $ python tests.py
    $ python tests.py TestDemo
    $ python tests.py TestDemo.test_foo
    """


    import unittest

    class TestDemo(unittest.TestCase):

        def setUp(self):
            pass
            
        def tearDown(self):
            pass

        def test_foo(self):
            self.assertTrue('a' in 'asd')
            self.assertEqual(1+1, 2)
        
        def test_bar(self):
            pass

    if __name__ == '__main__':
        unittest.main()
  61. import subprocess
    op = subprocess.check_output(["ls", "-al"])
    print(op)
    
  62. #!/usr/bin/python
    
    from subprocess import *
    import os
    
    FIFO_PATH = '/tmp/my_fifo'
    
    if os.path.exists(FIFO_PATH):
        os.unlink(FIFO_PATH)
    
    if not os.path.exists(FIFO_PATH):
        os.mkfifo(FIFO_PATH)
        my_fifo = open(FIFO_PATH, 'w+')
        print "my_fifo:", my_fifo
    
    pipe = Popen('/bin/date', shell=False, stdin=PIPE, stdout=my_fifo, stderr=PIPE)
    
    print open(FIFO_PATH, 'r').readline()
    
    os.unlink(FIFO_PATH)
    
  63. import uuid
    uuid.uuid1()
    

    UUID('86e6df87-8546-11e1-aaeb-d49a20f5b3c2')

  64. import os
    
    def all_files_from_path_gen(p):
        for root, dirs, files in os.walk(p):
            for d in dirs:
                for f in files:
                    yield os.path.join(root, d, f)
    
    for path in all_files_from_path_gen('.'):
        print path
    
  65. import struct
    import ctypes
    
    bytes = ctypes.create_string_buffer(8)
    struct.pack_into('i', bytes, 0, 10)
    struct.pack_into('f', bytes, 4, 0.5)
    
    f = open("file.dat", 'wb')
    f.write(bytes)
    f.close()
    

    result

    $ hexdump file.dat 
    0000000 0a 00 00 00 00 00 00 3f                        
    0000008
    
  66. import sys
    
    sys.stderr.write("asd\n")
    
  67. server.py

    #!/usr/bin/python
    
    from SimpleXMLRPCServer import *
    
    class My_Web_Service:
        def __init__(self):
            pass
    
        # not callable through XML RPC because starts with '_'
        def _private(self):
            pass
    
        def add(self, x, y):
            return x + y
    
        def mul(self, x, y):
            return x * y
    
    if __name__ == "__main__":
        server = SimpleXMLRPCServer(("localhost", 8080))
        server.register_instance(My_Web_Service())
        server.serve_forever()
    

    client.py

    #!/usr/bin/python
    
    import xmlrpclib
    
    server = xmlrpclib.Server('http://localhost:8080')
    
    print server.add(3, 4)
    print server.mul(3, 4)
    
R
  1. $ R CMD INSTALL PACKAGE_NAME
    
Safari
  1. $ defaults write com.apple.Safari ProxiesInBookmarksBar ‘("Top Sites")’
    

    and back

    $ defaults write com.apple.Safari ProxiesInBookmarksBar '("Top Sites","Reading List")' 
    
  2. By default, the test search in Safari for Lion only finds words starting with a string, instead as words containing the string.

    To revert the default as in Snow Leopard:

    $ defaults write com.apple.Safari FindOnPageMatchesWordStartsOnly -bool FALSE
    
  3. $ defaults write com.apple.Safari WebKitHistoryItemLimit 2000
    $ defaults write com.apple.Safari WebKitHistoryAgeInDaysLimit 30
    
  4. Paste these URLs in the "Downloads" window.

  5. $ defaults write com.apple.Safari WebKitDeveloperExtras -bool true 
    

    see webkit.org

  6. $ defaults write com.apple.Safari IEFavoritesWereImported NO
    
  7. ... are listed in /Applications/Safari.app/Contents/Resources/Shortcuts.html

  8. x-man-page://ls
    

    the man page for ls will open in the terminal

  9. x-man-page://ls

  10. $ defaults write com.apple.Safari TargetedClicksCreateTabs -bool true
    
  11. Type the URL and hit cmd-enter.

  12. $ defaults write com.apple.Safari WebKitOmitPDFSupport -bool YES
    
  13. $ defaults write com.apple.Safari IncludeDebugMenu YES
    
sox
  1. $ sox dingding.wav -n spectrogram -o out.png
    
  2. $ cat /dev/urandom | sox -traw -r44100 -b16 -u - -tcoreaudio
    
Subversion
  1. $ svn add iPhone/Icon@2x.png@
    A  (bin)  iPhone/Icon@2x.png
    
  2. $ svn propset svn:ignore '*.pbxuser' '*.perspectivev3' MyProject.xcodeproj
    $ svn commit -m "added propset to exclude personnal project files"
    
  3. $ find . -name .svn -print0 | xargs -0 rm -rf
    

    great with an alias in your ~/.profile

    alias rmSVN="find . -name .svn -print0 | xargs -0 rm -rf"
    
  4. create the repository

    $ svnadmin create /Users/nst/Library/SVNRep --fs-type fsfs
    

    create the initial file tree

    $ mkdir /tmp/svn_layout
    $ mkdir /tmp/svn_layout/branches
    $ mkdir /tmp/svn_layout/tags    
    $ mkdir /tmp/svn_layout/trunk
    

    import the initial file tree

    $ svn import /tmp/svn_layout file:///Users/nst/Library/SVNRep -m "initial import"
    

    import a project

    $ svn import LifeLine file:///Users/nst/Library/SVNRep/trunk/LifeLine -m "LifeLine initial import"
    

    list the projects

    $ svn list file:///Users/nst/Library/SVNRep/trunk/
    

    get a project

    $ svn checkout file:///Users/nst/Library/SVNRep/trunk/LifeLine LifeLine
    

    display logs

    $ pwd
    /Users/nst/Documents/Projects/LifeLine
    $ svn log
    ------------------------------------------------------------------------
    r2 | nst | 2007-06-03 16:06:47 +0200 (Dim, 03 jui 2007) | 1 line
    
    LifeLine initial import
    ------------------------------------------------------------------------
    

    for the rest

    See the svnbook.

  5. $ svn log -v -r {`date -v-3d "+%Y-%m-%d"`}:HEAD
    

    https://twitter.com/zacwhite/statuses/1965487642

  6. Tag the current version:

    $ svn copy https://swisssms.googlecode.com/svn/trunk \
               https://swisssms.googlecode.com/svn/tags/release-1.2 \
               -m "tag on release 1.2"
    
    $ svn copy file:///Users/nst/Library/SVNRep/trunk/phpMyFlatSite \
               file:///Users/nst/Library/SVNRep/tags/mfs_0_1 \
               -m "tag on mfs 0.1"
    

    Tag a old version:

    $ svn copy -r 13 \
        https://swisssms.googlecode.com/svn/trunk \
        https://swisssms.googlecode.com/svn/tags/release-1.1 \
        -m "forgotten tag on release 1.1"
    
Swift
  1. $ xcrun swift
    Welcome to Swift!  Type :help for assistance.
      1> var x = "toto"
    x: String = "toto"
      2> println(x)
    toto
      3>  
    
TextMate
  1. $ svn diff | mate
    
Third-party applications
Unix
  1. data.txt

    380 EUR-USD
    105 EUR-CHF
    200 CHF-USD
    

    command

    $ awk '/EUR/ {print $1}' data.txt
    

    result

    380
    105
    
  2. stuff

    $ tar cjvf my_dir.tar.bz2 my_dir
    

    unstuff

    $ tar xjvf my_dir.tar.bz2
    
  3. Set the 4th byte of /tmp/test to 0xFF:

    $ printf '\xFF' | dd bs=1 seek=4 conv=notrunc of=/tmp/test
    
  4. $ sudo ifconfig en0 ether YOUR_NEW_ADDRESS_HERE
    
    $ ifconfig en0
    en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
            ether YOUR_NEW_ADDRESS_HERE 
            media: autoselect (none) status: inactive
            supported media: none autoselect 10baseT/UTP <half-duplex> ...
    
  5. $ touch -t 201206100230.00 x.txt
    
    $ ls -l x.txt 
    -rw-r--r--  1 nst  staff  0 Jun 10 02:30 x.txt
    
  6. $ iconv -c -f UTF-8 -t LATIN1 utf8.txt > latin1.txt
    
  7. $ openssl sha1 my_image.dmg
    
  8. On the client machine

    Generate keys (without passphrase)

    $ ssh-keygen -t rsa
    

    Copy the public key on the server

    $ scp ~/.ssh/id_rsa.pub nst@10.0.1.2:~/new_key
    

    On the server machine

    $ cat ~/new_key >> ~/.ssh/authorized_keys 
    $ rm new_key
    
  9. $ man -t ls | pstopdf -i -o ls.pdf
    
  10. $ date -r 1327307338
    Mon Jan 23 09:28:58 CET 2012
    
  11. $ tr '[:upper:]' '[:lower:]' < $1 > $2
    
  12. $ wc -l `find . -name "*.py" | awk '{print $1}'`
    
  13. cloc can't count the lines properly in multi-line Objective-C strings.

    It counts two lines instead of three here:

    NSString *s = "/* \
    x \
    */";
    

    The best way I can find is to use the cpp preprocessor:

    $ /usr/bin/cpp -fpreprocessed -P MyClass.m | grep -cve '^\s*$'
    
  14. $ dd if=/dev/urandom of=random.dat bs=1k count=128
    
  15. $ enscript --color --language=html -Epython --output=file.html file.py
    
  16. or any other header:

    $ curl -H "Cookie: KEY=VALUE" URL
    
  17. $ curl -u USER:PASSWORD URL
    
  18. $ curl -F "KEY=VALUE" URL
    
  19. $ curl -k URL
    
  20. data.txt

    <option>A</option>
    <option>B</option>
    <option>C</option>
    

    extract contents with cut

    $ cat data.txt | cut -d ">" -f 2 | cut -d "<" -f 1
    

    A
    B
    C

  21. $ ./hello
    Hello world
    
    $ xxd hello > hello.hex
    
    $ xxd -r hello.hex > hello2
    
    $ chmod hello2
    
    $ ./hello2
    Hello world
    

    Use -p for dumping and reloading a file without addresses.

  22. $ xxd -p hello
    
    $ hexdump -ve '1/1 "%.2x"' hello
    
    $ od -v -t x1 -An hello |tr -d '\n '
    
    $ od -t x4 -v hello
    
  23. $ cat *.m | sort | uniq -c | sort
    
  24. $ my_program > out.txt 2>&1 &
    
  25. $ file Base
    Base: Mach-O universal binary with 2 architectures
    Base (for architecture x86_64): Mach-O 64-bit executable x86_64
    Base (for architecture i386):   Mach-O executable i386
    
    $ lipo Base -extract i386 -output Base32
    
    $ file Base32
    Base32: Mach-O universal binary with 1 architecture
    
  26. $ find . -exec grep "my_string" '{}' \; -print
    

    or

    $ grep "$1" * -Ri
    

    useful with an alias

    $ alias ffind="grep $1 * -Ri"
    
  27. $ find . -name "*.txt" -print
    
  28. $ cd -
    
  29. $ egrep '.{6,}' data.txt
    
  30. strings digests

    MD5

    $ echo "asd" | md5
    e07910a06a086c83ba41827aa00b26ed
    

    now without digesting the trailing NUL

    $ md5 -s "asd"
    MD5 ("asd") = 7815696ecbf1c96e6894b779456d330e
    

    SHA

    $ echo "asd" | shasum -a 256
    dc460da4ad72c482231e28e688e01f2778a88ce31a08826899d54ef7183998b5  -
    

    -a may be 1 (default), 224, 256, 384, 512

    files digests

    $ echo "asd" > asd.txt
    

    MD5

    $ openssl dgst -md5 asd.txt
    MD5(asd.txt)= e07910a06a086c83ba41827aa00b26ed
    

    SHA

    $ openssl dgst -sha256 asd.txt
    SHA256(asd.txt)= dc460da4ad72c482231e28e688e01f2778a88ce31a08826899d54ef7183998b5
    
  31. $ history|awk '{a[$2]++ }END{for(i in a){print a[i]" "i}}'|sort -rn|head
    159 svn
    112 rm
    53 cd
    38 python2.5
    26 open
    12 ls
    9 python
    7 pdflatex
    6 whois
    6 locate
    
  32. $ lsof -i -a -p 99340
    
  33. $ sudo fs_usage -f filesys -w
    
  34. . R W X
    1 0 0 1
    2 0 1 0
    3 0 1 1
    4 1 0 0
    5 1 0 1
    6 1 1 0
    7 1 1 1
    
  35. $ du -c -h -s *
    184M    Books
    9.0G    Conferences
     20K    toto.csv
    
  36. $ wget -O - --post-data="login=0000000000&password=0000000000" "https://wifi.free.fr/Auth"
    
  37. $ ./xxx >> xxx.logs 2>&1
    
  38. $ man ls | col -bx > ls.txt
    
  39. $ man -f python
    Inline::Python(3pm)      - Write Perl subs and classes in Python
    pydoc(1)                 - the Python documentation tool
    python(1)                - an interpreted, interactive, object-oriented programming language
    python(1), pythonw(1)    - an interpreted, interactive, object-oriented programming language
    pythonw(1)               - run python script allowing GUI
    pythonw(1)               - run python script with GUI
    python2.7(1), python(1)  - an interpreted, interactive, object-oriented programming language
    
  40. $ df -k
    
  41. Into 15 lines chunks:

    $ split -l 15 text_file.txt text_file
    $ cat text_file* > text_file.txt
    

    Into 5 MB blocks:

    $ split -b 5m binary_file
    $ cat binary_file* > binary_file
    
  42. $ kill -STOP <PID>
    $ kill -CONT <PID>
    
  43. ssh stb@192.168.0.210 <<EOT
    touch test_file
    EOT
    exit 0
    
  44. $ find . -name "*.txt" -print | xargs zip -qr archive.zip
    
Xcode
  1. Here is an XCode run script build phase, setting your Cocoa app version to the latest date and svn revision each time you build. The values then appear in the Finder or in the application "About" panel.

    In the XCode Project view, click on your target. Choose Project menu > New Build Phase > New Run Script Build Phase. Put this script just before "Copy Bundle Resources". Set the ' CFBundleVersion^ value to __myBundleVersion__.

    Double-clic or apple-I on the Run Script build phase. Paste this python script. Don't forget to set the python path. Also check your svnversion, which may vary.

    Clean your projet, build and run it. You should be able to see something like this.

  2. add a breakpoint on objc_exception_throw

  3. $ defaults write com.apple.Xcode GenerateGraphVizFiles -bool YES
    

    Thank you 0xced.

  4. ctrl + arrow keys

  5. $ defaults write com.apple.Xcode NSRecentDocumentsLimit 25
    
  6. #pragma mark -
    #pragma mark NSTableDataSource protocol
    

  7. $ /Developer/usr/bin/xcodeindex -project MyProject.xcodeproj rebuild
    

    See also the dumpaction.

  8. $ defaults write com.apple.Xcode PBXBuildFailureSound ~/sound.mp3
    
  9. $ defaults write com.apple.xcode PBXCustomTemplateMacroDefinitions '{ORGANIZATIONNAME="MY_COMPANY SA";}'
    
  10. $ defaults delete com.apple.Xcode PBXExternalEditorList
    
  11. $ dwarfdump --uuid *.xcarchive/dSYMs/XXX.app.dSYM
    
    $ dwarfdump --lookup=0x0008157b *.xcarchive/dSYMs/XXX.app.dSYM