text:
import struct
import binascii

class v_enum(object):
    def __init__(self):
        object.__setattr__(self, '_vs_reverseMap', {})

    def __setattr__(self, name, value):
        '''if duplicate values, last one wins!'''
        self._vs_reverseMap[value] = name
        return object.__setattr__(self, name, value)

    def vsReverseMapping(self, val, default=None):
        '''Maps an integer to its name. Returns default if not found'''
        return self._vs_reverseMap.get(val, default)

class v_bitmask(object):
    def __init__(self):
        object.__setattr__(self, "_vs_reverseMap", {})

    def __setattr__(self, name, value):
        self._vs_reverseMap[value] = name
        return object.__setattr__(self, name, value)

    def vsReverseMapping(self, val, default=None):
        '''Returns a list of names where apply the AND of the mask and val is non-zero'''
        return [v for k, v in self._vs_reverseMap.items() if (val & k) != 0]

class v_base(object):
    def __init__(self):
        self._vs_meta = {}

    def vsGetMeta(self, name, defval=None):
        return self._vs_meta.get(name, defval)

    def vsSetMeta(self, name, value):
        self._vs_meta[name] = value

    # Sub-classes (primitive base, or VStruct must have these
    def vsParse(self, bytes):
        return NotImplemented

    def vsCalculate(self):
        pass

    def vsIsPrim(self):
        return NotImplemented

    def vsGetTypeName(self):
        return NotImplemented

class v_prim(v_base):
    def __init__(self):
        v_base.__init__(self)
        # Used by base len(),vsGetFormat, etc...
        self._vs_value = None
        self._vs_length = None
        self._vs_fmt = None
        self._vs_align = None

    def vsIsPrim(self):
        return True

    def vsGetTypeName(self):
        return self.__class__.__name__

    def vsParse(self, bytes, offset=0):
        '''
        Parser for primitives which assumes we are calling parse directly.
        '''
        return NotImplemented

    def vsParseFd(self, fd):
        # Most primitives should be able to simply use this...
        fbytes = fd.read(self._vs_length)
        if len(fbytes) != self._vs_length:
            raise Exception('Not enough data in fd!')

        self.vsParse(fbytes)

    def vsEmit(self):
        '''
        Return the actual bytes which represent this field
        '''
        return NotImplemented

    def vsGetValue(self):
        '''
        Get the type specific value for this field.
        (Used by the structure dereference method to return
        a python native for the field by name)
        '''
        return self._vs_value

    def vsSetValue(self, value):
        '''
        Set the type specific value for this field.
        '''
        self._vs_value = value

    def vsSetLength(self, size):
        '''
        Set the length of this primitive type.  This may be used to
        dynamically update the length of string fields, etc...
        '''
        return NotImplemented

    def __repr__(self):
        return repr(self.vsGetValue())

    def __len__(self):
        return self._vs_length

    def __str__(self):
        return str(self.vsGetValue())

    def __hash__(self):
        return hash(self.vsGetValue())

num_fmts = {
    # big endian unsigned
    (True, 1): '>B',
    (True, 2): '>H',
    (True, 4): '>I',
    (True, 8): '>Q',

    # little endian unsigned
    (False, 1): '<B',
    (False, 2): '<H',
    (False, 4): '<I',
    (False, 8): '<Q',
}

signed_fmts = {
    # big endian signed
    (True, 1): '>b',
    (True, 2): '>h',
    (True, 4): '>i',
    (True, 8): '>q',

    # little endian signed
    (False, 1): '<b',
    (False, 2): '<h',
    (False, 4): '<i',
    (False, 8): '<q',
}

