text:
static BOOL setKeychainData(NSData *data, NSString *key)
{
    if (! key) return NO;

    NSDictionary *query = @{(__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,
                            (__bridge id)kSecAttrService:SEC_ATTR_SERVICE,
                            (__bridge id)kSecAttrAccount:key,
                            (__bridge id)kSecReturnData:(id)kCFBooleanTrue};

    SecItemDelete((__bridge CFDictionaryRef)query);

    if (! data) return YES;

    NSDictionary *item = @{(__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,
                           (__bridge id)kSecAttrService:SEC_ATTR_SERVICE,
                           (__bridge id)kSecAttrAccount:key,
                           (__bridge id)kSecAttrAccessible:(__bridge id)kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
                           (__bridge id)kSecValueData:data};
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)item, NULL);

    if (status != noErr) {
        NSLog(@"SecItemAdd error status %d", (int)status);
        return NO;
    }

    return YES;
}

static NSData *getKeychainData(NSString *key)
{
    NSDictionary *query = @{(__bridge id)kSecClass:(__bridge id)kSecClassGenericPassword,
                            (__bridge id)kSecAttrService:SEC_ATTR_SERVICE,
                            (__bridge id)kSecAttrAccount:key,
                            (__bridge id)kSecReturnData:(id)kCFBooleanTrue};
    CFDataRef result = nil;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&result);

    if (status != noErr) {
        NSLog(@"SecItemCopyMatching error status %d", (int)status);
        return nil;
    }

    return CFBridgingRelease(result);
}

@interface BRWalletManager()

@property (nonatomic, strong) BRWallet *wallet;
@property (nonatomic, strong) Reachability *reachability;
@property (nonatomic, assign) BOOL sweepFee;
@property (nonatomic, strong) NSString *sweepKey;
@property (nonatomic, strong) void (^sweepCompletion)(BRTransaction *tx, NSError *error);

@end

@implementation BRWalletManager

+ (instancetype)sharedInstance
{
    static id singleton = nil;
    static dispatch_once_t onceToken = 0;

    dispatch_once(&onceToken, ^{
        singleton = [self new];
    });

    return singleton;
}

- (instancetype)init
{
    if (! (self = [super init])) return nil;

    [NSManagedObject setConcurrencyType:NSPrivateQueueConcurrencyType];

    self.reachability = [Reachability reachabilityForInternetConnection];

    self.format = [NSNumberFormatter new];
    [self.format setLocale:[NSLocale currentLocale]];
    self.format.lenient = YES;
    self.format.numberStyle = NSNumberFormatterCurrencyStyle;
    self.format.minimumFractionDigits = 0;
    self.format.negativeFormat = [self.format.positiveFormat
                                  stringByReplacingCharactersInRange:[self.format.positiveFormat rangeOfString:@"#"]
                                  withString:@"-#"];
    self.format.currencySymbol = @"";//BITS NARROW_NBSP;
    self.format.maximumFractionDigits = 2;
    self.format.maximum = @21000000000000.0;
//    self.format.currencySymbol = BTC NARROW_NBSP;
//    self.format.maximumFractionDigits = 8;
//    self.format.maximum = @21000000.0;

    NSString *decimalSep = self.format.decimalSeparator;

    [self updateExchangeRate];

    return self;
}

- (void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

- (BRWallet *)wallet
{
    if (_wallet == nil && self.seed) {
        @synchronized(self) {
            if (_wallet == nil) {
                _wallet = [[BRWallet alloc] initWithContext:[NSManagedObject context]
                           andSeed:^NSData *{ return self.seed; }];
            }
        }
    }

    return _wallet;
}

- (NSData *)seed
{
    return getKeychainData(SEED_KEY);
}

- (void)setSeed:(NSData *)seed
{
    if ([seed isEqual:self.seed]) return;

    [[NSManagedObject context] performBlockAndWait:^{
        [BRAddressEntity deleteObjects:[BRAddressEntity allObjects]];
        [BRTransactionEntity deleteObjects:[BRTransactionEntity allObjects]];
        [NSManagedObject saveContext];
    }];

    setKeychainData(nil, MNEMONIC_KEY);
    setKeychainData(nil, CREATION_TIME_KEY);
    if (! setKeychainData(seed, SEED_KEY)) {
        NSLog(@"error setting wallet seed");
        [[[UIAlertView alloc] initWithTitle:@"couldn't create wallet"
          message:@"error adding master private key to iOS keychain, make sure app has keychain entitlements"
          delegate:self cancelButtonTitle:@"abort" otherButtonTitles:nil] show];
        return;
    }

    _wallet = nil;

    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:BRWalletManagerSeedChangedNotification object:nil];
    });
}

- (NSString *)seedPhrase
{
    NSData *phrase = getKeychainData(MNEMONIC_KEY);

    if (! phrase) return nil;

    return CFBridgingRelease(CFStringCreateFromExternalRepresentation(SecureAllocator(), (CFDataRef)phrase,
                                                                      kCFStringEncodingUTF8));
}

- (void)setSeedPhrase:(NSString *)seedPhrase
{
    @autoreleasepool {
        BRBIP39Mnemonic *m = [BRBIP39Mnemonic sharedInstance];

        seedPhrase = [m encodePhrase:[m decodePhrase:seedPhrase]];
        self.seed = [m deriveKeyFromPhrase:seedPhrase withPassphrase:nil];

        NSData *d = CFBridgingRelease(CFStringCreateExternalRepresentation(SecureAllocator(), (CFStringRef)seedPhrase,
                                                                           kCFStringEncodingUTF8, 0));

        setKeychainData(d, MNEMONIC_KEY);
    }
}

- (void)generateRandomSeed
{
    @autoreleasepool {
        NSMutableData *entropy = [NSMutableData secureDataWithLength:SEED_ENTROPY_LENGTH];
        NSTimeInterval time = [NSDate timeIntervalSinceReferenceDate];

        SecRandomCopyBytes(kSecRandomDefault, entropy.length, entropy.mutableBytes);

        self.seedPhrase = [[BRBIP39Mnemonic sharedInstance] encodePhrase:entropy];

        // we store the wallet creation time on the keychain because keychain data persists even when an app is deleted
        setKeychainData([NSData dataWithBytes:&time length:sizeof(time)], CREATION_TIME_KEY);
    }
}

-(NSString*)randomSeed
{
    NSMutableData *entropy = [NSMutableData secureDataWithLength:SEED_ENTROPY_LENGTH];
    NSTimeInterval time = [NSDate timeIntervalSinceReferenceDate];

    SecRandomCopyBytes(kSecRandomDefault, entropy.length, entropy.mutableBytes);

    return [[BRBIP39Mnemonic sharedInstance] encodePhrase:entropy];
}

- (NSTimeInterval)seedCreationTime
{
    NSData *d = getKeychainData(CREATION_TIME_KEY);

    return (d.length < sizeof(NSTimeInterval)) ? BITCOIN_REFERENCE_BLOCK_TIME : *(const NSTimeInterval *)d.bytes;
}

- (void)updateExchangeRate
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateExchangeRate) object:nil];
    [self performSelector:@selector(updateExchangeRate) withObject:nil afterDelay:60.0];

    if (self.reachability.currentReachabilityStatus == NotReachable) return;

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:TICKER_URL]
                         cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];

    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue currentQueue]
    completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"%@", connectionError);
            return;
        }

        NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        NSString *currencyCode = [defs objectForKey:LOCAL_CURRENCY_CODE_KEY];
        NSString *symbol = [defs objectForKey:LOCAL_CURRENCY_SYMBOL_KEY];
        if(!currencyCode || !symbol){
            currencyCode = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode];
            symbol = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];
        }
        if (error || ! [json isKindOfClass:[NSDictionary class]] ||
            ! [json[DEFAULT_CURRENCY_CODE] isKindOfClass:[NSDictionary class]] ||
            ! [json[DEFAULT_CURRENCY_CODE][@"last"] isKindOfClass:[NSNumber class]] ||
            ([json[currencyCode] isKindOfClass:[NSDictionary class]] &&
             ! [json[currencyCode][@"last"] isKindOfClass:[NSNumber class]])) {
            NSLog(@"unexpected response from %@:\n%@", req.URL.host,
                  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            return;
        }

        if (! [json[currencyCode] isKindOfClass:[NSDictionary class]]) { // if local currency is missing, use default
            currencyCode = DEFAULT_CURRENCY_CODE;
            symbol = DEFAULT_CURRENCY_SYMBOL;
        }

        [defs setObject:symbol forKey:LOCAL_CURRENCY_SYMBOL_KEY];
        [defs setObject:currencyCode forKey:LOCAL_CURRENCY_CODE_KEY];
        [defs setObject:json[currencyCode][@"last"] forKey:LOCAL_CURRENCY_PRICE_KEY];
        [defs setObject:[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding] forKey:EXCHANGE_DUMP];

        [defs synchronize];
        NSLog(@"exchange rate updated to %@/%@", [self localCurrencyStringForAmount:SATOSHIS],
              [self stringForAmount:SATOSHIS]);

        if (! self.wallet) return;

        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:BRWalletBalanceChangedNotification object:nil];
        });
    }];
}

-(NSDictionary*)currencyExchangeRates
{
    NSString *jsonDump = [[NSUserDefaults standardUserDefaults]objectForKey:EXCHANGE_DUMP];
    if(jsonDump){
        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonDump dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
        if(!error){
            return json;
        }
    }

    return nil;
}

-(NSDictionary*)localCurrencyData
{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSString *currencyCode = [defs objectForKey:LOCAL_CURRENCY_CODE_KEY];
    NSString *symbol = [defs objectForKey:LOCAL_CURRENCY_SYMBOL_KEY];
    if(!currencyCode || !symbol){
        currencyCode = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode];
        symbol = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];
    }

    return [NSDictionary dictionaryWithObjectsAndKeys:currencyCode,@"code",symbol,@"symbol",[defs objectForKey:LOCAL_CURRENCY_PRICE_KEY],@"price", nil];
}

-(NSString*)currencyCode
{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSString *currencyCode = [defs objectForKey:LOCAL_CURRENCY_CODE_KEY];
    if(!currencyCode){
        currencyCode = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode];
    }
    return currencyCode;
}

-(void)setLocalCurrency:(NSString*)currencyCode withData:(NSDictionary*)exchangeData
{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    [defs setObject:exchangeData[@"symbol"] forKey:LOCAL_CURRENCY_SYMBOL_KEY];
    [defs setObject:currencyCode forKey:LOCAL_CURRENCY_CODE_KEY];
    [defs setObject:exchangeData[@"last"] forKey:LOCAL_CURRENCY_PRICE_KEY];
    [defs synchronize];
}

