[categories] [index] [all (527)] [latest]
# apachectl graceful
$ 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
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
log class of myVariable
$ for f in *; do mv "$f" "$f.json"; done
no error
$ echo hello
$ echo $?
0
error
$ asdfg
$ echo $?
-bash: 127: command not found
$ echo -ne 'x41'
int n = 1;
int isLittleEndian = (*(char *)&n == 1);
// $ 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;
}
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.
int a[3]= { 1, 2, 3 };
int len = sizeof(a)/sizeof(*a);
$ /System/Library/CoreServices/talagent -memory_pressure
- (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"];
}
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]
[[NSProcessInfo processInfo] processName]
NSImage *image = [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kAlertNoteIcon)];
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
forKey:kCATransactionDisableActions];
myLayer.position = CGPointMake(x, y);
[CATransaction commit];
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
NSArray *runningApps = [ws valueForKeyPath:@"launchedApplications.NSApplicationName"];
[NSImage imageNamed:NSImageNameComputer]
[NSCursor hide];
[NSCursor unhide];
[NSCursor setHiddenUntilMouseMoves:YES];
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
BOOL appDidLaunch = [ws launchApplication:@"AnotherApp"];
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
$ defaults write ch.seriot.TheMachine NSShowAllViews YES
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:myURLString]];
- (void)drawRect:(NSRect)dirtyRect {
NSGraphicsContext *context = [NSGraphicsContext currentContext];
[context saveGraphicsState];
[context setShouldAntialias:NO];
// draw here
[context restoreGraphicsState];
[super drawRect:dirtyRect];
}
$ python -c "import AppKit; print AppKit.NSAppKitVersionNumber"
1187.0
[[NSWorkspace sharedWorkspace] selectFile:path inFileViewerRootedAtPath:path];
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
Download an Xcode demo project: CocoaPython.zip.
FILE *f = fopen("/bin/ssh", "r");
if (f != NULL) {
// jailbreak
}
fclose(f)
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
static MyClass *sharedInstance = nil;
+ (MyClass)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperationWithBlock:^{
CGFloat n = [self resultOfSomeMassiveComputation];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self updateOnMainThreadWithResult:n];
}];
}];
// MyClass.h
extern NSString * const kMyString;
// MyClass.m
NSString * const kMyString = @"xxx";
#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]
- (void)oldMethod __deprecated_msg("use new method instead");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"--");
});
$ 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
/Developer/Extras/64BitConversion/ConvertCocoa64 MyClass.m
> NSApplication sharedApplication delegate managedObjectContext inspectWithSystem:sys
- (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"];
}
NSString *formattedDate = [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S"];
2006-11-15 00:26:11
let myConcurrentQueue = dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT)
let group = dispatch_group_create()
dispatch_group_notify(group, dispatch_get_main_queue()) {
print("done")
}
for i in 0..<5 {
dispatch_group_async(group, myConcurrentQueue) {
print(i, NSThread.currentThread())
}
}
[NSThread currentThread]
+[NSThread callStackSymbols]
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"];
NSString *desktop = [NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) objectAtIndex:0];
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");
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);
}
Helps in diagnosing conflicts among classes:
-OBJC_PRINT_REPLACED_METHODS YES
- (instancetype)initWithParam:(id)param;
- (instancetype)init __attribute__((unavailable("use initWithParam:")));
NSDate *startDate = [NSDate date];
// ...
NSLog(@"%f seconds elapsed", [[NSDate date] timeIntervalSinceDate:startDate]);
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
#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);
}
NSArray *addresses = [[NSHost currentHost] addresses];
NSString *hostName = [[NSProcessInfo processInfo] hostName];
extension NSCalendar {
func numberOfDaysBetweenStartDate(startDate: NSDate, andEndDate endDate: NSDate) -> Int {
let startDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: startDate)
let endDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: endDate)
return endDay - startDay
}
}
NSUInteger dayOfYear = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:[NSDate date]];
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"
)
Run env OBJC_HELP=YES true
to see libobjc's recognized environment variables.
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
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"-> 1");
[NSThread sleepForTimeInterval:2];
NSLog(@"<- 1");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"-> 2");
[NSThread sleepForTimeInterval:4];
NSLog(@"<- 2");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"-> 3");
[NSThread sleepForTimeInterval:3];
NSLog(@"<- 3");
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"finished");
});
[[NSRunLoop currentRunLoop] run];
Logs:
-> 1
-> 2
-> 3
<- 1
<- 3
<- 2
finished
NSDictionary *errors;
NSAppleScript *quitApp;
quitApp = [[NSAppleScript alloc] initWithSource:@"tell application \"AnotherApplication\" to quit"];
[quitApp executeAndReturnError:&errors];
[quitApp release];
if(errors != nil) {
// manage error
}
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/
NSString *s = @"Hello World!";
NSString *re = @".*l{2}.*";
NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", re];
NSLog(@"Match: %d", [p evaluateWithObject:s]);
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;
}
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;
}
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
#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;
}
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_0) {
// <= 6.0
} else {
// > 6.0
}
#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 ================
- -- ---- -------- ----------------- -------- ---- -- -
+(MyClass *)sharedInstance {
static MyClass *sharedInstance = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
sharedInstance = [[MyClass alloc] init];
});
return sharedInstance;
}
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
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;
}
Thread safe code to be run only once with all other thread waiting at the barrier:
static dispatch_once_t onceToken;
dispatch_once (&onceToken, ^{
// ...
});
$ 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);
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
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"
SInt32 MacVersion = 0;
BOOL isRunningSnowLeopard = NO;
if (Gestalt(gestaltSystemVersionMinor, &MacVersion) == noErr) {
isRunningSnowLeopard = (MacVersion == 6);
}
NSLog(@"isRunningSnowLeopard %d", isRunningSnowLeopard);
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
@compatibility_alias UIColor NSColor;
#endif
[[NSUserDefaults standardUserDefaults] setObject:@YES forKey:@"UIUseLegacyUI"]
https://twitter.com/stroughtonsmith/status/384679231730761728
- (UIImage *)image {
UIGraphicsBeginImageContext(self.frame.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
application.statusBarHidden = YES;
// ...
}
[UIApplication sharedApplication].idleTimerDisabled = YES;
#ifdef DEBUG
[NSTimer scheduledTimerWithTimeInterval:1.0
target:application
selector:@selector(_performMemoryWarning)
userInfo:nil
repeats:YES];
#endif
po [UIView recursiveDescription]
results:
<UIView: 0x4b4d3d0; frame = (0 20; 320 460); (...)
| <MyView: 0x4b4b800; frame = (20 20; 237 243); (...)
| | <UIRoundedRectButton: 0x4b4e790; (...)
| | | <UIButtonLabel: 0x4b4f190; (...)
$ cvs co -r TagName ProjectName
$ cvs status -v project.pbxproj
$ cvs log -wnicolas -d"2006-04-01<2006-05-01" -S
$ find -d . -name 'CVS' -exec rm -rf '{}' \; -print
$ 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 -b install <package_name>
(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
(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:] ()'),
(gdb) thread apply all where
(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
# 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
$ git add -u
$ git log --format='%aN' | sort -u
$ git shortlog -n -s
$ git push --delete origin MY_TAG
$ git commit --amend -m "new message"
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
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
git tag -d TAG_NAME
delete remote tag 'TAG_NAME'
git push origin :refs/tags/TAG_NAME
or
git push --delete origin TAG_NAME
git tag -d TAG_NAME
$ git reset --hard
#!/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
$ 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
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
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
Append the KML url to https://maps.google.com/maps?q=
.
Example: https://maps.google.com/maps?q=http://seriot.ch/temp/radars.kml
$ sudo echo "127.0.0.1 pagead2.googlesyndication.com" >> /etc/hosts
encrypt
$ gpg -c file.txt
decrypt
$ gpg file.txt.gpg
$ defaults write com.apple.iCal "Default duration in minutes for new event" 15
$ defaults write com.apple.iCal IncludeDebugMenu YES
$ convert picture.jpg \
\( +clone -background black -shadow 70x4+5+5 \) +swap \
-background none -flatten -trim +repage picture.png
$ convert foo.png -resize 500x400 -background white -flatten foo.jpg
Source: http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=8359
$ echo "0x28 0x46" | llvm-mc --disassemble -triple=thumbv7
.text
mov r0, r5
$ echo "mov r0, r5" | llvm-mc -assemble -triple=thumbv7 -show-encoding
.text
mov r0, r5 @ encoding: [0x28,0x46]
$ echo "movs r0, 0x1" | llvm-mc -assemble -triple=thumbv7 -show-encoding
.text
movs r0, #1 @ encoding: [0x01,0x20]
See also iOS binary patching: http://www.zdziarski.com/blog/?p=2172
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')
#import <QuartzCore/QuartzCore.h>
...
view.layer.borderColor = [UIColor blackColor].CGColor;
view.layer.borderWidth = 1;
$ rvictl -s UDID
$ sudo launchctl list com.apple.rpmuxd
$ sudo tcpdump -n -t -i rvi0 -q tcp
$ codesign -d --entitlements - MyApp.app
the result should include:
<key>aps-environment</key>
<string>production</string>
With an iPhone, dial and call:
*3001#12345#*
Add them into scheme > arguments
-AppleLanguages (de)
-AppleLocale fr_FR
po [[[UIApplication sharedApplication] keyWindow] recursiveDescription]
#if os(iOS)
#elseif os(tvOS)
#else
#endif
$ export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
$ codesign -fs "MyName" MyBinary
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
// ...
}
xcrun simctl io booted recordVideo movie.mp4
$ defaults write com.apple.dock itunes-notifications -bool TRUE
String username = System.getProperty("user.name");
InputStream is = this.class.getResourceAsStream("file.txt");
$ jar xvf myjar.jar
data:text/html,
<canvas id=x>
<script>
X = x.getContext("2d");
X.fillRect(10, 10, 20, 20)
</script>
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}
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}
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}
\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}
Avec le paquetage pst-tree.
\pstree{\Tcircle{A}}
{\pstree{\Tcircle{B}}
{\Tcircle{D}
\Tcircle{E}}
\pstree{\Tcircle{C}}
{\Tcircle{F}
\Tcircle{G}}}
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}
}
}
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}
}
}
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}}
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}
}
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 !
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}
en mode mathématique
\left\{ \begin{array}{rrrrr}
-9a & -2b & +6c & = & 11a \\
6a & -6b & +7c & = & 11b \\
2a & +9b & +6c & = & 11c
\end{array}
\right
\begin{eqnarray*}
\cos 2\theta & = & \cos^2 \theta - \sin^2 \theta \\
& = & 2 \cos^2 \theta - 1
\end{eqnarray*}
Avec la macro code128.
\input code128
\codetext{021\ seriot.ch} % avec texte
%\code{021\ seriot.ch} % sans texte
Avec la macro ean.
\input ean13
\ISBN 2-88074-488-1 \EAN 9-782880-744885
...
\input ean8
\EAN 1234-5670
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.
Avec le paquetage example:
\begin{example}
$$
\sum_{n=1}^{10} \cdot
\int_a^b e^{x} ~ dx
$$
\end{example}
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}
(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
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}
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}
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}
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}
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}
Avec le paquetage setspace :
\singlespace
\onehalfspace
\doublespace
Just draw the symbol you are looking for.
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}
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}
\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
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}
\marginpar{Ben tiens !}
On écrit $a\equiv b\pmod{c}$, \\
mais aussi $a = b \bmod c$.
Add an additional directory path for \includegraphics
\graphicspath{{./images/}}
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.
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}
\usepackage{eurosym}
\euro
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}
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}
\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}
Avec le paquetage ulem.
\sout{texte barré}
Avec le paquetage soul.
\st{texte barré}
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}.
Avec le paquetage multicol.
\begin{multicols}{3}
...
\end{multicols}
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}.
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.
Avec le paquetage url :
\newcommand\email{\begingroup \urlstyle{rm}\Url}
\newcommand\web{\begingroup \urlstyle{tt}\Url}
...
\email{nicolas@seriot.ch}
...
\web{http://seriot.ch}
To show applications opening JPEG files, search for uti:public.jpeg
.
Search for "extension:md" for instance.
$ defaults write -g ApplePressAndHoldEnabled -bool false
$ defaults write com.apple.Mail DisableSendAnimations -bool YES
$ defaults write com.apple.Mail DisableReplyAnimations -bool YES
ie disable Resume
per application:
$ defaults write com.apple.Preview NSQuitAlwaysKeepsWindows -int NO
$ defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool NO
In column mode, double-clic on the ||.
$ defaults write -g NSNavPanelExpandedStateForSaveMode -bool YES
$ atos -o MyiPhoneBinary -arch armv7 0x00009f16
-[AppDelegate application:didFinishLaunchingWithOptions:] (in MyiPhoneBinary) (AppDelegate.m:253)
enable:
$ sudo nvram boot-args="-v"
disable:
$ sudo nvram boot-args=
$ defaults write /Library/Preferences/com.apple.loginwindow DesktopPicture /picture.jpg
$ defaults write com.apple.screencapture location ~/Pictures
$ killall SystemUIServer
$ defaults write com.apple.screencapture type jpg
$ killall SystemUIServer
type may be jpg, pdf, tif or png
$ 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
$ defaults write com.apple.dashboard mcx-disabled -boolean YES
$ killall Dock
$ defaults write com.apple.mail DisableDataDetectors YES
$ defaults write com.apple.iTunes disableGeniusSidebar YES
$ defaults write NSGlobalDomain AppleEnableMenuBarTransparency -bool false
$ launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist
$ killall NotificationCenter
$ defaults write -g NSScrollAnimationEnabled -bool false
$ defaults write com.apple.dock workspaces-swoosh-animation-off -bool YES
$ killall Dock
$ defaults write com.apple.screencapture disable-shadow -bool true
$ killall SystemUIServer
$ defaults write com.apple.mail PreferPlainText -bool YES
$ defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo SystemVersion
SystemVersion
can be replaced by:
SystemBuild
SerialNumber
IPAddress
DSStatus
Time
HostName
$ /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -S
See the help page:
$ airport --help
$ defaults write com.apple.dock no-glass -boolean YES
$ defaults write com.apple.DiskUtility DUDebugMenuEnabled -bool true
$ defaults write com.apple.appstore ShowDebugMenu -bool true
Source: http://www.red-sweater.com/blog/1586/the-mac-app-store-debug-menu
cmd + F1
$ defaults write com.apple.finder QLEnableTextSelection -bool TRUE; killall Finder
The simplest way:
Start with cmd-S, then
# mount /
# rm /var/db/.AppleSetupDone
# reboot
and create a new admin account through the assistant.
$ defaults write com.apple.dock mouse-over-hilte-stack -boolean YES
~/Library/Application Support/iLifeAssetManagement/assets/sub/
$ defaults write com.apple.dock largesize -float 200
$ killall Dock
128 is the default
$ hdiutil attach disk_image.dmg
$ cd /Volumes/volume_name/
$ sudo installer -pkg package_name.pkg -target "/"
$ hditutil detach /Volumes/volume_name/
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
$ sw_vers -productVersion
$ defaults write com.apple.mail AddressesIncludeNameOnPasteboard -bool NO
$ /Developer/Tools/SetFile -a V my_file.txt
$ defaults write com.apple.Dock showhidden -bool YES
$ open -a Terminal `pwd`
great with an alias in your ~/.profile
alias new="open -a Terminal `pwd`"
$ defaults write com.apple.dock launchanim -bool false
$ sudo pmset lidwake 0
$ 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.
cmd-R
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
Check the following directories:
"~/Library/Developer/Xcode/iOS DeviceSupport/"
"~/Library/Developer/Shared/Documentation/DocSets/"
$ defaults write NSGlobalDomain NSSavePanelStandardDesktopShortcutOnly -bool YES
$ defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
$ defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES
$ defaults write com.apple.addressbook ABShowDebugMenu -bool YES
(and probably other fancy behaviors)
# mkdir /AppleInternal
$ defaults write com.apple.dock static-only -bool TRUE
$ killall Dock
# dmesg
$ defaults write com.apple.desktopservices DSDontWriteNetworkStores true
$ /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background
$ 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
~/Library/Caches/Metadata/app.bundle.identifier
$ 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'
$ /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/AppleMobileDeviceHelper.app/Contents/Resources/AppleMobileBackup --help
$ atos -o MyiPhoneBinary -arch armv7 0x00009f16
-[AppDelegate application:didFinishLaunchingWithOptions:] (in MyiPhoneBinary) (AppDelegate.m:253)
$ ioreg -l | grep Capacity
| | "MaxCapacity" = 4047
| | "CurrentCapacity" = 3901
| | "LegacyBatteryInfo" = {"Amperage"=18446744073709548440,
"Flags"=4,"Capacity"=4047,
"Current"=3901,
"Voltage"=11976,
"Cycle Count"=283}
| | "DesignCapacity" = 4600
$ install_name_tool -change libbz2.1.0.2.dylib @executable_path/../Frameworks/libbz2.1.0.2.dylib MyFunBinary
$ pmset -g
sleep 0 (imposed by 6783)
here, process 6783 is responsible
$ sudo gcc_select 3.3
$ sudo gcc_select 4.0
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
for i in *.HEIC; do sips -Z 2016 format jpeg -s formatOptions 80 "${i}" --out "${i%HEIC}jpg"; done
$ plutil -convert xml1 foo.plist
$ plutil -convert binary1 bar.plist
$ diskutil erasevolume HFS+ 'RAM Disk' `hdiutil attach -nomount ram://204800`
hdiutil create -fs HFS+ -volname VOL_NAME -srcfolder SRC DST.dmg
$ sudo mdutil -E -i on /
$ defaults write com.apple.ImageCapture disableHotPlug -bool YES
$ defaults write com.apple.LaunchServices LSQuarantine -bool NO
on a file basis
$ xattr -d com.apple.quarantine PATH
$ sudo mdutil -E off -d /
sqlite3 ~/Library/Safari/CloudTabs.db "select url from cloud_tabs;"
Requires to disable SIP.
$ /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump
$ defaults write com.apple.NetworkBrowser BrowseAllInterfaces 1
$ 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
$ /System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc
> 1+1
2
Prevent /usr/bin/login
from searching the system logs so that it can display the date and time of your last login.
$ touch .hushlogin
$ sudo opensnoop -f /path/to/file
$ sudo opensnoop -n Terminal
$ sudo opensnoop -p <pid>
$ sudo update_prebinding -root /
End the directory name with .noindex
$ defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences RememberedNetworks | grep SSID_STR
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
# diskutil repairPermissions /
With sips
, a built-in Mac OS X tool.
$ sips -Z 640 *.jpg
$ sudo periodic daily weekly monthly
# softwareupdate -i -a
no need to open Mac App Store
$ otool -v -s __TEXT __objc_methname RuntimeBrowser
RuntimeBrowser:
Contents of (__TEXT,__objc_methname) section
0x000000010000b450 init
0x000000010000b455 mainBundle
0x000000010000b460 pathForResource:ofType:
...
$ defaults write NSGlobalDomain InitialKeyRepeat -int 7
$ defaults write NSGlobalDomain KeyRepeat -int 0
Here, smaller is better.
$ 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)
$ sudo spctl --master-disable
Can replace unix find:
$ mdfind -onlyin ~/Documents Leopard
$ spctl --assess --verbose=4 /Applications/Notes.app
/Applications/Notes.app: accepted
source=Apple System
defaults write com.apple.TextEdit NSShowAppCentricOpenPanelInsteadOfUntitledFile -bool false
update the database
$ sudo /usr/libexec/locate.updatedb
use the database
$ locate my_report
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
$ sudo xcode-select /Library/Developer/CommandLineTools/
$ xcode-select --print-path
/Library/Developer/CommandLineTools
$ chflags nohidden ~/Library
$ defaults write com.apple.NetworkBrowser BrowseAllInterfaces 1
$ defaults write com.apple.finder QuitMenuItem -bool YES
$ sudo mv Desktop Desktop_original
$ ln -s Projects Desktop
$ killall Finder
$ defaults write com.apple.finder DisableAllAnimations -bool yes
$ defaults write com.apple.finder AppleShowAllFiles TRUE
hit the enter
key
$ defaults write com.apple.finder EmptyTrashSecurely -bool true
$ defaults write com.apple.finder CreateDesktop -bool False
Drop the directory on the Print Center.
$ defaults read com.apple.desktop Background
Achieves the same as in Finder Preferences.
$ defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
from pylab import *
x = arange(0, 10, 0.2)
y = sin(x)
plot(x, y)
show()
[hostfingerprints]
my.server.com = 07:a0:bd:32:6e:2f:81:58:92:e9:60:d4:e4:83:7a:48:43:d3:5a:c4
[auth]
repo.prefix = https://my.repository.com:444/hg/xxx/
repo.username = nseriot
repo.password = password
[ui]
username = Nicolas Seriot <nicolas.seriot@xxx.com>
like git commit --amend
$ hg rollback
$ hg commit -m "new message"
$ 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
$ hg diff -r tag1:tag2
$ hg pull --insecure https://server/repository
hg tag -r 1220 new_tag
hg tag --remove old_tag
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
raise `my_var`
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');
mysql> ALTER TABLE nm_newsitem ADD CONSTRAINT unique_link UNIQUE (link(255));
mysql> ALTER TABLE my_table ADD INDEX(my_col);
mysql> ANALYZE TABLE my_table;
mysql> USE my_db;
$ mysql -u user_name -p
mysql> DESCRIBE my_table;
mysql> SHOW TABLES;
$ mysqldump --opt --user=username --password database > dumpfile.sql
$ mysqldump --user my_user --password=my_password database > dumpfile.sql
$ mysqldump --no-data --opt --user=root --password news_memory > tables.sql
$ mysql --user=username --password database < dumpfile.sql
mysql> INSERT INTO my_table VALUES ('','France','fr');
$ /usr/local/mysql/bin/mysqladmin -u root password xxxxxxxx
mysql> UPDATE my_table SET my_table.my_row_1 = 'Lausanne' WHERE my_table.my_row_2 = 2338;
mysql> OPTIMIZE TABLE my_table;
ALTER TABLE my_table AUTO_INCREMENT=1;
The value is the one that will be used next.
update <table> set <champ> = replace(<champ>,'<avant>','<apres>');
$ sudo mysqld_safe --user=root &
$ mysqladmin -u root --password=xxxxxxxx shutdown
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;
Since MySQL 4.1 :
mysql> ALTER TABLE ma_table MODIFY ma_colonne CHAR(150) CHARACTER SET utf8;
$ ncftp
ncftp> open -u catane colons.seriot.ch
Password:
ncftp / >
nc -l 5000
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 rsa -in pri.pem -modulus -noout
Modulus=E5EC8AFD
$ echo "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobed3lKVSW7OB5ufeoLR
hunKSX5pjmqcFypG2d+RPRCFRslNZJTzt6XJ6zwBftcORmJJWC1No7cbTmhmbq+r
q3MJ1azR4mTTyL462K+KEJx9oOASdruBmE4YDOJ3q9noTRARmfLy747udLzFVuam
kmtkAWvpyePq0aQanK6HHyhoklA2hs38eV0X2RVDLC+sbmNlXQ+elRan3jr+rVyf
iWr01C0yS6vAaIrDAk6FgHuDNMi9EzfSuJe9ixHOqdLSHjE17xcZUJi2Hydvh3VW
O2X+fDVGSKgAV7j4rV9691vKTS/PerPrlP+I9nmTVC+28LK2Sur5jNw153RqFSJ2
dQIDAQAB
-----END PUBLIC KEY-----" | openssl rsa -pubin -modulus -noout
Modulus=A1B79DDE5295496ECE079B9F7A82D186E9CA497E698E6A9C172A46D9DF913D108546C94D6494F3B7A5C9EB3C017ED70E466249582D4DA3B71B4E68666EAFABAB7309D5ACD1E264D3C8BE3AD8AF8A109C7DA0E01276BB81984E180CE277ABD9E84D101199F2F2EF8EEE74BCC556E6A6926B64016BE9C9E3EAD1A41A9CAE871F286892503686CDFC795D17D915432C2FAC6E63655D0F9E9516A7DE3AFEAD5C9F896AF4D42D324BABC0688AC3024E85807B8334C8BD1337D2B897BD8B11CEA9D2D21E3135EF17195098B61F276F8775563B65FE7C354648A80057B8F8AD5F7AF75BCA4D2FCF7AB3EB94FF88F67993542FB6F0B2B64AEAF98CDC35E7746A15227675
$ openssl rsa -text -in pri.pem -noout
Private-Key: (50 bit)
modulus: 932104465369093 (0x34fbe7b8d4805)
publicExponent: 65537 (0x10001)
privateExponent: 714399564038593 (0x289be1c3e01c1)
prime1: 30607469 (0x1d3086d)
prime2: 30453497 (0x1d0aef9)
exponent1: 19335801 (0x1270a79)
exponent2: 15609409 (0xee2e41)
coefficient: 27047014 (0x19cb466)
$ openssl x509 -pubkey -noout -in crt.pem
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobed3lKVSW7OB5ufeoLR
hunKSX5pjmqcFypG2d+RPRCFRslNZJTzt6XJ6zwBftcORmJJWC1No7cbTmhmbq+r
q3MJ1azR4mTTyL462K+KEJx9oOASdruBmE4YDOJ3q9noTRARmfLy747udLzFVuam
kmtkAWvpyePq0aQanK6HHyhoklA2hs38eV0X2RVDLC+sbmNlXQ+elRan3jr+rVyf
iWr01C0yS6vAaIrDAk6FgHuDNMi9EzfSuJe9ixHOqdLSHjE17xcZUJi2Hydvh3VW
O2X+fDVGSKgAV7j4rV9691vKTS/PerPrlP+I9nmTVC+28LK2Sur5jNw153RqFSJ2
dQIDAQAB
-----END PUBLIC KEY-----
from Crypto.PublicKey import RSA
pem = open("pub.pem").read()
key = RSA.importKey(pem)
print(key.n)
$ 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
With GhostScript:
$ gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf a.pdf b.pdf
$ java -classpath Multivalent20040415.jar tool.pdf.Decrypt file.pdf
$ pg_dump -s DB_NAME -t TABLE_NAME
$ postgres=# \l
65 1 string dup 0 4 -1 roll put
or
/s ( ) def
s 0 65 put
/MyDict
<<
/MyKey1 (asd)
/MyKey2 { (sdf) }
>> def
MyDict (MyKey1) get == % (asd)
MyDict (MyKey2) get == % { (sdf) }
MyDict (MyKey3) get == % undefined
bind def
: add
lookup occurs once at definition:
save
/foo { add } bind def
1 2 foo == % 3
/add { mul } def
1 2 foo == % 3, uses original add
restore
def
alone: add
lookup occurs each time:
save
/foo { add } def
1 2 foo == % 3
/add { mul } def
1 2 foo == % 2, uses redefined add
restore
MyDict {
/v exch def
/k exch def
} forall
connect on port 9100:
nc 192.168.1.10 9100
type this:
%
executive
get that:
PostScript(r) Version 3018.102
(c) Copyright 1984-2004 Adobe Systems Incorporated.
Typefaces (c) Copyright 1981 Linotype-Hell AG and/or its subsidiaries.
All Rights Reserved.
PS>
systemdict (product) get
%!PS-Adobe-2.0
% gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile="output-%d.pdf" m.ps
/Courier findfont 12 scalefont setfont
50 700 moveto
1 20 string cvs show
showpage
50 700 moveto
2 20 string cvs show
showpage
50 700 moveto
3 20 string cvs show
showpage
/printUsage {
(Usage:) =
( a - some stuff) =
( b - other stuff) =
( q - quit) =
} def
printUsage
{
/userInput 128 string def
(>) print flush
(%lineedit) (r) file userInput readline
pop % bool
token not { () } if
{
dup (q) eq { quit } if
dup (a) eq {
pop token pop
(a) =
exit
} if
dup (b) eq {
pop token pop
(b) =
exit
} if
clear
printUsage
exit
} loop
} loop
999 3 string cvs print
(=======================================) ==
pstack
(=======================================) ==
quit
Ghostscript specific:
=only
and
==only
See https://stackoverflow.com/questions/57983225/postscript-tokens-string-only-etc
/userInput 128 string def
(>) print flush
(%lineedit) (r) file userInput readline
pop % bool
{ token not{exit}if == } loop
%!PS
% nc 172.16.158.21 9100
/Courier findfont 12 scalefont setfont
32 740 moveto
/s 100 string def
(>) print flush
(%lineedit) (r) file s readline
pop
show
showpage
$ python cars.py
Ford, blue
Ferrari, pink
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
{'a': 1, 'c': 3, 'b': 2}
>>> dict((k, []) for k in ['a', 'b', 'c'])
{'a': [], 'c': [], 'b': []}
>>> 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)
import my_module
f = getattr(my_module, 'my_function')
result = f()
or
globals()["my_function"]()
or
locals()["my_function"]()
class C:
def foo(cls, y):
print "classmethod", cls, y
foo = classmethod(foo)
C.foo(1)
c = C()
c.foo(1)
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
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)
import cProfile, pstats, io
from pstats import SortKey
# ...
pr = cProfile.Profile()
pr.enable()
f() # <- code to profile here
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
>>> import datetime
>>> import time
>>> dt = datetime.datetime(2010, 2, 25, 23, 23)
>>> time.mktime(dt.timetuple())
1267136580.0
s_latin1 = unicode(s_utf8, 'utf-8').encode('latin-1', 'replace')
sum(1 for line in open('myfile.txt'))
>>> import datetime
>>> datetime.datetime.fromtimestamp(1294236000)
datetime.datetime(2011, 1, 5, 15, 0)
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
#!/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)
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'
$ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
/Library/Python/2.5/site-packages
import pdb
pdb.set_trace()
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)
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();
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()
>>> 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]
write:
for x in data:
if meets_condition(x):
break
else:
# raise error or do additional processing
instead of:
condition_is_met = False
for x in data:
if meets_condition(x):
condition_is_met = True
if not condition_is_met:
# raise error or do additional processing
http://shahriar.svbtle.com/pythons-else-clause-in-loops
import random
random.sample(xrange(100), 3)
[32, 49, 0]
from random import randint
randint(0, 2)
0, 1 or 2
import sys
if sys.byteorder == "little":
print "little-endian platform (intel, alpha)"
else:
print "big-endian platform (motorola, sparc)"
import os
for param in os.environ.keys():
print "%20s %s" % (param, os.environ[param])
import inspect
def f():
a = 1 + 2
return a
s = inspect.getsource(f)
print s
"""
def f():
a = 1 + 2
return a
"""
lines, start = inspect.getsourcelines(f)
print lines
"""
['def f():n', ' a = 1 + 2n', ' return an']
"""
import socket
print socket.gethostbyname(socket.gethostname())
192.168.0.231
print f.__name__
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']
#!/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"
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
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()
#!/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)
#!/usr/bin/python
import os
print "-- will kill"
pid = os.getpid()
print "-- pid:", pid
os.kill(pid, 1)
print "-- did kill"
import popen2
(stdout, stdin, stderr) = popen2.popen3("ping -q -c2 www.google.com")
print stdout.readlines()
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()
python2.7 -c 'import sys,objc;from Foundation import NSBundle as nb;f="SACLockScreenImmediate";objc.loadBundleFunctions(nb.bundleWithPath_(sys.argv[1]),globals(),[(f,"@")]);exec(f+"()")' /S*/L*/P*/l*.f*
Source: https://gist.github.com/pudquick/9797a9ce8ad97de6e326afc7c9894965 through @gorelics
# -*- 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.
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 )
#!/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
#!/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)
import DictionaryServices
s = "love"
print DictionaryServices.DCSCopyTextDefinition(None, s, (0,len(s)))
love |lʌv| noun 1 a strong feeling of affection: ...
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
$ echo '{"foo": "lorem", "bar": "ipsum"}' | python -mjson.tool
http://stackoverflow.com/questions/352098/how-to-pretty-print-json-script
from time import strftime
strftime("%Y-%m-%d %H:%M:%S")
2016-08-27 14:09:48
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")
import random
random.choice(['a', 'b', 'c', 'd'])
'b'
fileinput
reads lines sequentially, but doesn't keep them in memory.
import fileinput
for line in fileinput.input(['path']):
print line
import linecache
linecache.getline('/etc/passwd', 4)
>>> import datetime
>>> datetime.datetime.strptime("20100225232300", "%Y%m%d%H%M%S")
datetime.datetime(2010, 2, 25, 23, 23)
docs.python.org format documentation
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).
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()
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()
import keyword
keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> import cairo
>>> print(cairo)
<module 'cairo' from '/usr/local/lib/python3.9/site-packages/cairo/__init__.py'>
Source: @nedbat
class State:
UNKNOWN, WAKE, SLEEP = range(3)
state = State.UNKNOWN
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
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
s = "1234567890"
[s[i:i+3] for i in xrange(0, len(s), 3)]
['123', '456', '789', '0']
$ python -m SimpleHTTPServer 8080
class C:
def foo(x, y):
print "staticmethod", x, y
foo = staticmethod(foo)
C.foo(1, 2)
c = C()
c.foo(1, 2)
s = "asd"
s.startswith(('a','b','c'))
True
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
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
>>> 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!
import subprocess
op = subprocess.check_output(["ls", "-al"])
print(op)
#!/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)
Generate project requirements
pip3 install pipreqs
pipreqs /path/to/project
Then
pip3 install -r requirements.txt
import uuid
uuid.uuid1()
UUID('86e6df87-8546-11e1-aaeb-d49a20f5b3c2')
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
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
import sys
sys.stderr.write("asd\n")
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 CMD INSTALL PACKAGE_NAME
$ defaults write com.apple.Safari ProxiesInBookmarksBar ‘("Top Sites")’
and back
$ defaults write com.apple.Safari ProxiesInBookmarksBar '("Top Sites","Reading List")'
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
$ defaults write com.apple.Safari WebKitHistoryItemLimit 2000
$ defaults write com.apple.Safari WebKitHistoryAgeInDaysLimit 30
Paste these URLs in the "Downloads" window.
$ defaults write com.apple.Safari WebKitDeveloperExtras -bool true
see webkit.org
$ defaults write com.apple.Safari IEFavoritesWereImported NO
... are listed in /Applications/Safari.app/Contents/Resources/Shortcuts.html
x-man-page://ls
the man page for ls will open in the terminal
x-man-page://ls
$ defaults write com.apple.Safari TargetedClicksCreateTabs -bool true
Type the URL and hit cmd-enter.
$ defaults write com.apple.Safari WebKitOmitPDFSupport -bool YES
$ defaults write com.apple.Safari IncludeDebugMenu YES
use the text-shadow
property
$ sox dingding.wav -n spectrogram -o out.png
$ cat /dev/urandom | sox -traw -r44100 -b16 -u - -tcoreaudio
$ svn add iPhone/Icon@2x.png@
A (bin) iPhone/Icon@2x.png
$ svn propset svn:ignore '*.pbxuser' '*.perspectivev3' MyProject.xcodeproj
$ svn commit -m "added propset to exclude personnal project files"
$ 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"
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.
$ svn log -v -r {`date -v-3d "+%Y-%m-%d"`}:HEAD
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"
if ("ABCDE" as NSString).containsString("BC") {
println("Containing")
}
let group = dispatch_group_create()
let mainQueue = dispatch_get_main_queue()
for i in 1...10 {
dispatch_group_enter(hgReadGroup)
longSubTask(param:String, completionHandler: { (results) -> () in
// ...
dispatch_group_leave(group)
})
}
dispatch_group_notify(group, mainQueue) {
print("-> all subtasks are finished")
completionHandler(entries:entries)
}
let date = NSDate()
let name: AnyClass! = object_getClass(date) // __NSDate
let string = "Hello"
let name = string.dynamicType // Swift.String
also:
class MyClass { }
let o : AnyObject = MyClass()
print(o is String) // false
print(o is MyClass) // true
guard let data = optionalData,
optionalDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? [String:AnyObject],
d = optionalDict,
latestVersionString = d["latest_version_string"] as? String,
latestVersionURL = d["latest_version_url"] as? String else {
return
}
static var x = {
// ...
return xxx
}()
let date = NSDate()
let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: date)
$ xcrun swift
Welcome to Swift! Type :help for assistance.
1> var x = "toto"
x: String = "toto"
2> println(x)
toto
3>
private var stravaAPI : StravaAPI = {
return StravaAPI()
}()
public class Person {
public private(set) var name: String
// ...
}
#!/usr/bin/swift
/*
$ swift x.swift
*/
import Foundation
for arg in Process.arguments {
print(arg)
}
static let dateFormatter: NSDateFormatter = {
let df = NSDateFormatter()
df.dateFormat = "yyyyMMdd"
return df
}()
struct Board {
var cells : [[Int]]
init(row:Int, columns:Int) {
self.cells = [[Int]]()
for _ in 0..<row {
self.cells.append([Int](count: columns, repeatedValue: 0))
}
}
subscript(row: Int, column: Int) -> Int {
get {
return cells[row][column]
}
set {
cells[row][column] = newValue
}
}
}
var b = Board(row: 3, columns: 4)
b[1,1] = 1
print(b[1,1])
#!/usr/bin/env xcrun --toolchain com.apple.dt.toolchain.XcodeDefault swift
// -F/my/frameworks add to search path
// -framework MyUtils.framework load framework
// -D FLAG compilation flag
import Foundation
print(CommandLine.arguments)
class MyClass {
static let sharedInstance = MyClass()
}
$ svn diff | mate
youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio' --merge-output-format mp4
Requires ffmpeg
chrome://flags/#enable-tab-audio-muting
data.txt
380 EUR-USD
105 EUR-CHF
200 CHF-USD
command
$ awk '/EUR/ {print $1}' data.txt
result
380
105
rsync -av --delete /src/ /dst/
stuff
$ tar cjvf my_dir.tar.bz2 my_dir
unstuff
$ tar xjvf my_dir.tar.bz2
Set the 4th byte of /tmp/test
to 0xFF
:
$ printf '\xFF' | dd bs=1 seek=4 conv=notrunc of=/tmp/test
$ 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> ...
$ touch -t 201206100230.00 x.txt
$ ls -l x.txt
-rw-r--r-- 1 nst staff 0 Jun 10 02:30 x.txt
$ iconv -c -f UTF-8 -t LATIN1 utf8.txt > latin1.txt
$ openssl sha1 my_image.dmg
$ nc -z -u time.euro.apple.com 123
Connection to time.euro.apple.com port 123 [udp/ntp] succeeded!
Google Chrome > bookmarks.html > raw URLs
grep -o 'http[^\"]*' bookmarks.html
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
$ man -t ls | pstopdf -i -o ls.pdf
$ date -ur 1234567890
Fri Feb 13 23:31:30 UTC 2009
$ tr '[:upper:]' '[:lower:]' < $1 > $2
$ wc -l `find . -name "*.py" | awk '{print $1}'`
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*$'
$ dd if=/dev/urandom of=random.dat bs=1k count=128
$ enscript --color --language=html -Epython --output=file.html file.py
or any other header:
$ curl -H "Cookie: KEY=VALUE" URL
$ curl -u USER:PASSWORD URL
$ curl -F "KEY=VALUE" URL
$ curl -k URL
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
$ ./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.
$ xxd -p hello
$ hexdump -ve '1/1 "%.2x"' hello
$ od -v -t x1 -An hello |tr -d '\n '
$ od -t x4 -v hello
$ cat *.m | sort | uniq -c | sort
$ my_program > out.txt 2>&1 &
$ 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
$ find . -exec grep "my_string" '{}' \; -print
or
$ grep "$1" * -Ri
useful with an alias
$ alias ffind="grep $1 * -Ri"
$ find . -name "*.txt" -print
$ cd -
$ egrep '.{6,}' data.txt
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
$ 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
$ lsof -i -a -p 99340
$ sudo fs_usage -f filesys -w
$ ncftp
> open -u ******** -p ******** ftp.seriot.ch
. 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
$ du -c -h -s *
184M Books
9.0G Conferences
20K toto.csv
$ wget -O - --post-data="login=0000000000&password=0000000000" "https://wifi.free.fr/Auth"
$ ./xxx >> xxx.logs 2>&1
$ ./screenshooter &
$ jobs
$ disown %1
$ exit
or
$ (screenshooter &)
$ man ls | col -bx > ls.txt
$ 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
$ df -k
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
$ kill -STOP <PID>
$ kill -CONT <PID>
ssh stb@192.168.0.210 <<EOT
touch test_file
EOT
exit 0
$ find . -name "*.txt" -print | xargs zip -qr archive.zip
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.
add a breakpoint on objc_exception_throw
$ defaults write com.apple.Xcode GenerateGraphVizFiles -bool YES
Thank you 0xced.
ctrl + arrow keys
$ defaults write com.apple.Xcode NSRecentDocumentsLimit 25
#pragma mark -
#pragma mark NSTableDataSource protocol
$ /Developer/usr/bin/xcodeindex -project MyProject.xcodeproj rebuild
See also the dump
action.
$ defaults write com.apple.Xcode PBXBuildFailureSound ~/sound.mp3
$ defaults write com.apple.xcode PBXCustomTemplateMacroDefinitions '{ORGANIZATIONNAME="MY_COMPANY SA";}'
$ defaults write com.apple.dt.Xcode ShowBuildOperationDuration YES
$ defaults delete com.apple.Xcode PBXExternalEditorList
$ dwarfdump --uuid *.xcarchive/dSYMs/XXX.app.dSYM
$ dwarfdump --lookup=0x0008157b *.xcarchive/dSYMs/XXX.app.dSYM