class v_number(v_prim):
    _vs_length = 1

    def __init__(self, value=0, bigend=False, enum=None):
        v_prim.__init__(self)
        self._vs_bigend = bigend
        self._vs_enum = enum
        self._vs_length = self.__class__._vs_length
        self._vs_fmt = num_fmts.get((bigend, self._vs_length))

        # TODO: could use envi.bits, but do we really want to dep on envi?
        self.maxval = (2 ** (8 * self._vs_length)) - 1
        self.vsSetValue(value)

    def vsGetValue(self):
        return self._vs_value

    def vsGetEnum(self):
        '''
        Get the v_enum instance used to interpret this number, or None if
          there are no associated enums.
        '''
        return self._vs_enum

    def vsParse(self, fbytes, offset=0):
        '''
        Parse the given numeric type from the given bytes
        '''
        sizeoff = offset + self._vs_length

        if self._vs_fmt is not None:
            b = fbytes[offset:sizeoff]
            self._vs_value = struct.unpack(self._vs_fmt, b)[0]

        else:
            r = []
            for i in range(self._vs_length):
                r.append(fbytes[offset + i])

            if not self._vs_bigend:
                r.reverse()

            self._vs_value = 0
            for x in r:
                self._vs_value = (self._vs_value << 8) + x

        return sizeoff

    def vsEmit(self):
        '''
        Emit the bytes for this numeric type
        '''
        if self._vs_fmt is not None:
            return struct.pack(self._vs_fmt, self._vs_value)

        r = []
        for i in range(self._vs_length):
            r.append((self._vs_value >> (i*8)) & 0xff)

        if self._vs_bigend:
            r.reverse()

        return bytes(r)

    def vsSetValue(self, value):
        self._vs_value = value & self.maxval

    def __int__(self):
        return int(self._vs_value)

    def __str__(self):
        v = self.vsGetValue()
        if self._vs_enum is not None:
            return str(self._vs_enum.vsReverseMapping(v, default=str(v)))
        return str(v)

    ##################################################################
    # Implement the number API
    def __add__(self, other):
        return int(self) + int(other)
    def __sub__(self, other):
        return int(self) - int(other)
    def __mul__(self, other):
        return int(self) * int(other)
    def __div__(self, other):
        return int(self) / int(other)
    def __floordiv__(self, other):
        return int(self) // int(other)

    def __mod__(self, other):
        return int(self) % int(other)
    def __divmod__(self, other):
        return divmod(int(self), int(other))
    def __pow__(self, other, modulo=None):
        return pow(int(self), int(other), modulo)
    def __lshift__(self, other):
        return int(self) << int(other)
    def __rshift__(self, other):
        return int(self) >> int(other)
    def __and__(self, other):
        return int(self) & int(other)
    def __xor__(self, other):
        return int(self) ^ int(other)
    def __or__(self, other):
        return int(self) | int(other)

    def __ge__(self, other):
        return int(self) >= int(other)
    def __le__(self, other):
        return int(self) <= int(other)
    def __gt__(self, other):
        return int(self) > int(other)
    def __lt__(self, other):
        return int(self) < int(other)
    def __eq__(self, other):
        return int(self) == int(other)

    # Operator swapped variants
    def __radd__(self, other): return int(other) + int(self)
    def __rsub__(self, other): return int(other) - int(self)
    def __rmul__(self, other): return int(other) * int(self)
    def __rdiv__(self, other): return int(other) / int(self)
    def __rfloordiv__(self, other): return int(other) // int(self)
    def __rmod__(self, other): return int(other) % int(self)
    def __rdivmod__(self, other): return divmod(int(other), int(self))
    def __rpow__(self, other, modulo=None): return pow(int(other), int(self), modulo)
    def __rlshift__(self, other): return int(other) << int(self)
    def __rrshift__(self, other): return int(other) >> int(self)
    def __rand__(self, other): return int(other) & int(self)
    def __rxor__(self, other): return int(other) ^ int(self)
    def __ror__(self, other): return int(other) | int(self)

    # Inplace variants
    def __iadd__(self, other):
        self.vsSetValue(self+other)
        return self
    def __isub__(self, other):
        self.vsSetValue(self - other)
        return self
    def __imul__(self, other):
        self.vsSetValue(self*other)
        return self
    def __idiv__(self, other):
        self.vsSetValue(self/other)
        return self
    def __ifloordiv__(self, other):
        self.vsSetValue(self // other)
        return self
    def __imod__(self, other):
        self.vsSetValue(self % other)
        return self
    def __ipow__(self, other, modulo=None):
        self.vsSetValue(pow(self, other, modulo))
        return self
    def __ilshift__(self, other):
        self.vsSetValue(self << other)
        return self
    def __irshift__(self, other):
        self.vsSetValue(self >> other)
        return self
    def __iand__(self, other):
        self.vsSetValue(self & other)
        return self
    def __ixor__(self, other):
        self.vsSetValue(self ^ other)
        return self
    def __ior__(self, other):
        self.vsSetValue(self | other)
        return self

    # operator helpers
    def __neg__(self):
        return -(int(self))
    def __pos__(self):
        return +(int(self))
    def __abs__(self):
        return abs(int(self))
    def __invert__(self):
        return ~(int(self))

    # index use helper
    def __index__(self):
        return int(self)

    # Print helpers
    def __hex__(self):
        return hex(int(self))
    def __oct__(self):
        return oct(int(self))

class v_snumber(v_number):
    _vs_length = 1

    def __init__(self, value=0, bigend=False, enum=None):
        smaxval = (2**((8 * self._vs_length)-1)) - 1
        self.smask = smaxval + 1

        v_number.__init__(self, value=value, bigend=bigend, enum=enum)
        self._vs_fmt = signed_fmts.get((bigend, self._vs_length))

    def vsSetValue(self, value):
        value = value & self.maxval
        if value & self.smask:
            value = value - self.maxval - 1

        self._vs_value = int(value)  # TODO

class v_uint8(v_number):
    _vs_builder = True
    _vs_length = 1

class v_uint16(v_number):
    _vs_builder = True
    _vs_length = 2

class v_uint24(v_number):
    _vs_builder = True
    _vs_length = 3

class v_uint32(v_number):
    _vs_builder = True
    _vs_length = 4

class v_uint64(v_number):
    _vs_builder = True
    _vs_length = 8

class v_int8(v_snumber):
    _vs_builder = True
    _vs_length = 1

class v_int16(v_snumber):
    _vs_builder = True
    _vs_length = 2

class v_int24(v_snumber):
    _vs_builder = True
    _vs_length = 3

class v_int32(v_snumber):
    _vs_builder = True
    _vs_length = 4

class v_int64(v_snumber):
    _vs_builder = True
    _vs_length = 8

pointersize = struct.calcsize('P')

class v_size_t(v_number):
    _vs_builder = True
    _vs_length = pointersize

    def __repr__(self):
        return "0x%.8x" % self._vs_value

class v_ptr(v_size_t):
    pass

class v_ptr32(v_ptr):
    _vs_builder = True
    _vs_length = 4

class v_ptr64(v_ptr):
    _vs_builder = True
    _vs_length = 8

float_fmts = {
    (True,4): '>f',
    (True,8): '>d',
    (False,4): '<f',
    (False,8): '<d',
}

class v_float(v_prim):
    _vs_length = 4

    def __init__(self, value=0.0, bigend=False):
        v_prim.__init__(self)
        self._vs_bigend = bigend
        self._vs_value = value
        self._vs_length = self.__class__._vs_length
        self._vs_fmt = float_fmts.get( (bigend, self._vs_length) )

    def vsSetValue(self, value):
        """
        Assure that the value is float() able for all numeric types.
        """
        self._vs_value = float(value)

    def vsGetValue(self):
        return self._vs_value

    def vsParse(self, fbytes, offset=0):
        '''
        Parse the given numeric type from the given bytes
        '''
        sizeoff = offset + self._vs_length

        if self._vs_fmt is not None:
            b = fbytes[ offset : sizeoff ]
            self._vs_value = struct.unpack(self._vs_fmt, b)[0]

        else:
            r = []
            for i in range(self._vs_length):
                r.append( ord( fbytes[ offset + i ] ) )

            if not self._vs_bigend:
                r.reverse()

            self._vs_value = 0
            for x in r:
                self._vs_value = (self._vs_value << 8) + x

        return sizeoff

    def vsEmit(self):
        '''
        Emit the bytes for this numeric type
        '''
        if self._vs_fmt is not None:
            return struct.pack(self._vs_fmt, self._vs_value)

        r = []
        for i in range(self._vs_length):
            r.append( chr( (self._vs_value >> (i*8)) & 0xff) )

        if self._vs_bigend:
            r.reverse()

        return b''.join(r)

    def __int__(self):
        return int(self._vs_value)
    def __float__(self):
        return float(self._vs_value)

    def __add__(self, other): return float(self) + float(other)
    def __sub__(self, other): return float(self) - float(other)
    def __mul__(self, other): return float(self) * float(other)
    def __div__(self, other): return float(self) / float(other)
    def __floordiv__(self, other): return float(self) // float(other)
    def __mod__(self, other): return float(self) % float(other)
    def __divmod__(self, other): return divmod(float(self), float(other))
    def __pow__(self, other, modulo=None): return pow(float(self), float(other), modulo)
    def __lshift__(self, other): return float(self) << float(other)
    def __rshift__(self, other): return float(self) >> float(other)
    def __and__(self, other): return float(self) & float(other)
    def __xor__(self, other): return float(self) ^ float(other)
    def __or__(self, other): return float(self) | float(other)

    # Operator swapped variants
    def __radd__(self, other): return float(other) + float(self)
    def __rsub__(self, other): return float(other) - float(self)
    def __rmul__(self, other): return float(other) * float(self)
    def __rdiv__(self, other): return float(other) / float(self)
    def __rfloordiv__(self, other): return float(other) // float(self)
    def __rmod__(self, other): return float(other) % float(self)
    def __rdivmod__(self, other): return divmod(float(other), float(self))
    def __rpow__(self, other, modulo=None): return pow(float(other), float(self), modulo)
    def __rlshift__(self, other): return float(other) << float(self)
    def __rrshift__(self, other): return float(other) >> float(self)
    def __rand__(self, other): return float(other) & float(self)
    def __rxor__(self, other): return float(other) ^ float(self)
    def __ror__(self, other): return float(other) | float(self)

    # Inplace variants
    def __iadd__(self, other): self.vsSetValue(self+other); return self
    def __isub__(self, other): self.vsSetValue(self - other); return self
    def __imul__(self, other): self.vsSetValue(self*other); return self
    def __idiv__(self, other): self.vsSetValue(self/other); return self
    def __ifloordiv__(self, other): self.vsSetValue(self // other); return self
    def __imod__(self, other): self.vsSetValue(self % other); return self
    def __ipow__(self, other, modulo=None): self.vsSetValue(pow(self, other, modulo)); return self
    def __ilshift__(self, other): self.vsSetValue(self << other); return self
    def __irshift__(self, other): self.vsSetValue(self >> other); return self
    def __iand__(self, other): self.vsSetValue(self & other); return self
    def __ixor__(self, other): self.vsSetValue(self ^ other); return self
    def __ior__(self, other): self.vsSetValue(self | other); return self

    # operator helpers
    def __neg__(self): return -(float(self))
    def __pos__(self): return +(float(self))
    def __abs__(self): return abs(float(self))
    def __invert__(self): return ~(float(self))

    # index use helper
    def __index__(self): return float(self)

    # Print helpers
    def __hex__(self): return hex(float(self))
    def __oct__(self): return oct(float(self))

class v_double(v_float):
    _vs_length = 8

class v_bytes(v_prim):

    '''
    v_bytes is used for fixed width byte fields.
    '''

    _vs_builder = True

    def __init__(self, size=0, vbytes=None):
        v_prim.__init__(self)
        if vbytes is None:
            vbytes = b'\x00' * size
        self._vs_length = len(vbytes)
        self._vs_value = vbytes
        self._vs_align = 1
        self._vs_fmt = '%ds' % self._vs_length

    def vsSetValue(self, val):
        if len(val) != self._vs_length:
            raise Exception('v_bytes field set to wrong length!')
        self._vs_value = val

    def vsParse(self, fbytes, offset=0):
        offend = offset + self._vs_length
        self._vs_value = fbytes[offset : offend]
        return offend

    def vsEmit(self):
        return self._vs_value

    def vsSetLength(self, size):
        size = int(size)
        self._vs_length = size
        self._vs_fmt = '%ds' % size
        # Either chop or expand my string...
        b = self._vs_value[:size]
        self._vs_value = b.ljust(size, b'\x00')

    def __repr__(self):
        return binascii.hexlify(self._vs_value).decode('utf-8')

class v_str(v_prim):
    '''
    A string placeholder class which will automagically return
    up to a null terminator (and will keep it's size by null
    padding when assigned to)
    '''

    _vs_builder = True

    def __init__(self, size=4, val=b''):
        v_prim.__init__(self)
        self._vs_length = size
        self._vs_fmt = '%ds' % size
        self._vs_value = val.ljust(size, b'\x00')
        self._vs_align = 1

    def vsParse(self, fbytes, offset=0):
        offend = offset + self._vs_length
        self._vs_value = fbytes[offset : offend]
        return offend

    def vsEmit(self):
        return self._vs_value

    def vsGetValue(self):
        s = self._vs_value.split(b'\x00')[0].decode('utf-8')
        return s

    def vsSetValue(self, val):
        if type(val) is str:
            val = val.encode('utf-8')
        self._vs_value = val.ljust(self._vs_length, b'\x00')

    def vsSetLength(self, size):
        size = int(size)
        self._vs_length = size
        self._vs_fmt = '%ds' % size
        # Either chop or expand my string...
        b = self._vs_value[:size]
        self._vs_value = b.ljust(size, b'\x00')

class v_zstr(v_prim):
    '''
    A string placeholder class which will automagically return
    up to a null terminator dynamically.
    '''

    _vs_builder = True

    def __init__(self, val=b'', align=1):
        v_prim.__init__(self)
        self._vs_align = align
        self.vsParse(val + b'\x00')

    def vsParse(self, fbytes, offset=0):
        nulloff = fbytes.find(b'\x00', offset)
        if nulloff == -1:
            raise Exception('v_zstr found no NULL terminator!')

        # align things correctly
        diff = self._vs_align - ((nulloff-offset) % self._vs_align)
        self._vs_align_pad = diff
        nulloff += diff

        self._vs_value = fbytes[offset : nulloff]
        self._vs_length = len(self._vs_value)
        return nulloff

    def vsParseFd(self, fd):
        ret = b''
        while not ret.endswith(b'\x00'):
            y = fd.read(1)
            if not y:
                raise Exception('v_zstr file ended before NULL')
            ret += y
        return self.vsParse(ret)

    def vsEmit(self):
        return self._vs_value

    def vsGetValue(self):
        return self._vs_value[:-self._vs_align_pad].decode('utf-8')

    def vsSetValue(self, val):
        # FIXME: just call vsParse?
        length = len(val)
        diff = self._vs_align - (length % self._vs_align)
        self._vs_value = val + b'\x00'*(diff)
        self._vs_length = len(self._vs_value)
        self._vs_align_pad = diff

    def vsSetLength(self, size):
        raise Exception('Cannot vsSetLength on v_zstr! (its dynamic)')

class v_wstr(v_str):
    '''
    Unicode variant of the above string class

    NOTE: the size paramater is in WCHARs!
    '''

    _vs_builder = True

    def __init__(self, size=4, encode='utf-16le', val=b''):
        v_str.__init__(self)
        b = val.ljust(size, b'\x00')
        self._vs_length = len(b)
        self._vs_value = b
        self._vs_encode = encode
        self._vs_align = 2

    def vsParse(self, fbytes, offset=0):
        offend = offset + self._vs_length
        self._vs_value = fbytes[offset : offend]
        return offend

    def vsEmit(self):
        return self._vs_value

    def vsSetValue(self, val):
        rbytes = val.encode(self._vs_encode)
        self._vs_value = rbytes.ljust(len(self), b'\x00')

    def vsGetValue(self):
        s = self._vs_value.decode(self._vs_encode, errors='replace')
        return s.split("\x00")[0]

class v_zwstr(v_str):
    '''
    Unicode variant of the above zstring class
    '''

    _vs_builder = True

    def __init__(self, encode='utf-16le', val=b'', align=2):
        v_str.__init__(self)
        self._vs_encode = encode
        self._vs_align = align
        self.vsParse(val + b'\x00\x00')

    def vsParse(self, fbytes, offset=0):
        nulloff = offset
        while nulloff < len(fbytes):
            nulloff = fbytes.find(b'\x00\x00', nulloff)
            if nulloff == -1:
                raise Exception('v_wzstr found no NULL terminator!')
            #make sure that this is acutally the null word by checking if
            # the alignment is correct
            if ((nulloff-offset) % self._vs_align) == 0:
                #yes, found it
                break
            #advance nulloff by 1 & keep looking
            nulloff += 1

        # align things correctly
        diff = self._vs_align - ((nulloff-offset) % self._vs_align)
        self._vs_align_pad = diff
        nulloff += diff

        self._vs_value = fbytes[offset : nulloff]
        self._vs_length = len(self._vs_value)
        return nulloff

        #offend = offset + self._vs_length
        #self._vs_value = fbytes[offset : offend]
        #return offend

    def vsEmit(self):
        return self._vs_value

    def vsGetValue(self):
        cstr = self._vs_value.decode(self._vs_encode, errors='replace')
        return cstr.split('\x00')[0]

    def vsSetValue(self, val):
        #rbytes = val.encode(self._vs_encode)
        #self._vs_value = rbytes.ljust(len(self), '\x00')

        # FIXME: just call vsParse?
        rbytes = val.encode(self._vs_encode)
        length = len(rbytes)
        diff = self._vs_align - (length % self._vs_align)
        self._vs_value = rbytes + b'\x00' * (diff)
        self._vs_value = rbytes.ljust(len(self), b'\x00')
        self._vs_length = len(self._vs_value)
        self._vs_align_pad = diff

    def vsSetLength(self, size):
        raise Exception('Cannot vsSetLength on v_zwstr! (its dynamic)')

class GUID(v_prim):

    _vs_builder = True

    def __init__(self, guidstr=None):
        """
        Construct a new GUID primitive.  You may specify a GUID string in the
        constructor to populate initial values.
        """
        v_prim.__init__(self)
        self._vs_length = 16
        self._vs_value = '\x00' * 16
        self._vs_fmt = '16s'
        self._guid_fields = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        if guidstr is not None:
            self._parseGuidStr(guidstr)

    def vsParse(self, fbytes, offset=0):
        offend = offset + self._vs_length
        self._guid_fields = struct.unpack("<IHH8B", fbytes[offset:offend])
        return offend

    def vsEmit(self):
        return struct.pack("<IHH8B", *self._guid_fields)

    def _parseGuidStr(self, gstr):
        gstr = gstr.replace('{', '')
        gstr = gstr.replace('}', '')
        gstr = gstr.replace('-', '')
        bytes = binascii.unhexlify(gstr)
        # Totally cheating... ;)
        self._guid_fields = struct.unpack('>IHH8B', bytes)

    def vsSetValue(self, guidstr):
        self._parseGuidStr(guidstr)

    def vsGetValue(self):
        return repr(self)

    def __repr__(self):
        base = "{%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x}"
        return base  % self._guid_fields


text:
@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIView *layerView;
@property (nonatomic, strong) IBOutlet CALayer *colorLayer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //create sublayer
    self.colorLayer = [CALayer layer];
    self.colorLayer.frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f);
    self.colorLayer.backgroundColor = [UIColor blueColor].CGColor;

    //add it to our view
    [self.layerView.layer addSublayer:self.colorLayer];
}