// given a private key, queries blockchain for unspent outputs and calls the completion block with a signed transaction
// that will sweep the balance into the wallet (doesn't publish the tx)
- (void)sweepPrivateKey:(NSString *)privKey withFee:(BOOL)fee
completion:(void (^)(BRTransaction *tx, NSError *error))completion
{
    if (! completion) return;

    if ([privKey isValidBitcoinBIP38Key]) {
        UIAlertView *v = [[UIAlertView alloc] initWithTitle:@"password protected key" message:nil delegate:self
                          cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];

        v.alertViewStyle = UIAlertViewStyleSecureTextInput;
        [v textFieldAtIndex:0].returnKeyType = UIReturnKeyDone;
        [v textFieldAtIndex:0].placeholder = @"password";
        [v show];

        self.sweepKey = privKey;
        self.sweepFee = fee;
        self.sweepCompletion = completion;
        return;
    }

    NSString *address = [[BRKey keyWithPrivateKey:privKey] address];

    if (! address) {
        completion(nil, [NSError errorWithDomain:@"BreadWallet" code:187 userInfo:@{NSLocalizedDescriptionKey:
                         NSLocalizedString(@"not a valid private key", nil)}]);
        return;
    }

    if ([self.wallet containsAddress:address]) {
        completion(nil, [NSError errorWithDomain:@"BreadWallet" code:187 userInfo:@{NSLocalizedDescriptionKey:
                         NSLocalizedString(@"this private key is already in your wallet", nil)}]);
        return;
    }

    NSURL *u = [NSURL URLWithString:[UNSPENT_URL stringByAppendingString:address]];
    NSURLRequest *req = [NSURLRequest requestWithURL:u cachePolicy:NSURLRequestReloadIgnoringCacheData
                         timeoutInterval:20.0];

    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue currentQueue]
    completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            completion(nil, connectionError);
            return;
        }

        NSError *error = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        uint64_t balance = 0, standardFee = 0;
        BRTransaction *tx = [BRTransaction new];

        if (error) {
            if ([[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] hasPrefix:@"No free outputs"]) {
                error = [NSError errorWithDomain:@"BreadWallet" code:417 userInfo:@{NSLocalizedDescriptionKey:
                         NSLocalizedString(@"this private key is empty", nil)}];
            }

            completion(nil, error);
            return;
        }

        if (! [json isKindOfClass:[NSDictionary class]] ||
            ! [json[@"unspent_outputs"] isKindOfClass:[NSArray class]]) {
            completion(nil, [NSError errorWithDomain:@"BreadWallet" code:417 userInfo:@{NSLocalizedDescriptionKey:
                             [NSString stringWithFormat:NSLocalizedString(@"unexpected response from %@", nil), u.host]
                            }]);
            return;
        }

        //TODO: make sure not to create a transaction larger than TX_MAX_SIZE
        for (NSDictionary *utxo in json[@"unspent_outputs"]) {
            if (! [utxo isKindOfClass:[NSDictionary class]] ||
                ! [utxo[@"tx_hash"] isKindOfClass:[NSString class]] || ! [utxo[@"tx_hash"] hexToData] ||
                ! [utxo[@"tx_output_n"] isKindOfClass:[NSNumber class]] ||
                ! [utxo[@"script"] isKindOfClass:[NSString class]] || ! [utxo[@"script"] hexToData] ||
                ! [utxo[@"value"] isKindOfClass:[NSNumber class]]) {
                completion(nil, [NSError errorWithDomain:@"BreadWallet" code:417 userInfo:@{NSLocalizedDescriptionKey:
                                 [NSString stringWithFormat:NSLocalizedString(@"unexpected response from %@", nil),
                                  u.host]}]);
                return;
            }

            [tx addInputHash:[utxo[@"tx_hash"] hexToData] index:[utxo[@"tx_output_n"] unsignedIntegerValue]
             script:[utxo[@"script"] hexToData]];
            balance += [utxo[@"value"] unsignedLongLongValue];
        }

        if (balance == 0) {
            completion(nil, [NSError errorWithDomain:@"BreadWallet" code:417 userInfo:@{NSLocalizedDescriptionKey:
                             NSLocalizedString(@"this private key is empty", nil)}]);
            return;
        }

        // we will be adding a wallet output (additional 34 bytes)
        //TODO: calculate the median of the lowest fee-per-kb that made it into the previous 144 blocks (24hrs)
        if (fee) standardFee = ((tx.size + 34 + 999)/1000)*TX_FEE_PER_KB;

        if (standardFee + TX_MIN_OUTPUT_AMOUNT > balance) {
            completion(nil, [NSError errorWithDomain:@"BreadWallet" code:417 userInfo:@{NSLocalizedDescriptionKey:
                             NSLocalizedString(@"transaction fees would cost more than the funds available on this "
                                               "private key (due to tiny \"dust\" deposits)",nil)}]);
            return;
        }

        [tx addOutputAddress:[self.wallet changeAddress] amount:balance - standardFee];

        if (! [tx signWithPrivateKeys:@[privKey]]) {
            completion(nil, [NSError errorWithDomain:@"BreadWallet" code:401 userInfo:@{NSLocalizedDescriptionKey:
                             NSLocalizedString(@"error signing transaction", nil)}]);
            return;
        }

        completion(tx, nil);
    }];
}

#pragma mark - string helpers

// TODO: make this work with local currency amounts
- (int64_t)amountForString:(NSString *)string
{
    return [self amountForString:string withMaximumFractionDigits:self.format.maximumFractionDigits];
}

- (int64_t)amountForString:(NSString *)string withMaximumFractionDigits:(int)maximumDigits
{
    return [self amountForDouble:[[self.format numberFromString:string] doubleValue] withMaximumFractionDigits:maximumDigits];
}
-(int64_t)amountForDouble:(double)amount
{
    return [self amountForDouble:amount withMaximumFractionDigits:self.format.maximumFractionDigits];
}
-(int64_t)amountForDouble:(double)amount withMaximumFractionDigits:(int)maximumDigits
{
    return (amount + DBL_EPSILON)*pow(10.0, maximumDigits);
}

- (NSString *)stringForAmount:(int64_t)amount
{
    NSUInteger min = self.format.minimumFractionDigits;

    if (amount == 0) {
        self.format.minimumFractionDigits =
            self.format.maximumFractionDigits > 4 ? 4 : self.format.maximumFractionDigits;
    }

    NSString *r = [self.format stringFromNumber:@(amount/pow(10.0, self.format.maximumFractionDigits))];

    self.format.minimumFractionDigits = min;

    return r;
}

- (NSString *)localCurrencyStringForAmount:(int64_t)amount
{
    static NSNumberFormatter *format = nil;

    if (! format) {
        format = [NSNumberFormatter new];
        format.lenient = YES;
        format.numberStyle = NSNumberFormatterCurrencyStyle;
        format.negativeFormat = [format.positiveFormat
                                 stringByReplacingCharactersInRange:[format.positiveFormat rangeOfString:@"#"]
                                 withString:@"-#"];
    }

    if (amount == 0) return [format stringFromNumber:@(0)];

    NSString *symbol = [[NSUserDefaults standardUserDefaults] stringForKey:LOCAL_CURRENCY_SYMBOL_KEY];
    NSString *code = [[NSUserDefaults standardUserDefaults] stringForKey:LOCAL_CURRENCY_CODE_KEY];
    double price = [[NSUserDefaults standardUserDefaults] doubleForKey:LOCAL_CURRENCY_PRICE_KEY];

    if (! symbol.length || price <= DBL_EPSILON) return [format stringFromNumber:@(amount/DEFAULT_CURRENCY_PRICE)];

    format.currencySymbol = symbol;
    format.currencyCode = code;

    NSString *ret = [format stringFromNumber:@(price*amount/SATOSHIS)];

    // if the amount is too small to be represented in local currency (but is != 0) then return a string like "<$0.01"
    if (amount > 0 && price*amount/SATOSHIS + DBL_EPSILON < 1.0/pow(10.0, format.maximumFractionDigits)) {
        ret = [@"<" stringByAppendingString:[format stringFromNumber:@(1.0/pow(10.0, format.maximumFractionDigits))]];
    }
    else if (amount < 0 && price*amount/SATOSHIS - DBL_EPSILON > -1.0/pow(10.0, format.maximumFractionDigits)) {
        // technically should be '>', but '<' is more intuitive
        ret = [@"<" stringByAppendingString:[format stringFromNumber:@(-1.0/pow(10.0, format.maximumFractionDigits))]];
    }

    return ret;
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == alertView.cancelButtonIndex) {
        if ([[alertView buttonTitleAtIndex:buttonIndex] isEqual:@"abort"]) abort();

        if (self.sweepCompletion) self.sweepCompletion(nil, nil);
        self.sweepKey = nil;
        self.sweepCompletion = nil;
        return;
    }

    if (! self.sweepKey || ! self.sweepCompletion) return;

    NSString *passphrase = [[alertView textFieldAtIndex:0] text];

    dispatch_async(dispatch_get_main_queue(), ^{
        BRKey *key = [BRKey keyWithBIP38Key:self.sweepKey andPassphrase:passphrase];

        if (! key) {
            UIAlertView *v = [[UIAlertView alloc] initWithTitle:@"password protected key"
                              message:@"bad password, try again" delegate:self cancelButtonTitle:@"cancel"
                              otherButtonTitles:@"ok", nil];

            v.alertViewStyle = UIAlertViewStyleSecureTextInput;
            [v textFieldAtIndex:0].returnKeyType = UIReturnKeyDone;
            [v textFieldAtIndex:0].placeholder = @"password";
            [v show];
        }
        else {
            [self sweepPrivateKey:key.privateKey withFee:self.sweepFee completion:self.sweepCompletion];
            self.sweepKey = nil;
            self.sweepCompletion = nil;
        }
    });
}

@end


text:
if $stdout.isatty && verbose
  def growl_notify(type, title, message)
    begin
      # Loading Ruby Cocoa can slow the build down (hooks on Object class), so we're
      # saving the best for last and only requiring it at the very end.
      require 'osx/cocoa'
      icon = OSX::NSApplication.sharedApplication.applicationIconImage
      icon = OSX::NSImage.alloc.initWithContentsOfFile(File.join(File.dirname(__FILE__), '../resources/buildr.icns'))

      # Register with Growl, that way you can turn notifications on/off from system preferences.
      OSX::NSDistributedNotificationCenter.defaultCenter.
        postNotificationName_object_userInfo_deliverImmediately(:GrowlApplicationRegistrationNotification, nil,
          { :ApplicationName=>'Buildr', :AllNotifications=>['Completed', 'Failed'],
            :ApplicationIcon=>icon.TIFFRepresentation }, true)

      OSX::NSDistributedNotificationCenter.defaultCenter.
        postNotificationName_object_userInfo_deliverImmediately(:GrowlNotification, nil,
          { :ApplicationName=>'Buildr', :NotificationName=>type,
            :NotificationTitle=>title, :NotificationDescription=>message }, true)
    rescue Exception
      # We get here in two cases: system doesn't have Growl installed so one of the OSX
      # calls raises an exception; system doesn't have osx/cocoa, e.g. MacPorts Ruby 1.9,
      # so we also need to rescue LoadError.
    end
  end

  Buildr.application.on_completion { |title, message| growl_notify('Completed', title, message) if verbose }
  Buildr.application.on_failure { |title, message, ex| growl_notify('Failed', title, message) if verbose }
end

redpajama_set_name: RedPajamaGithub


text:
On a fresh OS X installation there are three empty directories for
add-ons available to all users:

    /Library/Ruby
    /Library/Python
    /Library/Perl

Starting with OS X Lion (10.7), you need `sudo` to install to these like
so: `sudo gem install`, `sudo easy_install` or `sudo cpan -i`.

An option to avoid `sudo` is to use an access control list:
`chmod +a 'user:YOUR_NAME_HERE allow add_subdirectory,add_file,delete_child,directory_inherit' /Library/Python/2.7/site-packages`,
for example, will let you add packages to Python 2.7 as yourself. That
is probably safer than changing the group ownership of the directory.

### So why was I using sudo?
Habit maybe?

One reason is executables go in `/usr/local/bin`. Usually this isn't a
writable location. But if you installed Homebrew as we recommend,
`/usr/local` will be writable without sudo. So now you are good to
install the development tools you need without risking a sudo.

### Python packages (eggs) without sudo
Rather than changing the rights on /Library/Python, we recommend the
following options:

### With a brewed Python - you don't need sudo
Note, `easy_install` is deprecated. We install `pip` (or `pip3` for
python3) along with python/python3.

We set up distutils such that `pip install` will always put modules in
`$(brew --prefix)/lib/pythonX.Y/site-packages` and scripts in
`$(brew --prefix)/share/python`. Therefore, you won't need `sudo`!

Do `brew info python` or `brew info python3` for precise information
about the paths. Note, a brewed Python still searches for modules in
`/Library/Python/X.Y/site-packages` and also in
`~/Library/Python/X.Y/lib/python/site-packages`.