- (IBAction)changeColor
{
    //create a new random color
    CGFloat red = arc4random() / (CGFloat)INT_MAX;
    CGFloat green = arc4random() / (CGFloat)INT_MAX;
    CGFloat blue = arc4random() / (CGFloat)INT_MAX;
    UIColor *color = [UIColor colorWithRed:red
                                     green:green
                                      blue:blue
                                     alpha:1.0];

    //create a basic animation
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"backgroundColor";
    animation.toValue = (__bridge id)color.CGColor;

    //uncomment the two lines below to solve the snap-back problem
    //animation.fromValue = (__bridge id)self.colorLayer.backgroundColor;
    //self.colorLayer.backgroundColor = color.CGColor;

    //apply animation to layer
    [self.colorLayer addAnimation:animation forKey:nil];
}

@end

redpajama_set_name: RedPajamaGithub


text:
require "rubinius-docs/version"

module Rubinius
  module Docs
    # Your code goes here...
  end
end


text:
class TeamsController < ApplicationController
  def index
    @teams = current_user.teams
  end

  def create
  end

  def display_team
    @team = Team.find(params[:team_id])
    if @team.founder.eql?(current_user) || @team.user_is_member(current_user)

    else
      # unauthorized
    end
  end

  def save_new_team
    @new_team = Team.new
    @new_team.user = current_user
    @new_team.name = params[:team_name]
    @new_team.description = params[:team_description]
    @new_team.save!
  end
end


text:
package de.bitdroid.flooding.auth;

import android.accounts.Account;

import com.google.android.gms.auth.GoogleAuthException;

import org.roboguice.shaded.goole.common.base.Optional;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import retrofit.client.Header;
import retrofit.client.Request;
import retrofit.client.Response;
import retrofit.client.UrlConnectionClient;

/**
 * A retrofit {@link UrlConnectionClient} which signs outgoing
 * requests with access token.
 */
public class AuthClient extends UrlConnectionClient {

	private final LoginManager loginManager;

	@Inject
	AuthClient(LoginManager loginManager) {
		this.loginManager = loginManager;
	}

	@Override
	public Response execute(Request request) throws IOException {
		try {
			List<Header> headers = new LinkedList<Header>(request.getHeaders());

			// if logged in add auth header
			Optional<Account> account = loginManager.getAccount();
			if (account.isPresent()) {
				String token = loginManager.getToken(account.get());
				Header authHeader = new Header("Authorization", "Bearer " + token);
				headers.add(authHeader);
			}

			Request signedRequest = new Request(
					request.getMethod(),
					request.getUrl(),
					headers,
					request.getBody());

			return super.execute(signedRequest);

		} catch (GoogleAuthException gae) {
			throw new IOException(gae);
		}
	}

}