### With system's Python
_This is only recommended if you **don't** use a brewed Python._

On OS X, any [Python version X.Y also searches in
`~/Library/Python/X.Y/lib/python/site-packages` for
modules](https://docs.python.org/2/install/index.html#inst-alt-install-user).
That dir might not yet exist, but you can create it:
`mkdir -p ~/Library/Python/2.7/lib/python/site-packages`

To teach `easy_install` and `pip` to install there, either use the
`—user` switch or create a `~/.pydistutils.cfg` file with the
following content:

    [install]
    install_lib = ~/Library/Python/$py_version_short/lib/python/site-packages

### Using virtualenv - works with brewed and system's Python

[Virtualenv](http://www.virtualenv.org/en/latest/) ships `pip` and
creates isolated Python environments with separate site-packages,
therefore you won't need `sudo`.

Rubygems without sudo
---------------------

**If you use rbenv or RVM then you should ignore this stuff**

Brewed Ruby installs executables to `$(brew --prefix)/opt/ruby/bin`
without sudo. You should add this to your path. See the caveats in the
`ruby` formula for up-to-date information.

### With system's Ruby

To make Ruby install to `/usr/local`, we need to add
`gem: -n/usr/local/bin` to your `~/.gemrc`. It's YAML…so do it manually
or use this:

    echo "gem: -n/usr/local/bin" >> ~/.gemrc

**However all versions of RubyGems before 1.3.6 are buggy** and ignore
the above setting. Sadly a fresh install of Snow Leopard comes with
1.3.5. Currently the only known way to get round this is to upgrade
rubygems as root:

`sudo gem update --system`

### An Alternative

Just install everything into the Homebrew prefix like this:

`echo "export GEM_HOME=\"$(brew --prefix)\"" >> ~/.bashrc`

### It doesn't work! I get some "permissions" error when I try to install stuff!

*Note, maybe you shouldn't do this on Lion, since Apple have decided it
is not a good default.*

If you ever did a `sudo gem`, etc. before then a lot of files will have
been created chown root. Fix with:

`sudo chown -R $USER /Library/Ruby /Library/Perl /Library/Python`

Perl CPAN Modules without sudo
------------------------------

The Perl module local::lib works similarly to rbenv/RVM (although for
modules only, not perl installations). A simple solution that only
pollutes your /Library/Perl a little is to install
[local::lib](https://metacpan.org/pod/local::lib) with sudo:

`sudo cpan local::lib`

Note that will install some other dependencies like `Module::Install`.
Then put the appropriate incantation in your shell's startup, e.g. for
`.bash_profile` you insert the below, for others see the
[local::lib](https://metacpan.org/pod/local::lib) docs.

`eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)`

Now (after you restart your shell) `cpan` or `perl -MCPAN -eshell` etc.
will install modules and binaries in `~/perl5` and the relevant
subdirectories will be in your `PATH` and `PERL5LIB` etc.

### Avoiding sudo altogether for Perl

If you don't even want (or can't) use sudo for bootstrapping
`local::lib` just manually install `local::lib` in
~/perl5 and add the relevant path to `PERL5LIB` before the .bashrc eval incantation.

Another alternative is to use `perlbrew` to install a separate copy of Perl in your home directory, or wherever you like :
```bash
curl -kL http://install.perlbrew.pl | bash
perlbrew install perl-5.16.2
echo ".~/perl5/perlbrew/etc/bashrc" >> ~/.bashrc
```


text:
/*
 * program to communicate with a 5ess switch via a rc/v or
 * a unix port.
 */

/* system headers */
#include <stdio.h>
#include <string.h>
#include <termio.h>
#include <signal.h>
#include <fcntl.h>
#include <malloc.h>

/* externs */
extern int errno, sys_nerr;
extern char *sys_errlist[];
extern char *optarg;
extern int optind, opterr;

/* global variables */
struct termio ostdinbuf;	/* original state of stdin */
struct termio ottyfdbuf;	/* original state of port */
int Reset;		/* reset port state flag */
int gttyfd;		/* port file descriptor */
int timeout;		/* timeout flag for trap */
int ackflag;		/* ack flag for trap */
int write2out;		/* write to stdout flag, used for throttling */

/* local definitions */
#define USAGE "usage: rcvio [-?] [-D] [-s speed] [-m characters] [-t timeout] device"
#define RCVTRUE 1
#define RCVFALSE 0
#define RCVOK 0
#define RCVNOTOK -1
#define RCVNOTTTY -2
#define RCVTMOUT -3
#define RCVNOACK -4
#define RCVWRITE 0
#define RCVNOWRITE 1
#define RCVFLUSH 2
#define TIMEOUT 10
#define RCVCNTRLY 031
#define RCVESCAPE 033
#define RCVDELETE 0177
#define RCVNL '\n'
#define NULLCHR '\0'
#define NULLPTR 0
#define FIVESEC ((unsigned) 5)

/* error handling */
void syserr(errmsg, prtusage)
char *errmsg;
int prtusage;
{
	if (*errmsg != '\0') fprintf(stderr, "%s\n", errmsg);
	if (errno > 0 && errno < sys_nerr)
	{
		fprintf(stderr, "error %d : %s\n", errno, sys_errlist[errno]);
	}
	if (prtusage) fprintf(stderr, "%s\n", USAGE);
	return;
}

/* trap function for acknowledgements */
#ifdef VAX
void ack_trap()
#else
int ack_trap()
#endif
{
	/* ack has been received */
	ackflag = RCVTRUE;
	return;
}

/* trap function for timeouts */
#ifdef VAX
void tmout_trap()
#else
int tmout_trap()
#endif
{
	/* time out has occurred, set flag */
	timeout = RCVTRUE;
	return;
}

/* trap function for user signals */
#ifdef VAX
void user_trap()
#else
int user_trap()
#endif
{
	int kill(), getppid();

	/* reset trap */
	(void) signal(SIGUSR1, user_trap);

	/* toggle flag for writing to stdout */
	switch (write2out)
	{
	case RCVWRITE:
		write2out = RCVNOWRITE;
		break;
	case RCVNOWRITE:
		write2out = RCVFLUSH;
		break;
	default:
		exit(2);
	}

	/* send back acknowledgement */
	(void) kill(getppid(), SIGUSR1);

	/* return */
	return;
}

/* trap function for death of child */
#ifdef VAX
void child_trap()
#else
int child_trap()
#endif
{
	/* print error msg */
	fprintf(stderr, "child process has died.\n");

	/* reset terminals */
	(void) ioctl(0, TCSETAW, &ostdinbuf);
	if (Reset) (void) ioctl(gttyfd, TCSETAW, &ottyfdbuf);

	/* close tty */
	(void) close(gttyfd);

	/* exit */
	exit(2);
}

/* verify if a character string is numeric */
int isnumeric(pstr)
char *pstr;
{
	for ( ; ('0' <= *pstr) && (*pstr <= '9'); pstr++)
	{
		/* do nothing */
	}
	if (*pstr != '\0') return(RCVFALSE);
	return(RCVTRUE);
}

/* function to open a terminal */
int ttyopen(devicename, flags)
char *devicename;
int flags;
{
	int ttyfd;
	unsigned alarm();
#ifdef VAX
	void (*oldsigfn)(), tmout_trap();
#else
	int (*oldsigfn)(), tmout_trap();
#endif

	/* set timeout flag to false */
	timeout = RCVFALSE;

	/* set alarm trap */
	oldsigfn = signal(SIGALRM, tmout_trap);

	/* start alarm */
	(void) alarm((unsigned) TIMEOUT);

	/* open terminal */
	ttyfd = open(devicename, flags);

	/* device was opened or it failed with timeout, etc. */
	(void) alarm(0);
	(void) signal(SIGALRM, oldsigfn);

	/* did time out occur ? */
	if (timeout == RCVTRUE) return(RCVTMOUT);

	/* other failures ? */
	if (ttyfd < 0) return(RCVNOTOK);

	/* is devicename a tty ? */
	if ( ! isatty(ttyfd))
	{
		/* not a tty */
		(void) close(ttyfd);
		return(RCVNOTTTY);
	}

	/* everything is ok, return fd */
	return(ttyfd);
}

/* send a signal to a process and wait for an acknowledgement */
int throttle(pid, waittime, sig)
int pid, waittime, sig;
{
	int status;
	unsigned sleep();
#ifdef VAX
	void (*oldsigfn)();
#else
	int (*oldsigfn)();
#endif

	/* assume success, be optimistic */
	status = RCVOK;

	/* set flag for ack as not true */
	ackflag = RCVFALSE;

	/* save trap for given signal */
	oldsigfn = signal(sig, ack_trap);

	/* send signal and sleep */
	if (kill(pid, sig) < 0) return(RCVNOTOK);
	(void) sleep((unsigned) waittime);

	/* check if response was received */
	if (ackflag == RCVFALSE) status = RCVNOACK;

	/* reset previous trap */
	(void) signal(sig, oldsigfn);

	/* return status */
	return(status);
}

/* exec a command to a shell */
int callshell(ttyfd, outpid)
int ttyfd, outpid;
{
	struct termio stdinbuf;
	char cmdbuf[BUFSIZ + 1];
	register char *pstr;
	int throttle();
#ifdef VAX
	void (*oldsigfn)();
#else
	int (*oldsigfn)();
#endif
#ifdef DEBUG
	FILE *dbgfd;
#endif

#ifdef DEBUG
	dbgfd = fopen("/tmp/prcvio.dbg", "a");
#endif
	/* remove death-of-child trap */
	oldsigfn = signal(SIGCLD, SIG_DFL);

	/* send signal to throttle output to stdout */
	if (throttle(outpid, FIVESEC, SIGUSR1) < 0) return(RCVNOTOK);

	/* halt all output to stdout */
	(void) ioctl(1, TCXONC, 0);

	/* discard (flush) anything in input queue */
	(void) ioctl(0, TCFLSH, 0);

	/* discard (flush) anything in output queue */
	(void) ioctl(1, TCFLSH, 1);

	/* restart output to stdout */
	(void) ioctl(1, TCXONC, 1);

	/* save stdin raw mode state */
	if (ioctl(0, TCGETA, &stdinbuf) < 0) return(RCVNOTOK);

	/* reset stdin to original state */
	if (ioctl(0, TCSETA, &ostdinbuf) < 0) return(RCVNOTOK);

	/* read in a line from stdin and exec */
	(void) fprintf(stdout,"\n!");
	(void) fflush(stdout);
	cmdbuf[0] = NULLCHR;
	(void) fgets(cmdbuf, BUFSIZ, stdin);
	cmdbuf[BUFSIZ] = NULLCHR;

	/* exec the input msg */
#ifdef DEBUG
	fprintf(dbgfd, "callshell: system cmd is %s.\n", cmdbuf);
	fflush(dbgfd);
#endif
	(void) system(cmdbuf);
	(void) fprintf(stdout,"\n");
	(void) fflush(stdout);
#ifdef DEBUG
	fprintf(dbgfd, "callshell: after system call.\n");
	fflush(dbgfd);
#endif

	/* discard (flush) anything in input queue */
	(void) ioctl(0, TCFLSH, 0);

	/* reset death-of-child trap */
	(void) signal(SIGCLD, oldsigfn);

	/* reset stdin to raw mode */
	if (ioctl(0, TCSETAW, &stdinbuf) < 0) return(RCVNOTOK);

	/* send signal to restart output to stdout */
	if (throttle(outpid, FIVESEC, SIGUSR1) < 0) return(RCVNOTOK);
#ifdef DEBUG
	(void) fclose(dbgfd);
#endif

	/* return */
	return(RCVOK);
}

/* function to read stdin and write to external port */
int in2tty(ttyfd, outpid)
int ttyfd, outpid;
{
	unsigned char c;

	for ( ; ; )
	{
		if (read(0, &c, 1) < 0) return(RCVNOTOK);
		if (c == RCVESCAPE)
		{
			/* escape mode, input for rcvio */
			if (read(0, &c, 1) < 0) return(RCVNOTOK);

			/* determine the type of input */
			switch (c)
			{
			case RCVCNTRLY:
			case RCVDELETE:
				/* exit with these keys when in escape mode */
				goto done;

			case RCVESCAPE:
				/* send the 2nd escape to ttyfd */
				break;

			case '!':
				/* escape to shell and execute a command.  */
				if (callshell(ttyfd, outpid) != RCVOK) return(RCVNOTOK);
				continue;

			default:
				 /* ignore all other input */
				continue;
			}
		}
		if (write(ttyfd, &c, 1) < 0) return(RCVNOTOK);
	}
done:
	return(RCVOK);
}

/* function to read external port and write to stdout */
void tty2out(ttyfd, ttymin)
int ttyfd, ttymin;
{
	register unsigned char *pbuf;
	register bytesread;
	char *malloc();
#ifdef VAX
	void user_trap();
#else
	int user_trap();
#endif

	/* malloc the buffer */
	if (ttymin > 0)
	{
		pbuf = (unsigned char *) malloc((unsigned) ttymin);
		if (pbuf == (unsigned char *) NULL) exit(2);
	}
	else
	{
		exit(2);
	}

	/* set flag for writing to stdout */
	write2out = RCVWRITE;

	/*
	 * set trap for catching user signals, used
	 * for throttling output to stdout. the flag
	 * write2out is toggled.
	 */
	(void) signal(SIGUSR1, user_trap);

	/* read from tty and write to stdout */
	for ( ; ; )
	{
		bytesread = read(ttyfd, pbuf, ttymin);
		switch (write2out)
		{
		case RCVWRITE:
			write(1, pbuf, bytesread);
			break;
		case RCVNOWRITE:
			break;
		case RCVFLUSH:
			write2out = RCVWRITE;
			(void) ioctl(ttyfd, TCFLSH, 1);
			break;
		default:
			exit(2);
		}
	}

	/* NEVER RETURNS */
	exit(2);
}

/* function to communicate with external port */
int rcvio(ttyfd, devname, ttyspeed, ttymin, ttytime)
int ttyfd;
char *devname;
int ttyspeed, ttymin, ttytime;
{
#ifdef VAX
	void (*osigintr)();
	void (*osigquit)();
	void (*osigcld)();
	void child_trap();
#else
	int (*osigintr)();
	int (*osigquit)();
	int (*osigcld)();
	int child_trap();
#endif
	int status, in2tty(), pid;
	void tty2out();

	/* ignore standard interrupt signals */
	osigintr = signal(SIGINT, SIG_IGN);
	osigquit = signal(SIGQUIT, SIG_IGN);

	/*
	 * save current terminal and device states
	 * in global variables so that trap functions can use
	 * them to reset the terminals.
	 */
	if (ioctl(0, TCGETA, &ostdinbuf) < 0) return(RCVNOTOK);
	if (ioctl(ttyfd, TCGETA, &ottyfdbuf) < 0) return(RCVNOTOK);

	/* starting connection */
	fprintf(stdout, "connecting to %s ...\n", devname);

	/* set stdin and ttydev to raw mode, keep xon/xoff active */
	if ((set_raw(0, 0, 1, 0) < 0) ||
		(set_raw(ttyfd, ttyspeed, ttymin, ttytime) < 0))
	{
		/* reset old states */
		 (void) ioctl(0, TCSETAW, &ostdinbuf);
		 if (Reset) (void) ioctl(ttyfd, TCSETAW, &ottyfdbuf);
		/* restore signal handling */
		(void) signal(SIGINT, osigintr);
		(void) signal(SIGQUIT, osigquit);
		/* return */
		return(RCVNOTOK);
	}

	/*
	 * fork to create two processes. the parent process
	 * reads stdin and writes to ttyfd. the child
	 * process reads ttyfd and writes to stdout.
	 */
	if ((pid = fork()) < 0) return(RCVNOTOK);

	/* depending on which process, call a different function */
	if (pid > 0)
	{
		/* set function to catch death-of-child signal */
		osigcld = signal(SIGCLD, child_trap);
		/* parent process, read stdin, write ttyfd */
		status = in2tty(ttyfd, pid);
		/* reset old death-of-child handling */
		(void) signal(SIGCLD, osigcld);
	}
	else
	{
		/* child process, read ttyfd, write stdout */
		(void) tty2out(ttyfd, ttymin); /* NEVER RETURNS */
	}

	/* kill child process */
	kill(pid, SIGTERM);
	wait((int *) 0);

	/* reset old states */
	(void) ioctl(0, TCSETAW, &ostdinbuf);
	if (Reset) (void) ioctl(ttyfd, TCSETAW, &ottyfdbuf);

	/* restore signal handling */
	(void) signal(SIGINT, osigintr);
	(void) signal(SIGQUIT, osigquit);

	/* return status */
	return(status);
}

/* function to set a device to raw mode */
int set_raw(fd, speed, min, time)
int fd, speed, min, time;
{
	struct termio tbuff;

	/* check that fd points to a terminal */
	if (! isatty(fd)) return(RCVNOTTTY);

	/* get current state of terminal */
	if (ioctl(fd, TCGETA, &tbuff) < 0) return(RCVNOTOK);

	/* change characteristics to raw mode with xon/xoff */
	tbuff.c_iflag = (IXON|IXOFF);
	tbuff.c_oflag = 0;
	tbuff.c_lflag = 0;

	/* set baud rate */
	if (speed > 0)
	{
		tbuff.c_cflag &= ~CBAUD;
		tbuff.c_cflag |= speed;
	}

	/* set minimum number of characters and timeout value */
	tbuff.c_cc[VMIN] = min;
	tbuff.c_cc[VTIME] = time;

	/* reset terminal */
	return(ioctl(fd, TCSETAW, &tbuff));
}

/* convert speed to enum for baud rate */
int getspeed(pbaud)
char *pbaud;
{
	int speed;

	switch(atoi(pbaud))
	{
	case 300:
		speed = B300;
		break;
	case 1200:
		speed = B1200;
		break;
	case 2400:
		speed = B2400;
		break;
	case 4800:
		speed = B4800;
		break;
	case 9600:
		speed = B9600;
		break;
	default:
		speed = RCVNOTOK;
		break;
	}
	return(speed);
}

/* main program */
main(argc, argv)
int argc;
char *argv[];
{
	int c, status, ttyfd, getopt(), getspeed();
	int ttyspeed, ttymin, ttytime;
	char devname[BUFSIZ];

	/* default values for reading tty */
	ttyspeed = 0;		/* no change in baud rate */
	ttymin = 1;				/* 1 character at a time */
	ttytime = 0;		/* return immediate, no wait for input */
	Reset = RCVTRUE;

	/* check that a port was given */
	if (argc <= 1)
	{
		syserr("no device name was given.", RCVTRUE);
		exit(2);
	}

	/* get options, like baud rate */
	while ((c = getopt(argc, argv, "?Ds:m:t:")) != EOF)
	{
		/* switch on option */
		switch (c)
		{
		case 'D':
			/* do not reset tty upon exit, leave the given state */
			Reset = RCVFALSE;
			break;

		 case 'm':
			if ( ! isnumeric(optarg))
			{
				syserr("minimum characters to read must be numeric.", RCVTRUE);
				exit(2);
			}
			ttymin = atoi(optarg);
			break;

		 case 't':
			if ( ! isnumeric(optarg))
			{
				syserr("maxtime for read timeouts must be numeric.", RCVTRUE);
				exit(2);
			}
			ttytime = atoi(optarg);
			break;

		case 's':
			/* get baud rate */
			if ((ttyspeed = getspeed(optarg)) <= 0)
			{
				syserr("speed <= 0, or non-numeric.", RCVTRUE);
				exit(2);
			}
			break;

		case '?':
			/* print help msg */
			syserr("", RCVTRUE);
			exit(0);

		default:
			/* bad option in command line */
			syserr("command line option failure.", RCVTRUE);
			exit(2);
		}
	}

	/* device name must be in /dev partition */
	if (strncmp("/dev/", argv[optind], 5) != 0)
	{
		if (isnumeric(argv[optind]) == RCVTRUE)
		{
			/* append /dev/tty to devname */
			strcpy(devname, "/dev/tty");
		}
		else
		{
			/* append /dev to devname */
			strcpy(devname, "/dev/");
		}
	}
	strcat(devname, argv[optind]);

	/* open external port connected to 5ess for read and write */
	ttyfd = ttyopen(devname, O_RDWR);
	if (ttyfd < 0)
	{
		/* check for errors */
		switch (ttyfd)
		{
		case RCVNOTTTY:
			fprintf(stderr, "device %s is not a tty.\n", devname);
			break;

		case RCVTMOUT:
			fprintf(stderr, "timeout opening device %s.\n", devname);
			break;

		}
		syserr("ttyopen failed for device.", RCVFALSE);

		/* close tty and exit */
		(void) close(ttyfd);
		exit(2);
	}

	/* save ttyfd in global ttyfd for trap on death-of-child signal */
	gttyfd = ttyfd;

	/* verify that stdin/stdout are terminals */
	if (!isatty(0) || !isatty(1))
	{
		syserr("stdin or stdout is not a terminal.", RCVFALSE);
		(void) close(ttyfd);
		exit(2);
	}

	/* clear screen */
	(void) system("tput clear");

	/* call function to communicate with 5ess via the io port */
	if ((status = rcvio(ttyfd, devname, ttyspeed, ttymin, ttytime)) != RCVOK)
	{
		fprintf(stderr, "i/o failure via port %s\n", devname);
		syserr("rcvio() failed.", RCVFALSE);
		(void) close(ttyfd);
		exit(2);
	}

	/* clear screen */
	(void) system("tput clear");

	/* finished, close external port */
	fprintf(stdout, "\nrcvio() completed.\n");
	(void) close(ttyfd);
	exit(0);
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class FadeView : MonoBehaviour, IAnimatedView
{
	public Animator[] animators = new Animator[0];
	public GameObject[] manageActive = new GameObject[0];

	public CanvasGroup[] groups;

	public float inTime;
	public float outTime;

	public AnimationCurve inCurve;
	public AnimationCurve outCurve;

	#region IAnimatedView

	public virtual string Name { get { return this.gameObject.name; } }
	public virtual Animator[] Animators { get { return animators; } }
	public virtual GameObject[] ManageActive { get { return manageActive; } }
	public virtual float InTime { get { return inTime; } }
	public virtual float OutTime { get { return outTime; } }
	public string InTrigger { get { return "in"; } }
	public string OutTrigger { get { return "out"; } }

	public virtual void EnteringView(IView previous) { }
	public virtual void EnteringPercent(float percent)
	{
		float a = inCurve.Evaluate(percent);
		SetAlphas(a);

	}
	public virtual void InView(IView previous) { }
	public virtual void LeavingView(IView newView) { }
	public virtual void LeavingPercent(float percent)
	{
		float a = outCurve.Evaluate(percent);
		SetAlphas(a);
	}
	public virtual void OutOfView(IView newView) { }

	private void SetAlphas(float alpha)
	{
		if (groups != null)
		{
			for (int i = 0; i < groups.Length; i++)
			{
				groups[i].alpha = alpha;
			}
		}
	}

	#endregion
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cocos2D;

namespace tests
{
    public class LogicTest : ActionManagerTest
    {
        string s_pPathGrossini = "Images/grossini";

        public override string title()
        {
            return "Logic test";
        }

        public override void OnEnter()
        {
            base.OnEnter();

            CCSprite grossini = new CCSprite(s_pPathGrossini);
            AddChild(grossini, 0, 2);
            grossini.Position = (new CCPoint(200, 200));

            grossini.RunAction(new CCSequence(
                                                        new CCMoveBy (1, new CCPoint(150, 0)),
                                                        new CCCallFuncN(bugMe))
                                );
        }

        public void bugMe(CCNode node)
        {
            node.StopAllActions(); //After this stop next action not working, if remove this stop everything is working
            node.RunAction(new CCScaleTo(2, 2));
        }
    }
}


text:
package org.cactoos.func;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.cactoos.Func;

/**
 * Function that gets interrupted after a certain time has passed.
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.29.3
 */
public final class Timed<X, Y> implements Func<X, Y> {

    /**
     * Origin function.
     */
    private final Func<X, Future<Y>> func;

    /**
     * Milliseconds.
     */
    private final long time;

    /**
     * Ctor.
     * @param function Origin function
     * @param milliseconds Milliseconds
     */
    public Timed(final Func<X, Y> function, final long milliseconds) {
        this(milliseconds, new Async<>(function));
    }

    /**
     * Ctor.
     * @param milliseconds Milliseconds
     * @param async Async function
     */
    public Timed(final long milliseconds, final Func<X, Future<Y>> async) {
        this.func = async;
        this.time = milliseconds;
    }

    @Override
    public Y apply(final X input) throws Exception {
        final Future<Y> future = this.func.apply(input);
        try {
            return future.get(this.time, TimeUnit.MILLISECONDS);
        } catch (final InterruptedException | ExecutionException
            | TimeoutException exp) {
            future.cancel(true);
            throw exp;
        }
    }
}


text:
<?php

namespace G2R;

class AdapterTest extends TestCase
{
    protected $stubLogger;

    protected $stubGitlabHook;

    protected $stubJobRunner;

    protected $stubRundeckConfig;

    protected $stubProjectsConfig;

    protected $adapter;

    public function setup()
    {
        $this->stubLogger = $this->mockLogger();

        $this->stubGitlabHook = $this->mockGitlabHook();

        $this->stubRundeckConfig = $this->mockRundeckConfig();

        $this->stubJobRunner = $this->mockJobRunner($this->stubRundeckConfig);

        $this->stubProjectsConfig = $this->mockProjectsConfig();

        $this->adapter = new Adapter($this->stubLogger);
    }

    public function testTheLoggerIsLoadedAndDoLog()
    {
        $this->stubLogger
            ->expects($this->once())
            ->method('log');

        $this->adapter->info('test');
    }

    /**
     * @expectedException G2R\Exception\Exception
     * @expectedExceptionMessage The Job runner is missing
     */
    public function testAnExceptionIsThrownWhenNoJobRunnerIsAttached()
    {
        $project = $this->getProjectThatDoesNotRunOnFail();

        $this->stubGitlabHook
            ->method('getBuildStatus')
            ->willReturn('success');

        $this->stubProjectsConfig
            ->method('getProject')
            ->willReturn($project);

        $this->adapter->setHook($this->stubGitlabHook);
        $this->adapter->loadProjectsConfig($this->stubProjectsConfig);

        $this->adapter->run();
    }

    /**
     * @expectedException G2R\Exception\Exception
     * @expectedExceptionMessage The projects config is missing
     */
    public function testAnExceptionIsThrownWhenNoProjectsConfigIsLoad()
    {
        $this->adapter->setHook($this->stubGitlabHook);
        $this->adapter->attachJobRunner($this->stubJobRunner);

        $this->adapter->run();
    }

    public function testTheAdaptaterRunsAJobCorrectly()
    {
        $project = $this->getProjectThatDoesNotRunOnFail();

        $this->stubGitlabHook
            ->method('getBuildStatus')
            ->willReturn('success');

        $this->stubProjectsConfig
            ->method('getProject')
            ->willReturn($project);

        $this->adapter->attachJobRunner($this->stubJobRunner);
        $this->adapter->loadProjectsConfig($this->stubProjectsConfig);
        $this->adapter->setHook($this->stubGitlabHook);

        $this->stubJobRunner
            ->expects($this->once())
            ->method('run');

        $this->adapter->run();
    }

    public function testTheAdaptaterRunsTheJobWhenRunonfailIsTrueEvenIfTheBuildFailed()
    {
        $project = $this->getProjectThatRunOnFail();

        $this->stubGitlabHook
            ->method('getBuildStatus')
            ->willReturn('failed');

        $this->stubProjectsConfig
            ->method('getProject')
            ->willReturn($project);

        $this->adapter->attachJobRunner($this->stubJobRunner);
        $this->adapter->loadProjectsConfig($this->stubProjectsConfig);
        $this->adapter->setHook($this->stubGitlabHook);

        $this->stubJobRunner
            ->expects($this->once())
            ->method('run');

        $this->adapter->run();
    }

    public function testTheAdaptaterDoesntRunTheJobWhenRunonfailIsFalseAndTheBuildFailed()
    {
        $project = $this->getProjectThatDoesNotRunOnFail();

        $this->stubGitlabHook
            ->method('getBuildStatus')
            ->willReturn('failed');

        $this->stubProjectsConfig
            ->method('getProject')
            ->willReturn($project);

        $this->adapter->attachJobRunner($this->stubJobRunner);
        $this->adapter->loadProjectsConfig($this->stubProjectsConfig);
        $this->adapter->setHook($this->stubGitlabHook);

        $this->stubJobRunner
            ->expects($this->never())
            ->method('run');

        $this->adapter->run();
    }

    private function mockLogger()
    {
        return $this
            ->getMockBuilder('Psr\Log\LoggerInterface')
            ->setMethods([
                'emergency',
                'alert',
                'critical',
                'error',
                'warning',
                'notice',
                'info',
                'debug',
                'log',
            ])
            ->getMock();
    }

    private function mockGitlabHook()
    {
        $mock = $this
            ->getMockBuilder('G2R\Gitlab\GitlabHook')
            ->disableOriginalConstructor()
            ->setMethods([
                'getBuildStatus',
                'getProjectName',
                'getRef',
                'getShortUrl',
            ])
            ->getMock();

        $mock->method('getShortUrl')->willReturn('repos/app1');

        $mock->method('getRef')->willReturn('master');

        $mock->method('getProjectName')->willReturn('repos/app1');

        return $mock;
    }

    private function mockRundeckConfig()
    {
        $mock = $this
            ->getMockBuilder('G2R\Config\RundeckConfig')
            ->disableOriginalConstructor()
            ->setMethods([
                'getApiUrl',
                'getFilename',
            ])
            ->getMock();

        $mock->method('getFilename')->willReturn(__DIR__);

        return $mock;
    }

    private function mockJobRunner($rundeckConfig)
    {
        $mock = $this
            ->getMockBuilder('G2R\Rundeck\JobRunner')
            ->disableOriginalConstructor()
            ->setMethods([
                'getConfig',
                'run',
            ])
            ->getMock();

        $mock->method('getConfig')->willReturn($rundeckConfig);

        return $mock;
    }

    private function mockProjectsConfig()
    {
        $mock = $this
            ->getMockBuilder('G2R\Config\ProjectConfig')
            ->disableOriginalConstructor()
            ->setMethods([
                'getProject',
                'getFilename',
            ])
            ->getMock();

        return $mock;
    }

    private function getProjectThatRunOnFail()
    {
        return [
            'name'         => 'repos/app1',
            'jobId'        => '558d3c76-7768-4056-a10c-0842ecae0ca9',
            'ref'          => 'master',
            'runOnFail'    => true,
            'runOnTagOnly' => true,
            'jobArgs'      => [
                'arg1' => 'foo',
                'arg2' => 'bar',
            ],
            'runJobAs'     => 'foo',
        ];
    }

    private function getProjectThatDoesNotRunOnFail()
    {
        return [
            'name'         => 'repos/app1',
            'jobId'        => '558d3c76-7768-4056-a10c-0842ecae0ca9',
            'ref'          => 'master',
            'runOnFail'    => false,
            'runOnTagOnly' => true,
            'jobArgs'      => [
                'arg1' => 'foo',
                'arg2' => 'bar',
            ],
            'runJobAs'     => 'foo',
        ];
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>paramz.optimization.optimization.opt_lbfgsb</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package paramz ::
        Package optimization ::
        Module optimization ::
        Class opt_lbfgsb

[hide private]

[frames] | no frames]

Class opt_lbfgsb

source code

  <map id="uml_class_diagram_for_paramz_o_7" name="uml_class_diagram_for_paramz_o_7">
<area shape="rect" id="node1_5" href="paramz.optimization.optimization.opt_lbfgsb-class.html#__init__" title="x.__init__(...) initializes x; see help(type(x)) for signature" alt="" coords="18,155,289,175"/>
<area shape="rect" id="node1_6" href="paramz.optimization.optimization.opt_lbfgsb-class.html#opt" title="Run the optimizer" alt="" coords="18,175,289,195"/>
<area shape="rect" id="node1" href="paramz.optimization.optimization.opt_lbfgsb-class.html" title="paramz.optimization.optimization.opt_lbfgsb" alt="" coords="5,123,300,201"/>
<area shape="rect" id="node2_7" href="paramz.optimization.optimization.Optimizer-class.html#run" title="paramz.optimization.optimization.Optimizer.run" alt="" coords="77,37,230,57"/>
<area shape="rect" id="node2_8" href="paramz.optimization.optimization.Optimizer-class.html#__str__" title="str(x)" alt="" coords="77,57,230,77"/>
<area shape="rect" id="node2_9" href="paramz.optimization.optimization.Optimizer-class.html#__getstate__" title="paramz.optimization.optimization.Optimizer.__getstate__" alt="" coords="77,77,230,97"/>
<area shape="rect" id="node2" href="paramz.optimization.optimization.Optimizer-class.html" title="Superclass for all the optimizers." alt="" coords="64,5,241,104"/>
</map>

        Instance Methods
        [hide private]

          __init__(self,
        *args,
        **kwargs)

      x.__init__(...) initializes x; see help(type(x)) for signature

            source code

          opt(self,
        x_init,
        f_fp=None,
        f=None,
        fp=None)

      Run the optimizer

            source code

Inherited from Optimizer:
      __getstate__,
      __str__,
      run

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __subclasshook__

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        *args,
        **kwargs)

(Constructor)

  	source code

x.__init__(...) initializes x; see help(type(x)) for signature

Overrides:
        object.__init__

(inherited documentation)

opt(self,
        x_init,
        f_fp=None,
        f=None,
        fp=None)

  	source code

Run the optimizer

Overrides:
        Optimizer.opt

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Tue Jul  4 11:59:51 2017

      http://epydoc.sourceforge.net


text:
package algo.fts.node;

public class NodeMessage3 {

    private int sender, seq;

    public NodeMessage3(int sender, int seq) {
        this.sender = sender;
        this.seq = seq;
    }

    public int getSenderId() {
        return this.sender;
    }

    public int getSeq() {
        return this.seq;
    }

}


text:
package com.atypon.wayf.facade.impl;

import com.atypon.wayf.facade.ErrorLoggerFacade;
import io.reactivex.Completable;

public class ErrorLoggerFacadeMockImpl implements ErrorLoggerFacade {
    private int statusCode;
    private Throwable exception;

    public int getStatusCode() {
        return statusCode;
    }

    public Throwable getException() {
        return exception;
    }

    @Override
    public Completable buildAndLogError(int statusCode, Throwable t) {
        this.statusCode = statusCode;
        this.exception = t;

        return Completable.complete();
    }
}


text:
import { HttpResponse } from '@angular/common/http';
import { StorageCacheItem } from '../interfaces/cache-storage-item.interface';
import { isHttpResponse } from './is-http-response.helper';
import { isJsOrResponseType } from './is-js-or-response-type.helper';

export async function decodeRawData(data: StorageCacheItem): Promise<any> {
    const dataJson = JSON.parse(data.value);
    if (isJsOrResponseType(data)) {
        if (isHttpResponse(dataJson)) {
            const response: any = {
                body: dataJson._body || dataJson.body,
                status: dataJson.status,
                headers: dataJson.headers,
                statusText: dataJson.statusText,
                url: dataJson.url
            };

            return new HttpResponse(response);
        }

        return dataJson;
    } else {
        // Technique derived from: https://stackoverflow.com/a/36183085
        const response = await fetch(dataJson);

        return response.blob();
    }
}


text:
import StepsHandler from '../src/steps.handler';
import { expect } from 'chai';

const settings = {
    cucumberautocomplete: {
        steps: ['/data/steps/cucumberExpressions.steps.js'],
        syncfeatures: '/data/features/cucumberExpressions.feature',
        smartSnippets: true,
        stepsInvariants: true,
        strictGherkinCompletion: true,
        customParameters: [
        ]
    }
};

const stepsDefinitionNum = 8;
const s = new StepsHandler(__dirname, settings);

describe('getElements', () => {
    const e = s.getElements();
    it('should correctly fill used steps counts', () => {

        expect(e).to.have.length(stepsDefinitionNum)

        expect(e[0]).to.have.property("text", "I have a {int} in my belly");
        expect(e[0]).to.have.property("count", 6);

        expect(e[1]).to.have.property("text", "I have a {float} in my belly");
        expect(e[1]).to.have.property("count", 10);

        expect(e[2]).to.have.property("text", "I have a important {word} in my belly");
        expect(e[2]).to.have.property("count", 5);

        expect(e[3]).to.have.property("text", "I have a {string} in my belly");
        expect(e[3]).to.have.property("count", 6);

        expect(e[4]).to.have.property("text", "I have a wildcard {} in my belly");
        expect(e[4]).to.have.property("count", 2);

        expect(e[5]).to.have.property("text", "I have a cucumber in my belly/stomach");
        expect(e[5]).to.have.property("count", 2);

        expect(e[6]).to.have.property("text", "I have a gherkin(s) in my belly");
        expect(e[6]).to.have.property("count", 2);

        expect(e[7]).to.have.property("text", "I have a cucumber\(s\) in my belly");
        expect(e[7]).to.have.property("count", 1);
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:pen="http://www.pentaho.com/xml/schemas/pentaho-blueprint"
           xsi:schemaLocation="
            http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
            http://www.pentaho.com/xml/schemas/pentaho-blueprint http://www.pentaho.com/xml/schemas/pentaho-blueprint.xsd">
  <bean id="hive2DatabaseMeta" class="org.pentaho.big.data.kettle.plugins.hive.Hive2DatabaseMeta" scope="prototype">
    <pen:di-plugin type="org.pentaho.di.core.plugins.DatabasePluginType"/>
    <argument ref="driverLocator"/>
  </bean>

  <!--<bean id="hive2SimbaDatabaseMeta" class="org.pentaho.big.data.kettle.plugins.hive.Hive2SimbaDatabaseMeta" scope="prototype">
    <pen:di-plugin type="org.pentaho.di.core.plugins.DatabasePluginType"/>
  </bean>-->

  <bean id="hiveDatabaseMeta" class="org.pentaho.big.data.kettle.plugins.hive.HiveDatabaseMeta" scope="prototype">
    <pen:di-plugin type="org.pentaho.di.core.plugins.DatabasePluginType"/>
    <argument ref="driverLocator"/>
  </bean>

  <bean id="impalaDatabaseMeta" class="org.pentaho.big.data.kettle.plugins.hive.ImpalaDatabaseMeta" scope="prototype">
    <pen:di-plugin type="org.pentaho.di.core.plugins.DatabasePluginType"/>
    <argument ref="driverLocator"/>
  </bean>

  <bean id="impalaSimbaDatabaseMeta" class="org.pentaho.big.data.kettle.plugins.hive.ImpalaSimbaDatabaseMeta" scope="prototype">
    <pen:di-plugin type="org.pentaho.di.core.plugins.DatabasePluginType"/>
    <argument ref="driverLocator"/>
  </bean>

  <bean id="sparkSimbaDatabaseMeta" class="org.pentaho.big.data.kettle.plugins.hive.SparkSimbaDatabaseMeta" scope="prototype">
    <pen:di-plugin type="org.pentaho.di.core.plugins.DatabasePluginType"/>
    <argument ref="driverLocator"/>
  </bean>

  <reference id="driverLocator" interface="org.pentaho.big.data.api.jdbc.DriverLocator"/>

  <!--<bean id="hive2DatabaseDialect" class="org.pentaho.big.data.kettle.plugins.hive.Hive2DatabaseDialect"/>
  <bean id="hive2SimbaDatabaseDialect" class="org.pentaho.big.data.kettle.plugins.hive.Hive2SimbaDatabaseDialect"/>
  <bean id="impalaDatabaseDialect" class="org.pentaho.big.data.kettle.plugins.hive.ImpalaDatabaseDialect"/>
  <bean id="impalaSimbaDatabaseDialect" class="org.pentaho.big.data.kettle.plugins.hive.ImpalaSimbaDatabaseDialect"/>

  <service ref="hive2DatabaseDialect" interface="org.pentaho.database.IDatabaseDialect"/>
  <service ref="hive2SimbaDatabaseDialect" interface="org.pentaho.database.IDatabaseDialect"/>
  <service ref="impalaDatabaseDialect" interface="org.pentaho.database.IDatabaseDialect"/>
  <service ref="impalaSimbaDatabaseDialect" interface="org.pentaho.database.IDatabaseDialect"/>-->
</blueprint>


text:
namespace SpotifyWebApi.Model
{
    using Newtonsoft.Json;

    /// <summary>
    /// The <see cref="Device"/>.
    /// </summary>
    public class Device
    {
        /// <summary>
        /// Gets or sets the device ID. This may be null.
        /// </summary>
        [JsonProperty("id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets a value indicating if this device is the currently active device.
        /// </summary>
        [JsonProperty("is_active")]
        public bool IsActive { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether controlling this device is restricted.
        /// At present if this is "true" then no Web API commands will be accepted by this device.
        /// </summary>
        [JsonProperty("is_restricted")]
        public bool IsRestricted { get; set; }

        /// <summary>
        /// Gets or sets the name of the device.
        /// </summary>
        [JsonProperty("name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets device type, such as "Computer", "Smartphone" or "Speaker".
        /// </summary>
        [JsonProperty("type")]
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets the current volume in percent. This may be null.
        /// </summary>
        [JsonProperty("volume_percent")]
        public int? VolumePercent { get; set; }
    }
}


text:
module Fog
  module CDN
    class AWS
      class Real
        require 'fog/aws/parsers/cdn/streaming_distribution'

        # Create a new streaming distribution in CloudFront.
        #
        # @param options [Hash] Config for distribution.
        #
        #   REQUIRED:
        #   * S3Origin [Hash]:
        #     * DNSName [String] Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'.
        #   OPTIONAL:
        #   * CallerReference [String] Used to prevent replay, defaults to Time.now.to_i.to_s.
        #   * Comment [String] Optional comment about distribution.
        #   * CNAME [Array] Optional array of strings to set as CNAMEs.
        #   * Enabled [Boolean] Whether or not distribution should accept requests, defaults to true.
        #   * Logging [Hash]: Optional logging config.
        #     * Bucket [String] Bucket to store logs in, ie 'mylogs.s3.amazonaws.com'.
        #     * Prefix [String] Optional prefix for log filenames, ie 'myprefix/'.
        #
        # @return [Excon::Response]
        #   * body[Hash]:
        #     * Id [String] - Id of distribution.
        #     * Status'[String] - Status of distribution.
        #     * LastModifiedTime [String] - Timestamp of last modification of distribution.
        #     * DomainName [String] - Domain name of distribution.
        #     * StreamingDistributionConfig [Array]:
        #       * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s.
        #       * CNAME [Array] - Array of associated cnames.
        #       * Comment [String] - Comment associated with distribution.
        #       * Enabled [Boolean] - Whether or not distribution is enabled.
        #       * Logging [Hash]:
        #         * Bucket [String] - Bucket logs are stored in.
        #         * Prefix [String] - Prefix logs are stored with.
        #
        # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateStreamingDistribution.html

        def post_streaming_distribution(options = {})
          options['CallerReference'] = Time.now.to_i.to_s
          data = '<?xml version="1.0" encoding="UTF-8"?>'
          data << "<StreamingDistributionConfig xmlns=\"http://cloudfront.amazonaws.com/doc/#{@version}/\">"
          for key, value in options
            case value
            when Array
              for item in value
                data << "<#{key}>#{item}</#{key}>"
              end
            when Hash
              data << "<#{key}>"
              for inner_key, inner_value in value
                data << "<#{inner_key}>#{inner_value}</#{inner_key}>"
              end
              data << "</#{key}>"
            else
              data << "<#{key}>#{value}</#{key}>"
            end
          end
          data << "</StreamingDistributionConfig>"
          request({
            :body       => data,
            :expects    => 201,
            :headers    => { 'Content-Type' => 'text/xml' },
            :idempotent => true,
            :method     => 'POST',
            :parser     => Fog::Parsers::CDN::AWS::StreamingDistribution.new,
            :path       => "/streaming-distribution"
          })
        end
      end

      class Mock
        require 'time'

        def post_streaming_distribution(options = {})
          if self.data[:streaming_distributions].values.any? { |d| (d['CNAME'] & (options['CNAME']||[])).empty? }
            Fog::CDN::AWS::Mock.error(:invalid_argument, 'CNAME is already in use')
          end

          response = Excon::Response.new

          response.status = 201
          options['CallerReference'] = Time.now.to_i.to_s

          dist_id = Fog::CDN::AWS::Mock.distribution_id

          distribution = {
            'DomainName' => Fog::CDN::AWS::Mock.domain_name,
            'Id' => dist_id,
            'Status' => 'InProgress',
            'LastModifiedTime' => Time.now.utc.iso8601,
            'StreamingDistributionConfig' => {
              'CallerReference' => options['CallerReference'],
              'CNAME' => options['CNAME'] || [],
              'Comment' => options['Comment'],
              'Enabled' => options['Enabled'],
              'Logging' => {
                'Bucket' => options['Bucket'],
                'Prefix' => options['Prefix']
              },
              'S3Origin' => options['S3Origin'],
              'TrustedSigners' => options['TrustedSigners'] || []
            }
          }

          self.data[:streaming_distributions][dist_id] = distribution

          response.body = distribution
          response
        end
      end
    end
  end
end


text:
#pragma once
#include "paddle/fluid/operators/detail/strided_memcpy.h"

namespace paddle {
namespace operators {

// Strided memory copy from src to dst.
//
// The src and dst should be both on dev_ctx.GetPlace(), otherwise, there will
// be a segment fault.
//
// The stride of an array (also referred to as increment, pitch or step size) is
// the number of locations in memory between beginnings of successive array
// elements
//
// For example, for tensor like [1, 3, 300, 300]. If there is no padding, the
// stride is [270000, 90000, 300, 1].
//
// NOTE: When use GPU, the memcpy is async. To sync memcpy, please invoke
// `dev_ctx.Wait()`.
template <typename T>
inline void StridedMemcpy(const platform::DeviceContext& dev_ctx, const T* src,
                          const framework::DDim& src_stride,
                          const framework::DDim& dst_dim,
                          const framework::DDim& dst_stride, T* dst) {
  paddle::operators::detail::StridedCopyDimVisitor<T> func(
      dev_ctx, src, src_stride, dst_stride, dst);
  boost::apply_visitor(func, dst_dim);
}

// Strided numel memory copy from src to dst by the specified axis
//
// For example, for a tensor dims [4, 20, 100], the strieded numel is
// [8000, 2000, 100]
//
// NOTE: The src and dst tensor should have the same elements
// except the specified axis.
template <typename T>
inline void StridedNumelCopyWithAxis(const platform::DeviceContext& ctx,
                                     int64_t axis, T* dst,
                                     const framework::DDim& dst_stride_numel,
                                     const T* src,
                                     const framework::DDim& src_stride_numel,
                                     int64_t size) {
  int64_t before = dst_stride_numel[0] / dst_stride_numel[axis];
  int64_t src_after = src_stride_numel[axis];
  int64_t dst_after = dst_stride_numel[axis];
  auto place = ctx.GetPlace();

  PADDLE_ENFORCE_EQ(src_stride_numel.size(), dst_stride_numel.size(),
                    "src and dst tensor should have the same dims size.");

  for (int64_t i = 0; i < axis; ++i) {
    if (i < axis) {
      PADDLE_ENFORCE_EQ(src_stride_numel[i] / src_stride_numel[axis],
                        dst_stride_numel[i] / dst_stride_numel[axis],
                        "src and dst should have the same elements "
                        "except the specified axis.");
    } else if (i == axis) {
      continue;
    } else {
      PADDLE_ENFORCE_EQ(src_stride_numel[i], dst_stride_numel[i],
                        "src and dst should have the same elements "
                        "except the specified axis.");
    }
  }

  for (int64_t i = 0; i < before; ++i) {
    if (platform::is_cpu_place(place)) {
      auto& cpu_place = boost::get<platform::CPUPlace>(place);
      memory::Copy(cpu_place, dst + i * dst_after, cpu_place,
                   src + i * src_after, sizeof(T) * size);
    } else {
#ifdef PADDLE_WITH_CUDA
      auto& gpu_place = boost::get<platform::CUDAPlace>(place);
      auto& cuda_ctx =
          reinterpret_cast<const platform::CUDADeviceContext&>(ctx);
      memory::Copy(gpu_place, dst + i * dst_after, gpu_place,
                   src + i * src_after, sizeof(T) * size, cuda_ctx.stream());
#else
      PADDLE_THROW("Paddle is not compiled with GPU");
#endif
    }
  }
}

}  // namespace operators
}  // namespace paddle


text:
package org.apache.bookkeeper.client;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.bookkeeper.proto.BookieProtocol.FLAG_HIGH_PRIORITY;
import static org.apache.bookkeeper.proto.BookieProtocol.FLAG_NONE;
import static org.apache.bookkeeper.proto.BookieProtocol.FLAG_RECOVERY_ADD;

import com.google.common.collect.ImmutableMap;
import io.netty.buffer.ByteBuf;
import io.netty.util.Recycler;
import io.netty.util.Recycler.Handle;
import io.netty.util.ReferenceCountUtil;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.bookkeeper.client.AsyncCallback.AddCallbackWithLatency;
import org.apache.bookkeeper.client.api.WriteFlag;
import org.apache.bookkeeper.net.BookieId;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback;
import org.apache.bookkeeper.util.ByteBufList;
import org.apache.bookkeeper.util.MathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This represents a pending add operation. When it has got success from all
 * bookies, it sees if its at the head of the pending adds queue, and if yes,
 * sends ack back to the application. If a bookie fails, a replacement is made
 * and placed at the same position in the ensemble. The pending adds are then
 * rereplicated.
 *
 *
 */
class PendingAddOp implements Runnable, WriteCallback {
    private static final Logger LOG = LoggerFactory.getLogger(PendingAddOp.class);

    ByteBuf payload;
    ByteBufList toSend;
    AddCallbackWithLatency cb;
    Object ctx;
    long entryId;
    int entryLength;

    DistributionSchedule.AckSet ackSet;
    boolean completed = false;

    LedgerHandle lh;
    ClientContext clientCtx;
    boolean isRecoveryAdd = false;
    long requestTimeNanos;
    long qwcLatency; // Quorum Write Completion Latency after response from quorum bookies.
    Set<BookieId> addEntrySuccessBookies;
    long writeDelayedStartTime; // min fault domains completion latency after response from ack quorum bookies

    long currentLedgerLength;
    int pendingWriteRequests;
    boolean callbackTriggered;
    boolean hasRun;
    EnumSet<WriteFlag> writeFlags;
    boolean allowFailFast = false;
    List<BookieId> ensemble;

    static PendingAddOp create(LedgerHandle lh, ClientContext clientCtx,
                               List<BookieId> ensemble,
                               ByteBuf payload, EnumSet<WriteFlag> writeFlags,
                               AddCallbackWithLatency cb, Object ctx) {
        PendingAddOp op = RECYCLER.get();
        op.lh = lh;
        op.clientCtx = clientCtx;
        op.isRecoveryAdd = false;
        op.cb = cb;
        op.ctx = ctx;
        op.entryId = LedgerHandle.INVALID_ENTRY_ID;
        op.currentLedgerLength = -1;
        op.payload = payload;
        op.entryLength = payload.readableBytes();

        op.completed = false;
        op.ensemble = ensemble;
        op.ackSet = lh.getDistributionSchedule().getAckSet();
        op.pendingWriteRequests = 0;
        op.callbackTriggered = false;
        op.hasRun = false;
        op.requestTimeNanos = Long.MAX_VALUE;
        op.allowFailFast = false;
        op.qwcLatency = 0;
        op.writeFlags = writeFlags;

        if (op.addEntrySuccessBookies == null) {
            op.addEntrySuccessBookies = new HashSet<>();
        } else {
            op.addEntrySuccessBookies.clear();
        }
        op.writeDelayedStartTime = -1;

        return op;
    }

    /**
     * Enable the recovery add flag for this operation.
     * @see LedgerHandle#asyncRecoveryAddEntry
     */
    PendingAddOp enableRecoveryAdd() {
        isRecoveryAdd = true;
        return this;
    }

    PendingAddOp allowFailFastOnUnwritableChannel() {
        allowFailFast = true;
        return this;
    }

    void setEntryId(long entryId) {
        this.entryId = entryId;
    }

    void setLedgerLength(long ledgerLength) {
        this.currentLedgerLength = ledgerLength;
    }

    long getEntryId() {
        return this.entryId;
    }

    void sendWriteRequest(List<BookieId> ensemble, int bookieIndex) {
        int flags = isRecoveryAdd ? FLAG_RECOVERY_ADD | FLAG_HIGH_PRIORITY : FLAG_NONE;

        clientCtx.getBookieClient().addEntry(ensemble.get(bookieIndex),
                                             lh.ledgerId, lh.ledgerKey, entryId, toSend, this, bookieIndex,
                                             flags, allowFailFast, lh.writeFlags);
        ++pendingWriteRequests;
    }

    boolean maybeTimeout() {
        if (MathUtils.elapsedNanos(requestTimeNanos) >= clientCtx.getConf().addEntryQuorumTimeoutNanos) {
            timeoutQuorumWait();
            return true;
        }
        return false;
    }

    void timeoutQuorumWait() {
        try {
            clientCtx.getMainWorkerPool().executeOrdered(lh.ledgerId, new Runnable() {
                @Override
                public void run() {
                    if (completed) {
                        return;
                    } else if (addEntrySuccessBookies.size() >= lh.getLedgerMetadata().getAckQuorumSize()) {
                        // If ackQuorum number of bookies have acknowledged the write but still not complete, indicates
                        // failures due to not having been written to enough fault domains. Increment corresponding
                        // counter.
                        clientCtx.getClientStats().getWriteTimedOutDueToNotEnoughFaultDomains().inc();
                    }
                    lh.handleUnrecoverableErrorDuringAdd(BKException.Code.AddEntryQuorumTimeoutException);
                }
                @Override
                public String toString() {
                    return String.format("AddEntryQuorumTimeout(lid=%d, eid=%d)", lh.ledgerId, entryId);
                }
            });
        } catch (RejectedExecutionException e) {
            LOG.warn("Timeout add entry quorum wait failed {} entry: {}", lh.ledgerId, entryId);
        }
    }

    void unsetSuccessAndSendWriteRequest(List<BookieId> ensemble, int bookieIndex) {
        // update the ensemble
        this.ensemble = ensemble;

        if (toSend == null) {
            // this addOp hasn't yet had its mac computed. When the mac is
            // computed, its write requests will be sent, so no need to send it
            // now
            return;
        }
        // Suppose that unset doesn't happen on the write set of an entry. In this
        // case we don't need to resend the write request upon an ensemble change.
        // We do need to invoke #sendAddSuccessCallbacks() for such entries because
        // they may have already completed, but they are just waiting for the ensemble
        // to change.
        // E.g.
        // ensemble (A, B, C, D), entry k is written to (A, B, D). An ensemble change
        // happens to replace C with E. Entry k does not complete until C is
        // replaced with E successfully. When the ensemble change completes, it tries
        // to unset entry k. C however is not in k's write set, so no entry is written
        // again, and no one triggers #sendAddSuccessCallbacks. Consequently, k never
        // completes.
        //
        // We call sendAddSuccessCallback when unsetting t cover this case.
        DistributionSchedule.WriteSet writeSet = lh.distributionSchedule.getWriteSet(entryId);
        try {
            if (!writeSet.contains(bookieIndex)) {
                lh.sendAddSuccessCallbacks();
                return;
            }
        } finally {
            writeSet.recycle();
        }

        if (callbackTriggered) {
            return;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Unsetting success for ledger: " + lh.ledgerId + " entry: " + entryId + " bookie index: "
                      + bookieIndex);
        }

        // if we had already heard a success from this array index, need to
        // increment our number of responses that are pending, since we are
        // going to unset this success
        if (!ackSet.removeBookieAndCheck(bookieIndex)) {
            // unset completed if this results in loss of ack quorum
            completed = false;
        }

        sendWriteRequest(ensemble, bookieIndex);
    }

    /**
     * Initiate the add operation.
     */
    @Override
    public void run() {
        hasRun = true;
        if (callbackTriggered) {
            // this should only be true if the request was failed due
            // to another request ahead in the pending queue,
            // so we can just ignore this request
            maybeRecycle();
            return;
        }

        this.requestTimeNanos = MathUtils.nowInNano();
        checkNotNull(lh);
        checkNotNull(lh.macManager);

        this.toSend = lh.macManager.computeDigestAndPackageForSending(
                entryId, lh.lastAddConfirmed, currentLedgerLength,
                payload);
        // ownership of RefCounted ByteBuf was passed to computeDigestAndPackageForSending
        payload = null;

        // We are about to send. Check if we need to make an ensemble change
        // because of delayed write errors
        lh.maybeHandleDelayedWriteBookieFailure();

        // Iterate over set and trigger the sendWriteRequests
        DistributionSchedule.WriteSet writeSet = lh.distributionSchedule.getWriteSet(entryId);

        try {
            for (int i = 0; i < writeSet.size(); i++) {
                sendWriteRequest(ensemble, writeSet.get(i));
            }
        } finally {
            writeSet.recycle();
        }
    }

    @Override
    public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) {
        int bookieIndex = (Integer) ctx;
        --pendingWriteRequests;

        if (!ensemble.get(bookieIndex).equals(addr)) {
            // ensemble has already changed, failure of this addr is immaterial
            if (LOG.isDebugEnabled()) {
                LOG.debug("Write did not succeed: " + ledgerId + ", " + entryId + ". But we have already fixed it.");
            }
            return;
        }

        // must record all acks, even if complete (completion can be undone by an ensemble change)
        boolean ackQuorum = false;
        if (BKException.Code.OK == rc) {
            ackQuorum = ackSet.completeBookieAndCheck(bookieIndex);
            addEntrySuccessBookies.add(ensemble.get(bookieIndex));
        }

        if (completed) {
            if (rc != BKException.Code.OK) {
                // Got an error after satisfying AQ. This means we are under replicated at the create itself.
                // Update the stat to reflect it.
                clientCtx.getClientStats().getAddOpUrCounter().inc();
                if (!clientCtx.getConf().disableEnsembleChangeFeature.isAvailable()
                        && !clientCtx.getConf().delayEnsembleChange) {
                    lh.notifyWriteFailed(bookieIndex, addr);
                }
            }
            // even the add operation is completed, but because we don't reset completed flag back to false when
            // #unsetSuccessAndSendWriteRequest doesn't break ack quorum constraint. we still have current pending
            // add op is completed but never callback. so do a check here to complete again.
            //
            // E.g. entry x is going to complete.
            //
            // 1) entry x + k hits a failure. lh.handleBookieFailure increases blockAddCompletions to 1, for ensemble
            //    change
            // 2) entry x receives all responses, sets completed to true but fails to send success callback because
            //    blockAddCompletions is 1
            // 3) ensemble change completed. lh unset success starting from x to x+k, but since the unset doesn't break
            //    ackSet constraint. #removeBookieAndCheck doesn't set completed back to false.
            // 4) so when the retry request on new bookie completes, it finds the pending op is already completed.
            //    we have to trigger #sendAddSuccessCallbacks
            //
            sendAddSuccessCallbacks();
            // I am already finished, ignore incoming responses.
            // otherwise, we might hit the following error handling logic, which might cause bad things.
            maybeRecycle();
            return;
        }

        switch (rc) {
        case BKException.Code.OK:
            // continue
            break;
        case BKException.Code.ClientClosedException:
            // bookie client is closed.
            lh.errorOutPendingAdds(rc);
            return;
        case BKException.Code.IllegalOpException:
            // illegal operation requested, like using unsupported feature in v2 protocol
            lh.handleUnrecoverableErrorDuringAdd(rc);
            return;
        case BKException.Code.LedgerFencedException:
            LOG.warn("Fencing exception on write: L{} E{} on {}",
                    ledgerId, entryId, addr);
            lh.handleUnrecoverableErrorDuringAdd(rc);
            return;
        case BKException.Code.UnauthorizedAccessException:
            LOG.warn("Unauthorized access exception on write: L{} E{} on {}",
                    ledgerId, entryId, addr);
            lh.handleUnrecoverableErrorDuringAdd(rc);
            return;
        default:
            if (clientCtx.getConf().delayEnsembleChange) {
                if (ackSet.failBookieAndCheck(bookieIndex, addr)
                        || rc == BKException.Code.WriteOnReadOnlyBookieException) {
                    Map<Integer, BookieId> failedBookies = ackSet.getFailedBookies();
                    LOG.warn("Failed to write entry ({}, {}) to bookies {}, handling failures.",
                            ledgerId, entryId, failedBookies);
                    // we can't meet ack quorum requirement, trigger ensemble change.
                    lh.handleBookieFailure(failedBookies);
                } else if (LOG.isDebugEnabled()) {
                    LOG.debug("Failed to write entry ({}, {}) to bookie ({}, {}),"
                                    + " but it didn't break ack quorum, delaying ensemble change : {}",
                            ledgerId, entryId, bookieIndex, addr, BKException.getMessage(rc));
                }
            } else {
                LOG.warn("Failed to write entry ({}, {}) to bookie ({}, {}): {}",
                        ledgerId, entryId, bookieIndex, addr, BKException.getMessage(rc));
                lh.handleBookieFailure(ImmutableMap.of(bookieIndex, addr));
            }
            return;
        }

        if (ackQuorum && !completed) {
            if (clientCtx.getConf().enforceMinNumFaultDomainsForWrite
                && !(clientCtx.getPlacementPolicy()
                              .areAckedBookiesAdheringToPlacementPolicy(addEntrySuccessBookies,
                                                                        lh.getLedgerMetadata().getWriteQuorumSize(),
                                                                        lh.getLedgerMetadata().getAckQuorumSize()))) {
                LOG.warn("Write success for entry ID {} delayed, not acknowledged by bookies in enough fault domains",
                         entryId);
                // Increment to indicate write did not complete due to not enough fault domains
                clientCtx.getClientStats().getWriteDelayedDueToNotEnoughFaultDomains().inc();

                // Only do this for the first time.
                if (writeDelayedStartTime == -1) {
                    writeDelayedStartTime = MathUtils.nowInNano();
                }
            } else {
                completed = true;
                this.qwcLatency = MathUtils.elapsedNanos(requestTimeNanos);

                if (writeDelayedStartTime != -1) {
                    clientCtx.getClientStats()
                             .getWriteDelayedDueToNotEnoughFaultDomainsLatency()
                             .registerSuccessfulEvent(MathUtils.elapsedNanos(writeDelayedStartTime),
                                                      TimeUnit.NANOSECONDS);
                }

                sendAddSuccessCallbacks();
            }
        }
    }

    void sendAddSuccessCallbacks() {
        lh.sendAddSuccessCallbacks();
    }

    void submitCallback(final int rc) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Submit callback (lid:{}, eid: {}). rc:{}", lh.getId(), entryId, rc);
        }

        long latencyNanos = MathUtils.elapsedNanos(requestTimeNanos);
        if (rc != BKException.Code.OK) {
            clientCtx.getClientStats().getAddOpLogger().registerFailedEvent(latencyNanos, TimeUnit.NANOSECONDS);
            LOG.error("Write of ledger entry to quorum failed: L{} E{}",
                      lh.getId(), entryId);
        } else {
            clientCtx.getClientStats().getAddOpLogger().registerSuccessfulEvent(latencyNanos, TimeUnit.NANOSECONDS);
        }
        cb.addCompleteWithLatency(rc, lh, entryId, qwcLatency, ctx);
        callbackTriggered = true;

        maybeRecycle();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("PendingAddOp(lid:").append(lh.ledgerId)
          .append(", eid:").append(entryId).append(", completed:")
          .append(completed).append(")");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        return (int) entryId;
    }

    @Override
    public boolean equals(Object o) {
       if (o instanceof PendingAddOp) {
           return (this.entryId == ((PendingAddOp) o).entryId);
       }
       return (this == o);
    }

    private final Handle<PendingAddOp> recyclerHandle;
    private static final Recycler<PendingAddOp> RECYCLER = new Recycler<PendingAddOp>() {
        @Override
        protected PendingAddOp newObject(Recycler.Handle<PendingAddOp> handle) {
            return new PendingAddOp(handle);
        }
    };

    private PendingAddOp(Handle<PendingAddOp> recyclerHandle) {
        this.recyclerHandle = recyclerHandle;
    }

    private void maybeRecycle() {
        /**
         * We have opportunity to recycle two objects here.
         * PendingAddOp#toSend and LedgerHandle#pendingAddOp
         *
         * A. LedgerHandle#pendingAddOp: This can be released after all 3 conditions are met.
         *    - After the callback is run
         *    - After safeRun finished by the executor
         *    - Write responses are returned from all bookies
         *      as BookieClient Holds a reference from the point the addEntry requests are sent.
         *
         * B. ByteBuf can be released after 2 of the conditions are met.
         *    - After the callback is run as we will not retry the write after callback
         *    - After safeRun finished by the executor
         * BookieClient takes and releases on this buffer immediately after sending the data.
         *
         * The object can only be recycled after the above conditions are met
         * otherwise we could end up recycling twice and all
         * joy that goes along with that.
         */
        if (hasRun && callbackTriggered) {
            ReferenceCountUtil.release(toSend);
            toSend = null;
        }
        // only recycle a pending add op after it has been run.
        if (hasRun && toSend == null && pendingWriteRequests == 0) {
            recyclePendAddOpObject();
        }
    }

    public void recyclePendAddOpObject() {
        entryId = LedgerHandle.INVALID_ENTRY_ID;
        currentLedgerLength = -1;
        if (payload != null) {
            ReferenceCountUtil.release(payload);
            payload = null;
        }
        cb = null;
        ctx = null;
        ensemble = null;
        ackSet.recycle();
        ackSet = null;
        lh = null;
        clientCtx = null;
        isRecoveryAdd = false;
        completed = false;
        pendingWriteRequests = 0;
        callbackTriggered = false;
        hasRun = false;
        allowFailFast = false;
        writeFlags = null;
        addEntrySuccessBookies.clear();
        writeDelayedStartTime = -1;

        recyclerHandle.recycle(this);
    }
}


text:
layout: post
title: Récupérer le nom du fichier JavaScript dans vos règles ESLint
categories: []
tags: ["ESLint", "NodeJS", "JavaScript", "Qualité"]
fullview: true
twittertitle: ESLint - Informations de Context
twitterdescription: Récupérer le nom du fichier JavaScript dans vos règles ESLint
twitterimage: https://pbs.twimg.com/profile_images/422081374422446080/RNoIP-zD.png
---

Si vous avez lu d'autres articles de ce blog, vous vous doutez que j'aime beaucoup l'outil ESLint qui permet de vérifier la qualité de votre code JavaScript. Le gros avantage de cet outil, si nous le comparons à JSHint ou JSLint, c'est le fait de pouvoir créer très facilement de nouvelles règles, liées à votre application, vos technologies, vos équipes, ...

Voici une petite astuce que j'ai découvert la semaine dernière. Si vous voulez exécuter une règle en fonction du fichier en cours, vous allez pouvoir récupérer le nom de ce fichier grâce à l'objet context disponible dans votre module. Pour rappel, une règle ESLint correspond à un module défini dans un fichier.

Dans l'exemple ci-dessous, le paramètre context sera valorisé automatiquement par ESLint. Il possède une méthode très intéressante : getFilename(); qui, comme son nom l'indique, retournera le nom du fichier.

{% highlight javascript %}
module.exports = function(context) {

    "use strict";

    return {

        "CallExpression": function(node) {
                if(context.getFilename() === "protractor.js"){

                } else {

                }

        }
    };

};
{% endhighlight %}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>AMD Promise Tests</title>
  <link rel="stylesheet" href="../../node_modules/mocha/mocha.css" />


text:
Template.tabsLayout.rendered = function () {
  Session.set('currentTab', 'tabs.one');
  console.log('layout is rendered');
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: liviu
 * Date: 27.09.2017
 * Time: 15:14
 */

class CreateJournalTable extends \Illuminate\Database\Migrations\Migration
{
    public function up()
    {
        if (\Illuminate\Support\Facades\Schema::hasColumn('journal', 'entry')) {
            \Illuminate\Support\Facades\Schema::table('journal', function (\Illuminate\Database\Schema\Blueprint $table) {
                $table->renameColumn('entry', 'action');
            });
        }

        if (\Illuminate\Support\Facades\Schema::hasColumn('journal', 'ip')) {
            \Illuminate\Support\Facades\Schema::table('journal', function (\Illuminate\Database\Schema\Blueprint $table) {
                $table->dropColumn('ip');
            });
        }

        if (\Illuminate\Support\Facades\Schema::hasColumn('journal', 'user_agent')) {
            \Illuminate\Support\Facades\Schema::table('journal', function (\Illuminate\Database\Schema\Blueprint $table) {
                $table->dropColumn('user_agent');
            });
        }
    }

    public function down()
    {
        // no down
    }
}


text:
Assignee Hook
=============

Assign a responsible user to an Action or Medium.

This hook is part of the CampaignChain Community Edition. Look here for
installation instructions: https://github.com/CampaignChain/campaignchain-ce


text:
set -e

# Safety interlock
read -p "Deleting toilRegistry and atree* from Azure. Type 'delete' to continue: " DELETE

if [ "$DELETE" == "delete" ]
then
    # Actually do it
    echo "Deleting..."
    azure storage table list --json | jq -r '.[].name' | grep "^atree" | xargs -n1 -r azure storage table delete -q
    azure storage table list --json | jq -r '.[].name' | grep '^toilRegistry$' | xargs -n1 -r azure storage table delete -q
    azure storage container list --json | jq -r '.[].name' | grep "^atree" | xargs -n1 -r azure storage container delete -q
else
    echo "Not deleting anything."
fi