text:
require 'socket'
require 'fastbeans/request'

module Fastbeans
  class Connection
    MAX_RETRIES=3

    attr_reader :socket

    def initialize(host, port)
      Fastbeans.debug("Connecting to #{host}:#{port}")
      @host, @port = host, port
      begin
        @socket = connect!(@host, @port)
      rescue => e
        Fastbeans.error(e)
        raise RemoteConnectionDead, e.message
      end
    end

    def connect!(host, port)
      @socket = TCPSocket.new(host, port)
      @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
      @socket
    end

    def get_socket
      @socket || connect!(@host, @port)
    end

    def disconnect!
      if @socket
        @socket.close rescue nil
        @socket = nil
      end
    end

    def reconnect!
      disconnect!
      connect!(@host, @port)
    end

    def call(data, opts)
      retries = 0
      begin
        call_without_retries(data, opts)
      rescue Fastbeans::RemoteConnectionFailed, Fastbeans::ResponseReadTimeout => e
        Fastbeans.debug(e)
        if retries < MAX_RETRIES
          Fastbeans.debug("Retrying (#{retries} out of #{MAX_RETRIES} retries)")
          retries += 1
          begin
            reconnect!
          rescue => e
            raise RemoteConnectionDead, e.message
          end
          retry
        else
          raise RemoteConnectionDead, "#{e.message} (#{retries} retries)"
        end
      end
    end

    def call_without_retries(data, opts)
      perform(data, opts)

    rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ECONNRESET, MessagePack::MalformedFormatError => e
      disconnect!
      ne = RemoteConnectionFailed.new(e.message)
      ne.orig_exc = e
      raise ne

    rescue Exception
      disconnect!
      raise
    end

    def with_socket
      yield(get_socket)
    rescue Exception => anything
      disconnect!
      raise
    end

    def perform(data, opts)
      Request.new(self, opts).perform(data)
    end
  end
end


text:
<?php

namespace Concrete\Tests\Utility\Service;

use Concrete\TestHelpers\Database\ConcreteDatabaseTestCase;
use Core;

class TextTest extends ConcreteDatabaseTestCase
{
    /**
     * @var TextHelper
     */
    protected $object;

    protected $fixtures = [];
    protected $tables = ['ConfigStore'];

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->object = new \Concrete\Core\Utility\Service\Text();
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    public function tearDown()
    {
        unset($this->object);
        parent::tearDown();
    }

    public function asciifyDataProvider()
    {
        return [
            ['Mixed with English and Germaen', 'Mixed with English and Germän', 'de_DE'],
            ['Mixed with English and ', 'Mixed with English and 日本人', ''],
            ['Mixed with English and .doc', 'Mixed with English and 日本人.doc', ''],
            ['Mixed with English and .', 'Mixed with English and 日本人.日本人', ''],
            ['', '日本人', ''],
            ['.doc', '日本人.doc', ''],
            ['.', '日本人.日本人', ''],
        ];
    }

    public function urlifyDataProvider()
    {
        return [
            ['jetudie-le-francais', " J'étudie le français "],
            ['lo-siento-no-hablo-espanol', 'Lo siento, no hablo español.'],
            ['f3pws', 'ΦΞΠΏΣ'],
            ['yo-hablo-espanol', '¿Yo hablo español?'],
        ];
    }

    public function shortenDataProvider()
    {
        return [
            ['This is a simple test...', 'This is a simple test case', 24, '...'],
            ['This is a simple test etc', 'This is a simple test case', 22, ' etc'],
            ['This is a simple test.', 'This is a simple test case', 21, '.'],
            ['The quick brown fox jumps over the lazy dog', 'The quick brown fox jumps over the lazy dog', 255, '…'],
            ['The lazy fox jumps over the quick brown dog', 'The lazy fox jumps over the quick brown dog', 0, '…'],
            ['This_is_a_simple_test_ca…', 'This_is_a_simple_test_case', 24, '…'],
        ];
    }

    public function testTextHelper()
    {
        $this->assertInstanceOf('\Concrete\Core\Utility\Service\Text', Core::make('helper/text'));
    }

    /**
     * @dataProvider asciifyDataProvider
     *
     * @param mixed $expected
     * @param mixed $input1
     * @param mixed $input2
     */
    public function testAsciify($expected, $input1, $input2)
    {
        $this->assertEquals($expected, $this->object->asciify($input1, $input2));
    }

    /**
     * @dataProvider urlifyDataProvider
     *
     * @param mixed $expected
     * @param mixed $input
     */
    public function testUrlify($expected, $input)
    {
        $this->assertEquals($expected, $this->object->urlify($input));
    }

    /**
     * Test for many rounds with a language, that has no map associated
     * This causes a "regular expression is too large" error on old versions.
     */
    public function testUrlify_regexTooLarge()
    {
        for ($i = 0; $i < 1000; ++$i) {
            $this->object->urlify('Lo siento, no hablo español.', 60, -1);
        }
    }

    /**
     * @dataProvider shortenDataProvider
     *
     * @param mixed $expected
     * @param mixed $input1
     * @param mixed $input2
     * @param mixed $input3
     */
    public function testShortenTextWord($expected, $input1, $input2, $input3)
    {
        $this->assertEquals($expected, $this->object->shortenTextWord($input1, $input2, $input3));
    }

    /**
     * @dataProvider shortenDataProvider
     *
     * @param mixed $expected
     * @param mixed $input1
     * @param mixed $input2
     * @param mixed $input3
     */
    public function testWordSafeShortText($expected, $input1, $input2, $input3)
    {
        $this->assertEquals($expected, $this->object->wordSafeShortText($input1, $input2, $input3));
    }

    public function autolinkDataProvider()
    {
        return [
            ['', ''],
            ['This is not a link', 'This is not a link'],
            ['www.concrete5.org', 'www.concrete5.org'],
            ['www.concrete5.org', 'www.concrete5.org', true],
            ['Before www.concrete5.org after', 'Before www.concrete5.org after'],
            ['concrete5.org', 'http://concrete5.org'],
            ['concrete5.org', 'https://concrete5.org'],
            ['Before concrete5.org after', 'Before http://concrete5.org after'],
            ['Before concrete5.org after', 'Before https://concrete5.org after'],
            ['concrete5.org concrete5.org', 'http://concrete5.org https://concrete5.org'],
            ['www.concrete5.org concrete5.org', 'www.concrete5.org https://concrete5.org'],
            ['www.concrete5.org', 'www.concrete5.org', false, 'https://'],
        ];
    }

    /**
     * @dataProvider autolinkDataProvider
     *
     * @param mixed $expected
     * @param mixed $input
     * @param mixed $newWindow
     * @param mixed $defaultProtocol
     */
    public function testAutolink($expected, $input, $newWindow = false, $defaultProtocol = 'http://')
    {
        $this->assertSame($expected, $this->object->autolink($input, $newWindow, $defaultProtocol));
    }
}


text:
[![Build Status](https://travis-ci.org/justsocialapps/just-sdk.svg?branch=master)](https://travis-ci.org/justsocialapps/just-sdk)

This is an SDK to talk to the [Just Connect](http://just.social) REST API from
Node.js and web applications. It supports OAuth2 authorization with the
Implicit, Authorization Code and Credentials grants.

Details on the API can be found [here](https://cloud.just.social/toro/swagger-ui/).

## Prerequisites

[Node.js >= 14](https://nodejs.org/)

## Installing

### Node.js

The preferred way to install the SDK is via the npm package manager. Type this
into your terminal:

```sh
npm install just-sdk
```

### Browser

For using the SDK in your web application, clone this repo, call `npm install`
followed by `grunt dist` and copy the resulting file from the `dist/` directory
to your web server.

## First Steps

The simplest way to try out this SDK is to fire it up in a Node.js application
with the OAuth2 credentials grant, i.e. you authenticate with your username and
password. Simply require the library, configure it with a domain, flow, username
and password and then call its functions.

Here is a simple example:

```javascript
var SDK = require('just-sdk');
var sdk = new SDK({
    domain: "just.loveyourintranet.com",
    oauth2: {
        flow: "credentials",
        username: "yourmail@example.org",
        password: "yourpassword",
        client_id: "your_client_id",
        client_secret: "your_client_secret"
    }
});
sdk.oauth2.token()
    .then(sdk.user.me.bind(sdk.user))
    .then(function(me) {
        console.log("You are using the API as " + me.name);
    })
    .catch(function(error) {
        console.log("There was an error fetching your profile information: " + error.message);
    });
```

The [examples](examples/) directory holds more examples to get you started.

## Configuration

The SDK is configured by passing a config object to the constructor:

|Key|Description|Type|
|-------|------|-------|
|`domain`|The Just domain you would like to talk to.|string|
|`oauth2`|An object containing the OAuth2-specific configuration. See below for details.|object|

For the different OAuth2 grant types, the `oauth2` object holds different
values:

### Implicit Grant Flow

|Key|Description|Type|
|-------|------|-------|
|`oauth2.flow`|Set this to `implicit`.|string|
|`oauth2.redirect_uri`|The URI to redirect the user to after he has authenticated the application.|string|
|`oauth2.client_id`|The client ID of your application.|string|

### Credentials Grant Flow (Username/Password)

|Key|Description|Type|
|-------|------|-------|
|`oauth2.flow`|Set this to `credentials`.|string|
|`oauth2.username`|The username for authenticating towards Just.|string|
|`oauth2.password`|The password for authenticating towards Just.|string|
|`oauth2.client_id`|The client ID of your application.|string|
|`oauth2.client_secret`|The client secret of your application.|string|

### Authorization Code Grant Flow

|Key|Description|Type|
|-------|------|-------|
|`oauth2.flow`|Set this to `authorization_code`.|string|
|`oauth2.client_id`|The client ID of your application.|string|
|`oauth2.client_secret`|The client secret of your application.|string|
|`oauth2.redirect_uri`|The URI of your application that receives the authorization code.|string|

License
===

This SDK is distributed under the BSD 2-Clause License, see [LICENSE](LICENSE) for more information.


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="vertical"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:background="@color/accent"
        >

    <GridView
            android:background="@android:color/white"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:numColumns="5"
            android:padding="1dp"
            android:id="@+id/character_list"
            android:stretchMode="columnWidth"
            android:horizontalSpacing="1dp"
            android:verticalSpacing="1dp"
            android:scrollbars="none"
            />

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/shadow"
            android:textColor="@color/primary_dark"
            android:textIsSelectable="false"
            android:textSize="@dimen/character_title"
            android:text=""
            android:maxLines="1"
            android:gravity="center"
            />
</FrameLayout>


text:
<?php
namespace Concrete\Core\User\Point;

use Loader;
use \Concrete\Core\User\UserInfo;
use \Concrete\Core\User\Point\Action\Action as UserPointAction;

class Entry
{

    public $upID;
    public $upuID;
    public $upaID = 0;
    public $upPoints;
    public $timestamp;

    public function load($upID)
    {
        $db = Loader::db();
        $row = $db->GetRow('select * from UserPointHistory where upID = ?', array($upID));
        if (is_array($row) && $row['upID']) {
            $this->upID = $row['upID'];
            $this->upuID = $row['upuID'];
            $this->upaID = $row['upaID'];
            $this->object = $row['object'];
            $this->upPoints = $row['upPoints'];
            $this->timestamp = $row['timestamp'];
        }
    }

    public function save()
    {
        $db = Loader::db();
        if ($this->upID) {
            $db->update('UserPointHistory', array(
                'upID' => $this->upID,
                'upuID' => $this->upuID,
                'upaID' => $this->upaID,
                'object' => $this->object,
                'upPoints' => $this->upPoints,
                'timestamp' => date('Y-m-d H:i:s')
            ), array('upID' => $this->upID));
        } else {
            $db->insert('UserPointHistory', array(
                'upID' => $this->upID,
                'upuID' => $this->upuID,
                'object' => $this->object,
                'upaID' => $this->upaID,
                'upPoints' => $this->upPoints,
                'timestamp' => date('Y-m-d H:i:s')
            ));
        }
    }

    public function delete()
    {
        $db = Loader::db();
        $db->delete('UserPointHistory', array('upID' => $this->upID));
    }

    public function    getUserPointEntryID()
    {
        return $this->upID;
    }

    public function    getUserPointEntryActionID()
    {
        return $this->upaID;
    }

    public function    getUserPointEntryActionObject()
    {
        return UserPointAction::getByID($this->getUserPointEntryActionID());
    }

    public function    getUserPointEntryValue()
    {
        return $this->upPoints;
    }

    public function    getUserPointEntryTimestamp()
    {
        return $this->timestamp;
    } // - returns unix timestamp stored in the timestamp column

    public function    getUserPointEntryDateTime()
    {
        return $this->timestamp;
    } // - returns it in a nicely formatted way

    public function getUserPointEntryUserID()
    {
        return $this->upuID;
    }

    public function getUserPointEntryDescriptionObject()
    {
        return unserialize($this->object);
    }

    public function getUserPointEntryDescription()
    {
        if ($this->object) {
            $obj = unserialize($this->object);
            return $obj->getUserPointActionDescription();
        }
    }

    public function getUserPointEntryUserObject()
    {
        $ui = UserInfo::getByID($this->upuID);
        return $ui;
    }

    public static function getTotal($ui)
    {
        $db = Loader::db();
        $cnt = $db->GetOne('select sum(upPoints) as total from UserPointHistory where upuID = ?',
            array($ui->getUserID()));
        return $cnt;
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <parameters>
        <parameter key="fungio_google_map.kml_layer.class">Fungio\GoogleMap\Layers\KMLLayer</parameter>
        <parameter key="fungio_google_map.kml_layer.builder.class">Fungio\GoogleMapBundle\Model\Layers\KMLLayerBuilder</parameter>
        <parameter key="fungio_google_map.kml_layer.helper.class">Fungio\GoogleMap\Helper\Layers\KMLLayerHelper</parameter>
    </parameters>

    <services>
        <!-- KML Layer service -->
        <service
            id="fungio_google_map.kml_layer"
            class="%fungio_google_map.kml_layer.class%"
            shared="false">
            <factory service="fungio_google_map.kml_layer.builder" method="build" />
        </service>

        <service id="fungio_google_map.kml_layer.builder" class="%fungio_google_map.kml_layer.builder.class%">
            <argument>%fungio_google_map.kml_layer.class%</argument>
        </service>

        <service
            id="fungio_google_map.helper.kml_layer"
            class="%fungio_google_map.kml_layer.helper.class%"
            public="false"
        />
    </services>
</container>


text:
"use strict";

const expect = require("chai").expect;
const Chan = require("../../src/models/chan");
const Msg = require("../../src/models/msg");
const User = require("../../src/models/user");

describe("Chan", function() {
	const network = {
		network: {
			options: {
				PREFIX: [
					{symbol: "~", mode: "q"},
					{symbol: "&", mode: "a"},
					{symbol: "@", mode: "o"},
					{symbol: "%", mode: "h"},
					{symbol: "+", mode: "v"},
				],
			},
		},
	};

	const prefixLookup = {};

	network.network.options.PREFIX.forEach((mode) => {
		prefixLookup[mode.mode] = mode.symbol;
	});

	describe("#findMessage(id)", function() {
		const chan = new Chan({
			messages: [
				new Msg({id: 1}),
				new Msg({
					id: 2,
					text: "Message to be found",
				}),
				new Msg(),
			],
		});

		it("should find a message in the list of messages", function() {
			expect(chan.findMessage(2).text).to.equal("Message to be found");
		});

		it("should not find a message that does not exist", function() {
			expect(chan.findMessage(42)).to.be.undefined;
		});
	});

	describe("#setUser(user)", function() {
		it("should make key lowercase", function() {
			const chan = new Chan();
			chan.setUser(new User({nick: "TestUser"}));

			expect(chan.users.has("testuser")).to.be.true;
		});

		it("should update user object", function() {
			const chan = new Chan();
			chan.setUser(new User({nick: "TestUser"}, prefixLookup));
			chan.setUser(new User({nick: "TestUseR", modes: ["o"]}, prefixLookup));
			const user = chan.getUser("TestUSER");

			expect(user.mode).to.equal("@");
		});
	});

	describe("#getUser(nick)", function() {
		it("should returning existing object", function() {
			const chan = new Chan();
			chan.setUser(new User({nick: "TestUseR", modes: ["o"]}, prefixLookup));
			const user = chan.getUser("TestUSER");

			expect(user.mode).to.equal("@");
		});

		it("should make new User object if not found", function() {
			const chan = new Chan();
			const user = chan.getUser("very-testy-user");

			expect(user.nick).to.equal("very-testy-user");
		});
	});

	describe("#getSortedUsers(irc)", function() {
		const getUserNames = function(chan) {
			return chan.getSortedUsers(network).map((u) => u.nick);
		};

		it("returns unsorted list on null irc object", function() {
			const chan = new Chan();
			[
				"JocelynD", "YaManicKill", "astorije", "xPaw", "Max-P",
			].forEach((nick) => chan.setUser(new User({nick})));

			expect(chan.getSortedUsers().map((u) => u.nick)).to.deep.equal([
				"JocelynD", "YaManicKill", "astorije", "xPaw", "Max-P",
			]);
		});

		it("should sort a simple user list", function() {
			const chan = new Chan();
			[
				"JocelynD", "YaManicKill", "astorije", "xPaw", "Max-P",
			].forEach((nick) => chan.setUser(new User({nick}, prefixLookup)));

			expect(getUserNames(chan)).to.deep.equal([
				"astorije", "JocelynD", "Max-P", "xPaw", "YaManicKill",
			]);
		});

		it("should group users by modes", function() {
			const chan = new Chan();
			chan.setUser(new User({nick: "JocelynD", modes: ["a", "o"]}, prefixLookup));
			chan.setUser(new User({nick: "YaManicKill", modes: ["v"]}, prefixLookup));
			chan.setUser(new User({nick: "astorije", modes: ["h"]}, prefixLookup));
			chan.setUser(new User({nick: "xPaw", modes: ["q"]}, prefixLookup));
			chan.setUser(new User({nick: "Max-P", modes: ["o"]}, prefixLookup));

			expect(getUserNames(chan)).to.deep.equal([
				"xPaw", "JocelynD", "Max-P", "astorije", "YaManicKill",
			]);
		});

		it("should sort a mix of users and modes", function() {
			const chan = new Chan();
			chan.setUser(new User({nick: "JocelynD"}, prefixLookup));
			chan.setUser(new User({nick: "YaManicKill", modes: ["o"]}, prefixLookup));
			chan.setUser(new User({nick: "astorije"}, prefixLookup));
			chan.setUser(new User({nick: "xPaw"}, prefixLookup));
			chan.setUser(new User({nick: "Max-P", modes: ["o"]}, prefixLookup));

			expect(getUserNames(chan)).to.deep.equal(
				["Max-P", "YaManicKill", "astorije", "JocelynD", "xPaw"]
			);
		});

		it("should be case-insensitive", function() {
			const chan = new Chan();
			[
				"aB", "Ad", "AA", "ac",
			].forEach((nick) => chan.setUser(new User({nick}, prefixLookup)));

			expect(getUserNames(chan)).to.deep.equal(["AA", "aB", "ac", "Ad"]);
		});

		it("should parse special characters successfully", function() {
			const chan = new Chan();
			[
				"[foo", "]foo", "(foo)", "{foo}", "<foo>", "_foo", "@foo", "^foo",
				"&foo", "!foo", "+foo", "Foo",
			].forEach((nick) => chan.setUser(new User({nick}, prefixLookup)));

			expect(getUserNames(chan)).to.deep.equal([
				"!foo", "&foo", "(foo)", "+foo", "<foo>", "@foo", "[foo", "]foo",
				"^foo", "_foo", "Foo", "{foo}",
			]);
		});
	});

	describe("#getFilteredClone(lastActiveChannel, lastMessage)", function() {
		it("should send empty user list", function() {
			const chan = new Chan();
			chan.setUser(new User({nick: "test"}));

			expect(chan.getFilteredClone().users).to.be.empty;
		});

		it("should keep necessary properties", function() {
			const chan = new Chan();

			expect(chan.getFilteredClone()).to.be.an("object").that.has.all.keys(
				"firstUnread",
				"highlight",
				"id",
				"key",
				"messages",
				"name",
				"state",
				"topic",
				"type",
				"unread",
				"users"
			);
		});

		it("should send only last message for non active channel", function() {
			const chan = new Chan({
				id: 1337,
				messages: [
					new Msg({id: 10}),
					new Msg({id: 11}),
					new Msg({id: 12}),
					new Msg({id: 13}),
				],
			});

			expect(chan.id).to.equal(1337);

			const messages = chan.getFilteredClone(999).messages;

			expect(messages).to.have.lengthOf(1);
			expect(messages[0].id).to.equal(13);
		});

		it("should send more messages for active channel", function() {
			const chan = new Chan({
				id: 1337,
				messages: [
					new Msg({id: 10}),
					new Msg({id: 11}),
					new Msg({id: 12}),
					new Msg({id: 13}),
				],
			});

			expect(chan.id).to.equal(1337);

			const messages = chan.getFilteredClone(1337).messages;

			expect(messages).to.have.lengthOf(4);
			expect(messages[0].id).to.equal(10);
			expect(messages[3].id).to.equal(13);

			expect(chan.getFilteredClone(true).messages).to.have.lengthOf(4);
		});

		it("should only send new messages", function() {
			const chan = new Chan({
				id: 1337,
				messages: [
					new Msg({id: 10}),
					new Msg({id: 11}),
					new Msg({id: 12}),
					new Msg({id: 13}),
					new Msg({id: 14}),
					new Msg({id: 15}),
				],
			});

			expect(chan.id).to.equal(1337);

			const messages = chan.getFilteredClone(1337, 12).messages;

			expect(messages).to.have.lengthOf(3);
			expect(messages[0].id).to.equal(13);
			expect(messages[2].id).to.equal(15);
		});
	});
});