text:
from array import array
from errno import EEXIST
from itertools import islice, izip
from math import ceil
from os import mkdir
from os.path import basename, abspath, dirname, exists, join as pathjoin
from sys import argv as sys_argv, exit, stderr
from textwrap import wrap
from time import time

from swift.common import exceptions
from swift.common.ring import RingBuilder, Ring
from swift.common.ring.builder import MAX_BALANCE
from swift.common.utils import lock_parent_directory
from swift.common.ring.utils import parse_search_value, parse_args, \
    build_dev_from_opts, parse_builder_ring_filename_args

MAJOR_VERSION = 1
MINOR_VERSION = 3
EXIT_SUCCESS = 0
EXIT_WARNING = 1
EXIT_ERROR = 2

global argv, backup_dir, builder, builder_file, ring_file
argv = backup_dir = builder = builder_file = ring_file = None

def format_device(dev):
    """
    Format a device for display.
    """
    copy_dev = dev.copy()
    for key in ('ip', 'replication_ip'):
        if ':' in copy_dev[key]:
            copy_dev[key] = '[' + copy_dev[key] + ']'
    return ('d%(id)sr%(region)sz%(zone)s-%(ip)s:%(port)sR'
            '%(replication_ip)s:%(replication_port)s/%(device)s_'
            '"%(meta)s"' % copy_dev)

def _parse_add_values(argvish):
    """
    Parse devices to add as specified on the command line.

    Will exit on error and spew warnings.

    :returns: array of device dicts
    """

    opts, args = parse_args(argvish)

    # We'll either parse the all-in-one-string format or the --options format,
    # but not both. If both are specified, raise an error.
    opts_used = opts.region or opts.zone or opts.ip or opts.port or \
        opts.device or opts.weight or opts.meta

    if len(args) > 0 and opts_used:
        print Commands.add.__doc__.strip()
        exit(EXIT_ERROR)
    elif len(args) > 0:
        if len(args) % 2 != 0:
            print Commands.add.__doc__.strip()
            exit(EXIT_ERROR)

        parsed_devs = []
        devs_and_weights = izip(islice(args, 0, len(args), 2),
                                islice(args, 1, len(args), 2))

        for devstr, weightstr in devs_and_weights:
            region = 1
            rest = devstr
            if devstr.startswith('r'):
                i = 1
                while i < len(devstr) and devstr[i].isdigit():
                    i += 1
                region = int(devstr[1:i])
                rest = devstr[i:]
            else:
                stderr.write("WARNING: No region specified for %s. "
                             "Defaulting to region 1.\n" % devstr)

            if not rest.startswith('z'):
                print 'Invalid add value: %s' % devstr
                exit(EXIT_ERROR)
            i = 1
            while i < len(rest) and rest[i].isdigit():
                i += 1
            zone = int(rest[1:i])
            rest = rest[i:]

            if not rest.startswith('-'):
                print 'Invalid add value: %s' % devstr
                print "The on-disk ring builder is unchanged.\n"
                exit(EXIT_ERROR)
            i = 1
            if rest[i] == '[':
                i += 1
                while i < len(rest) and rest[i] != ']':
                    i += 1
                i += 1
                ip = rest[1:i].lstrip('[').rstrip(']')
                rest = rest[i:]
            else:
                while i < len(rest) and rest[i] in '0123456789.':
                    i += 1
                ip = rest[1:i]
                rest = rest[i:]

            if not rest.startswith(':'):
                print 'Invalid add value: %s' % devstr
                print "The on-disk ring builder is unchanged.\n"
                exit(EXIT_ERROR)
            i = 1
            while i < len(rest) and rest[i].isdigit():
                i += 1
            port = int(rest[1:i])
            rest = rest[i:]

            replication_ip = ip
            replication_port = port
            if rest.startswith('R'):
                i = 1
                if rest[i] == '[':
                    i += 1
                    while i < len(rest) and rest[i] != ']':
                        i += 1
                    i += 1
                    replication_ip = rest[1:i].lstrip('[').rstrip(']')
                    rest = rest[i:]
                else:
                    while i < len(rest) and rest[i] in '0123456789.':
                        i += 1
                    replication_ip = rest[1:i]
                    rest = rest[i:]

                if not rest.startswith(':'):
                    print 'Invalid add value: %s' % devstr
                    print "The on-disk ring builder is unchanged.\n"
                    exit(EXIT_ERROR)
                i = 1
                while i < len(rest) and rest[i].isdigit():
                    i += 1
                replication_port = int(rest[1:i])
                rest = rest[i:]

            if not rest.startswith('/'):
                print 'Invalid add value: %s' % devstr
                print "The on-disk ring builder is unchanged.\n"
                exit(EXIT_ERROR)
            i = 1
            while i < len(rest) and rest[i] != '_':
                i += 1
            device_name = rest[1:i]
            rest = rest[i:]

            meta = ''
            if rest.startswith('_'):
                meta = rest[1:]

            try:
                weight = float(weightstr)
            except ValueError:
                print 'Invalid weight value: %s' % weightstr
                print "The on-disk ring builder is unchanged.\n"
                exit(EXIT_ERROR)

            if weight < 0:
                print 'Invalid weight value (must be positive): %s' % weightstr
                print "The on-disk ring builder is unchanged.\n"
                exit(EXIT_ERROR)

            parsed_devs.append({'region': region, 'zone': zone, 'ip': ip,
                                'port': port, 'device': device_name,
                                'replication_ip': replication_ip,
                                'replication_port': replication_port,
                                'weight': weight, 'meta': meta})
        return parsed_devs
    else:
        try:
            dev = build_dev_from_opts(opts)
        except ValueError as e:
            print e
            print "The on-disk ring builder is unchanged.\n"
            exit(EXIT_ERROR)
        return [dev]

class Commands(object):

    def unknown():
        print 'Unknown command: %s' % argv[2]
        exit(EXIT_ERROR)

    def create():
        """
swift-ring-builder <builder_file> create <part_power> <replicas>
                                         <min_part_hours>
    Creates <builder_file> with 2^<part_power> partitions and <replicas>.
    <min_part_hours> is number of hours to restrict moving a partition more
    than once.
        """
        if len(argv) < 6:
            print Commands.create.__doc__.strip()
            exit(EXIT_ERROR)
        builder = RingBuilder(int(argv[3]), float(argv[4]), int(argv[5]))
        backup_dir = pathjoin(dirname(argv[1]), 'backups')
        try:
            mkdir(backup_dir)
        except OSError as err:
            if err.errno != EEXIST:
                raise
        builder.save(pathjoin(backup_dir, '%d.' % time() + basename(argv[1])))
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def default():
        """
swift-ring-builder <builder_file>
    Shows information about the ring and the devices within.
        """
        print '%s, build version %d' % (argv[1], builder.version)
        regions = 0
        zones = 0
        balance = 0
        dev_count = 0
        if builder.devs:
            regions = len(set(d['region'] for d in builder.devs
                              if d is not None))
            zones = len(set((d['region'], d['zone']) for d in builder.devs
                            if d is not None))
            dev_count = len([dev for dev in builder.devs
                             if dev is not None])
            balance = builder.get_balance()
        print '%d partitions, %.6f replicas, %d regions, %d zones, ' \
              '%d devices, %.02f balance' % (builder.parts, builder.replicas,
                                             regions, zones, dev_count,
                                             balance)
        print 'The minimum number of hours before a partition can be ' \
              'reassigned is %s' % builder.min_part_hours
        if builder.devs:
            print 'Devices:    id  region  zone      ip address  port  ' \
                  'replication ip  replication port      name ' \
                  'weight partitions balance meta'
            weighted_parts = builder.parts * builder.replicas / \
                sum(d['weight'] for d in builder.devs if d is not None)
            for dev in builder.devs:
                if dev is None:
                    continue
                if not dev['weight']:
                    if dev['parts']:
                        balance = MAX_BALANCE
                    else:
                        balance = 0
                else:
                    balance = 100.0 * dev['parts'] / \
                        (dev['weight'] * weighted_parts) - 100.0
                print('         %5d %7d %5d %15s %5d %15s %17d %9s %6.02f '
                      '%10s %7.02f %s' %
                      (dev['id'], dev['region'], dev['zone'], dev['ip'],
                       dev['port'], dev['replication_ip'],
                       dev['replication_port'], dev['device'], dev['weight'],
                       dev['parts'], balance, dev['meta']))
        exit(EXIT_SUCCESS)

    def search():
        """
swift-ring-builder <builder_file> search <search-value>
    Shows information about matching devices.
        """
        if len(argv) < 4:
            print Commands.search.__doc__.strip()
            print
            print parse_search_value.__doc__.strip()
            exit(EXIT_ERROR)
        devs = builder.search_devs(parse_search_value(argv[3]))
        if not devs:
            print 'No matching devices found'
            exit(EXIT_ERROR)
        print 'Devices:    id  region  zone      ip address  port  ' \
              'replication ip  replication port      name weight partitions ' \
              'balance meta'
        weighted_parts = builder.parts * builder.replicas / \
            sum(d['weight'] for d in builder.devs if d is not None)
        for dev in devs:
            if not dev['weight']:
                if dev['parts']:
                    balance = MAX_BALANCE
                else:
                    balance = 0
            else:
                balance = 100.0 * dev['parts'] / \
                    (dev['weight'] * weighted_parts) - 100.0
            print('         %5d %7d %5d %15s %5d %15s %17d %9s %6.02f %10s '
                  '%7.02f %s' %
                  (dev['id'], dev['region'], dev['zone'], dev['ip'],
                   dev['port'], dev['replication_ip'], dev['replication_port'],
                   dev['device'], dev['weight'], dev['parts'], balance,
                   dev['meta']))
        exit(EXIT_SUCCESS)

    def list_parts():
        """
swift-ring-builder <builder_file> list_parts <search-value> [<search-value>] ..
    Returns a 2 column list of all the partitions that are assigned to any of
    the devices matching the search values given. The first column is the
    assigned partition number and the second column is the number of device
    matches for that partition. The list is ordered from most number of matches
    to least. If there are a lot of devices to match against, this command
    could take a while to run.
        """
        if len(argv) < 4:
            print Commands.list_parts.__doc__.strip()
            print
            print parse_search_value.__doc__.strip()
            exit(EXIT_ERROR)
        devs = []
        for arg in argv[3:]:
            devs.extend(builder.search_devs(parse_search_value(arg)) or [])
        if not devs:
            print 'No matching devices found'
            exit(EXIT_ERROR)
        devs = [d['id'] for d in devs]
        max_replicas = int(ceil(builder.replicas))
        matches = [array('i') for x in xrange(max_replicas)]
        for part in xrange(builder.parts):
            count = len([d for d in builder.get_part_devices(part)
                         if d['id'] in devs])
            if count:
                matches[max_replicas - count].append(part)
        print 'Partition   Matches'
        for index, parts in enumerate(matches):
            for part in parts:
                print '%9d   %7d' % (part, max_replicas - index)
        exit(EXIT_SUCCESS)

    def add():
        """
swift-ring-builder <builder_file> add
    [r<region>]z<zone>-<ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta>
     <weight>
    [[r<region>]z<zone>-<ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta>
     <weight>] ...

    Where <r_ip> and <r_port> are replication ip and port.

or

swift-ring-builder <builder_file> add
    [--region <region>] --zone <zone> --ip <ip> --port <port>
    --replication-ip <r_ip> --replication-port <r_port>
    --device <device_name> --meta <meta> --weight <weight>

    Adds devices to the ring with the given information. No partitions will be
    assigned to the new device until after running 'rebalance'. This is so you
    can make multiple device changes and rebalance them all just once.
        """
        if len(argv) < 5 or len(argv) % 2 != 1:
            print Commands.add.__doc__.strip()
            exit(EXIT_ERROR)

        for new_dev in _parse_add_values(argv[3:]):
            for dev in builder.devs:
                if dev is None:
                    continue
                if dev['ip'] == new_dev['ip'] and \
                        dev['port'] == new_dev['port'] and \
                        dev['device'] == new_dev['device']:
                    print 'Device %d already uses %s:%d/%s.' % \
                          (dev['id'], dev['ip'], dev['port'], dev['device'])
                    print "The on-disk ring builder is unchanged.\n"
                    exit(EXIT_ERROR)
            dev_id = builder.add_dev(new_dev)
            print('Device %s with %s weight got id %s' %
                  (format_device(new_dev), new_dev['weight'], dev_id))

        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def set_weight():
        """
swift-ring-builder <builder_file> set_weight <search-value> <weight>
    [<search-value> <weight] ...

    Resets the devices' weights. No partitions will be reassigned to or from
    the device until after running 'rebalance'. This is so you can make
    multiple device changes and rebalance them all just once.
        """
        if len(argv) < 5 or len(argv) % 2 != 1:
            print Commands.set_weight.__doc__.strip()
            print
            print parse_search_value.__doc__.strip()
            exit(EXIT_ERROR)

        devs_and_weights = izip(islice(argv, 3, len(argv), 2),
                                islice(argv, 4, len(argv), 2))
        for devstr, weightstr in devs_and_weights:
            devs = builder.search_devs(parse_search_value(devstr))
            weight = float(weightstr)
            if not devs:
                print("Search value \"%s\" matched 0 devices.\n"
                      "The on-disk ring builder is unchanged.\n"
                      % devstr)
                exit(EXIT_ERROR)
            if len(devs) > 1:
                print 'Matched more than one device:'
                for dev in devs:
                    print '    %s' % format_device(dev)
                if raw_input('Are you sure you want to update the weight for '
                             'these %s devices? (y/N) ' % len(devs)) != 'y':
                    print 'Aborting device modifications'
                    exit(EXIT_ERROR)
            for dev in devs:
                builder.set_dev_weight(dev['id'], weight)
                print '%s weight set to %s' % (format_device(dev),
                                               dev['weight'])
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def set_info():
        """
swift-ring-builder <builder_file> set_info
    <search-value> <ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta>
    [<search-value> <ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta>] ...

    Where <r_ip> and <r_port> are replication ip and port.

    For each search-value, resets the matched device's information.
    This information isn't used to assign partitions, so you can use
    'write_ring' afterward to rewrite the current ring with the newer
    device information. Any of the parts are optional in the final
    <ip>:<port>/<device_name>_<meta> parameter; just give what you
    want to change. For instance set_info d74 _"snet: 5.6.7.8" would
    just update the meta data for device id 74.
        """
        if len(argv) < 5 or len(argv) % 2 != 1:
            print Commands.set_info.__doc__.strip()
            print
            print parse_search_value.__doc__.strip()
            exit(EXIT_ERROR)

        searches_and_changes = izip(islice(argv, 3, len(argv), 2),
                                    islice(argv, 4, len(argv), 2))

        for search_value, change_value in searches_and_changes:
            devs = builder.search_devs(parse_search_value(search_value))
            change = []
            if len(change_value) and change_value[0].isdigit():
                i = 1
                while (i < len(change_value) and
                       change_value[i] in '0123456789.'):
                    i += 1
                change.append(('ip', change_value[:i]))
                change_value = change_value[i:]
            elif len(change_value) and change_value[0] == '[':
                i = 1
                while i < len(change_value) and change_value[i] != ']':
                    i += 1
                i += 1
                change.append(('ip', change_value[:i].lstrip('[').rstrip(']')))
                change_value = change_value[i:]
            if change_value.startswith(':'):
                i = 1
                while i < len(change_value) and change_value[i].isdigit():
                    i += 1
                change.append(('port', int(change_value[1:i])))
                change_value = change_value[i:]
            if change_value.startswith('R'):
                change_value = change_value[1:]
                if len(change_value) and change_value[0].isdigit():
                    i = 1
                    while (i < len(change_value) and
                           change_value[i] in '0123456789.'):
                        i += 1
                    change.append(('replication_ip', change_value[:i]))
                    change_value = change_value[i:]
                elif len(change_value) and change_value[0] == '[':
                    i = 1
                    while i < len(change_value) and change_value[i] != ']':
                        i += 1
                    i += 1
                    change.append(('replication_ip',
                                   change_value[:i].lstrip('[').rstrip(']')))
                    change_value = change_value[i:]
                if change_value.startswith(':'):
                    i = 1
                    while i < len(change_value) and change_value[i].isdigit():
                        i += 1
                    change.append(('replication_port', int(change_value[1:i])))
                    change_value = change_value[i:]
            if change_value.startswith('/'):
                i = 1
                while i < len(change_value) and change_value[i] != '_':
                    i += 1
                change.append(('device', change_value[1:i]))
                change_value = change_value[i:]
            if change_value.startswith('_'):
                change.append(('meta', change_value[1:]))
                change_value = ''
            if change_value or not change:
                raise ValueError('Invalid set info change value: %s' %
                                 repr(argv[4]))
            if not devs:
                print("Search value \"%s\" matched 0 devices.\n"
                      "The on-disk ring builder is unchanged.\n"
                      % search_value)
                exit(EXIT_ERROR)
            if len(devs) > 1:
                print 'Matched more than one device:'
                for dev in devs:
                    print '    %s' % format_device(dev)
                if raw_input('Are you sure you want to update the info for '
                             'these %s devices? (y/N) ' % len(devs)) != 'y':
                    print 'Aborting device modifications'
                    exit(EXIT_ERROR)
            for dev in devs:
                orig_dev_string = format_device(dev)
                test_dev = dict(dev)
                for key, value in change:
                    test_dev[key] = value
                for check_dev in builder.devs:
                    if not check_dev or check_dev['id'] == test_dev['id']:
                        continue
                    if check_dev['ip'] == test_dev['ip'] and \
                            check_dev['port'] == test_dev['port'] and \
                            check_dev['device'] == test_dev['device']:
                        print 'Device %d already uses %s:%d/%s.' % \
                              (check_dev['id'], check_dev['ip'],
                               check_dev['port'], check_dev['device'])
                        exit(EXIT_ERROR)
                for key, value in change:
                    dev[key] = value
                print 'Device %s is now %s' % (orig_dev_string,
                                               format_device(dev))
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def remove():
        """
swift-ring-builder <builder_file> remove <search-value> [search-value ...]
    Removes the device(s) from the ring. This should normally just be used for
    a device that has failed. For a device you wish to decommission, it's best
    to set its weight to 0, wait for it to drain all its data, then use this
    remove command. This will not take effect until after running 'rebalance'.
    This is so you can make multiple device changes and rebalance them all just
    once.
        """
        if len(argv) < 4:
            print Commands.remove.__doc__.strip()
            print
            print parse_search_value.__doc__.strip()
            exit(EXIT_ERROR)

        for search_value in argv[3:]:
            devs = builder.search_devs(parse_search_value(search_value))
            if not devs:
                print("Search value \"%s\" matched 0 devices.\n"
                      "The on-disk ring builder is unchanged." % search_value)
                exit(EXIT_ERROR)
            if len(devs) > 1:
                print 'Matched more than one device:'
                for dev in devs:
                    print '    %s' % format_device(dev)
                if raw_input('Are you sure you want to remove these %s '
                             'devices? (y/N) ' % len(devs)) != 'y':
                    print 'Aborting device removals'
                    exit(EXIT_ERROR)
            for dev in devs:
                try:
                    builder.remove_dev(dev['id'])
                except exceptions.RingBuilderError as e:
                    print '-' * 79
                    print(
                        "An error occurred while removing device with id %d\n"
                        "This usually means that you attempted to remove\n"
                        "the last device in a ring. If this is the case,\n"
                        "consider creating a new ring instead.\n"
                        "The on-disk ring builder is unchanged.\n"
                        "Original exception message: %s" %
                        (dev['id'], e)
                    )
                    print '-' * 79
                    exit(EXIT_ERROR)

                print '%s marked for removal and will ' \
                      'be removed next rebalance.' % format_device(dev)
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def rebalance():
        """
swift-ring-builder <builder_file> rebalance <seed>
    Attempts to rebalance the ring by reassigning partitions that haven't been
    recently reassigned.
        """
        def get_seed(index):
            try:
                return argv[index]
            except IndexError:
                pass

        devs_changed = builder.devs_changed
        try:
            last_balance = builder.get_balance()
            parts, balance = builder.rebalance(seed=get_seed(3))
        except exceptions.RingBuilderError as e:
            print '-' * 79
            print("An error has occurred during ring validation. Common\n"
                  "causes of failure are rings that are empty or do not\n"
                  "have enough devices to accommodate the replica count.\n"
                  "Original exception message:\n %s" % e.message
                  )
            print '-' * 79
            exit(EXIT_ERROR)
        if not parts:
            print 'No partitions could be reassigned.'
            print 'Either none need to be or none can be due to ' \
                  'min_part_hours [%s].' % builder.min_part_hours
            exit(EXIT_WARNING)
        # If we set device's weight to zero, currently balance will be set
        # special value(MAX_BALANCE) until zero weighted device return all
        # its partitions. So we cannot check balance has changed.
        # Thus we need to check balance or last_balance is special value.
        if not devs_changed and abs(last_balance - balance) < 1 and \
                not (last_balance == MAX_BALANCE and balance == MAX_BALANCE):
            print 'Cowardly refusing to save rebalance as it did not change ' \
                  'at least 1%.'
            exit(EXIT_WARNING)
        try:
            builder.validate()
        except exceptions.RingValidationError as e:
            print '-' * 79
            print("An error has occurred during ring validation. Common\n"
                  "causes of failure are rings that are empty or do not\n"
                  "have enough devices to accommodate the replica count.\n"
                  "Original exception message:\n %s" % e.message
                  )
            print '-' * 79
            exit(EXIT_ERROR)
        print 'Reassigned %d (%.02f%%) partitions. Balance is now %.02f.' % \
              (parts, 100.0 * parts / builder.parts, balance)
        status = EXIT_SUCCESS
        if balance > 5:
            print '-' * 79
            print 'NOTE: Balance of %.02f indicates you should push this ' % \
                  balance
            print '      ring, wait at least %d hours, and rebalance/repush.' \
                  % builder.min_part_hours
            print '-' * 79
            status = EXIT_WARNING
        ts = time()
        builder.get_ring().save(
            pathjoin(backup_dir, '%d.' % ts + basename(ring_file)))
        builder.save(pathjoin(backup_dir, '%d.' % ts + basename(argv[1])))
        builder.get_ring().save(ring_file)
        builder.save(argv[1])
        exit(status)

    def validate():
        """
swift-ring-builder <builder_file> validate
    Just runs the validation routines on the ring.
        """
        builder.validate()
        exit(EXIT_SUCCESS)

    def write_ring():
        """
swift-ring-builder <builder_file> write_ring
    Just rewrites the distributable ring file. This is done automatically after
    a successful rebalance, so really this is only useful after one or more
    'set_info' calls when no rebalance is needed but you want to send out the
    new device information.
        """
        ring_data = builder.get_ring()
        if not ring_data._replica2part2dev_id:
            if ring_data.devs:
                print 'Warning: Writing a ring with no partition ' \
                      'assignments but with devices; did you forget to run ' \
                      '"rebalance"?'
            else:
                print 'Warning: Writing an empty ring'
        ring_data.save(
            pathjoin(backup_dir, '%d.' % time() + basename(ring_file)))
        ring_data.save(ring_file)
        exit(EXIT_SUCCESS)

    def write_builder():
        """
swift-ring-builder <ring_file> write_builder [min_part_hours]
    Recreate a builder from a ring file (lossy) if you lost your builder
    backups.  (Protip: don't lose your builder backups).
    [min_part_hours] is one of those numbers lost to the builder,
    you can change it with set_min_part_hours.
        """
        if exists(builder_file):
            print 'Cowardly refusing to overwrite existing ' \
                'Ring Builder file: %s' % builder_file
            exit(EXIT_ERROR)
        if len(argv) > 3:
            min_part_hours = int(argv[3])
        else:
            stderr.write("WARNING: default min_part_hours may not match "
                         "the value in the lost builder.\n")
            min_part_hours = 24
        ring = Ring(ring_file)
        for dev in ring.devs:
            dev.update({
                'parts': 0,
                'parts_wanted': 0,
            })
        builder_dict = {
            'part_power': 32 - ring._part_shift,
            'replicas': float(ring.replica_count),
            'min_part_hours': min_part_hours,
            'parts': ring.partition_count,
            'devs': ring.devs,
            'devs_changed': False,
            'version': 0,
            '_replica2part2dev': ring._replica2part2dev_id,
            '_last_part_moves_epoch': None,
            '_last_part_moves': None,
            '_last_part_gather_start': 0,
            '_remove_devs': [],
        }
        builder = RingBuilder(1, 1, 1)
        builder.copy_from(builder_dict)
        for parts in builder._replica2part2dev:
            for dev_id in parts:
                builder.devs[dev_id]['parts'] += 1
        builder._set_parts_wanted()
        builder.save(builder_file)

    def pretend_min_part_hours_passed():
        builder.pretend_min_part_hours_passed()
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def set_min_part_hours():
        """
swift-ring-builder <builder_file> set_min_part_hours <hours>
    Changes the <min_part_hours> to the given <hours>. This should be set to
    however long a full replication/update cycle takes. We're working on a way
    to determine this more easily than scanning logs.
        """
        if len(argv) < 4:
            print Commands.set_min_part_hours.__doc__.strip()
            exit(EXIT_ERROR)
        builder.change_min_part_hours(int(argv[3]))
        print 'The minimum number of hours before a partition can be ' \
              'reassigned is now set to %s' % argv[3]
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

    def set_replicas():
        """
swift-ring-builder <builder_file> set_replicas <replicas>
    Changes the replica count to the given <replicas>. <replicas> may
    be a floating-point value, in which case some partitions will have
    floor(<replicas>) replicas and some will have ceiling(<replicas>)
    in the correct proportions.

    A rebalance is needed to make the change take effect.
    """
        if len(argv) < 4:
            print Commands.set_replicas.__doc__.strip()
            exit(EXIT_ERROR)

        new_replicas = argv[3]
        try:
            new_replicas = float(new_replicas)
        except ValueError:
            print Commands.set_replicas.__doc__.strip()
            print "\"%s\" is not a valid number." % new_replicas
            exit(EXIT_ERROR)

        if new_replicas < 1:
            print "Replica count must be at least 1."
            exit(EXIT_ERROR)

        builder.set_replicas(new_replicas)
        print 'The replica count is now %.6f.' % builder.replicas
        print 'The change will take effect after the next rebalance.'
        builder.save(argv[1])
        exit(EXIT_SUCCESS)

def main(arguments=None):
    global argv, backup_dir, builder, builder_file, ring_file
    if arguments:
        argv = arguments
    else:
        argv = sys_argv

    if len(argv) < 2:
        print "swift-ring-builder %(MAJOR_VERSION)s.%(MINOR_VERSION)s\n" % \
              globals()
        print Commands.default.__doc__.strip()
        print
        cmds = [c for c, f in Commands.__dict__.iteritems()
                if f.__doc__ and c[0] != '_' and c != 'default']
        cmds.sort()
        for cmd in cmds:
            print Commands.__dict__[cmd].__doc__.strip()
            print
        print parse_search_value.__doc__.strip()
        print
        for line in wrap(' '.join(cmds), 79, initial_indent='Quick list: ',
                         subsequent_indent='            '):
            print line
        print('Exit codes: 0 = operation successful\n'
              '            1 = operation completed with warnings\n'
              '            2 = error')
        exit(EXIT_SUCCESS)

    builder_file, ring_file = parse_builder_ring_filename_args(argv)

    try:
        builder = RingBuilder.load(builder_file)
    except exceptions.UnPicklingError as e:
        print e
        exit(EXIT_ERROR)
    except (exceptions.FileNotFoundError, exceptions.PermissionError) as e:
        if len(argv) < 3 or argv[2] not in('create', 'write_builder'):
            print e
            exit(EXIT_ERROR)
    except Exception as e:
        print 'Problem occurred while reading builder file: %s. %s' % (
            argv[1], e.message)
        exit(EXIT_ERROR)

    backup_dir = pathjoin(dirname(argv[1]), 'backups')
    try:
        mkdir(backup_dir)
    except OSError as err:
        if err.errno != EEXIST:
            raise

    if len(argv) == 2:
        command = "default"
    else:
        command = argv[2]
    if argv[0].endswith('-safe'):
        try:
            with lock_parent_directory(abspath(argv[1]), 15):
                Commands.__dict__.get(command, Commands.unknown.im_func)()
        except exceptions.LockTimeout:
            print "Ring/builder dir currently locked."
            exit(2)
    else:
        Commands.__dict__.get(command, Commands.unknown.im_func)()

if __name__ == '__main__':
    main()


text:
package com.coolweather.android.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;

import com.coolweather.android.gson.Weather;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.LogUtil;
import com.coolweather.android.util.Utility;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Drug on 2017/6/19.
 *
 * 实现天气和必应图片更新
 */

public class AutoUpdateService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //更新天气和图片
        updateWeather();
        updateBingPic();
        //定义机制管理器
        AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
        int betweenTime = 8 * 60 * 60 * 1000;   //更新时间间隔
        long triggerAtTime = SystemClock.elapsedRealtime() + betweenTime;  //触发时间点
        Intent i = new Intent(this, AutoUpdateService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
        manager.cancel(pi);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新天气信息
     */
    private void updateWeather(){
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = pref.getString("weather", null);
        if (weatherString != null){
            //如果缓冲不为空,则直接解析数据
            Weather weather = Utility.handleWeatherResponse(weatherString);
            //获取天气ID
            String weatherId = weather.basic.weatherId;
            //定义更新获取地址
            String weatherUrl = "https://free-api.heweather.com/v5/weather?city=" +
                    weatherId + "&key=001be178c1a54af7971a895bebff259e";
            //网络请求获取数据
            HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //从response中获取数据
                    String responseText = response.body().string();
                    LogUtil.d("AutoUpdateService", responseText);
                    Weather weather = Utility.handleWeatherResponse(responseText);
                    if (weather != null && "ok".equals(weather.status)){
                        SharedPreferences.Editor editor = PreferenceManager.
                                getDefaultSharedPreferences(AutoUpdateService.this).edit();
                        editor.putString("weather", responseText);
                        editor.apply();
                    }
                }
            });
        }
    }

    /**
     * 更新必应每日图片
     */
    private void updateBingPic(){
        //图片地址
        String bingPicUrl = "http://guolin.tech/api/bing_pic";
        //从网络获取图片
        HttpUtil.sendOkHttpRequest(bingPicUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取返回数据
                String responseText = response.body().string();
                //将数据存入缓冲
                SharedPreferences.Editor editor = PreferenceManager.
                        getDefaultSharedPreferences(AutoUpdateService.this).edit();
                editor.putString("bing_pic", responseText);
                editor.apply();
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ru.job4j.task2;

/**
 * A class describes a word counter.
 */
public class WordCounter implements Runnable {

    /**
     * A field for the line to be counted space.
     */
    private String string;

    /**
     * A constructor.
     * @param string is a text lin.
     */
    public WordCounter(String string) {
        this.string = string;
    }

    @Override
    public void run() {
        int counter = wordCounter();
        System.out.printf("An amount of word in a given text line. - is: %s%s", counter, "\n");
    }

    /**
     * A method counts word in a line.
     * @return amount of a words.
     */
    private int wordCounter() {
        int counter = 0;
        int position = 0;
        while (position < this.string.length()) {
            if (this.string.charAt(position) != ' ') {
                for (int i = position; i < this.string.length(); i++) {
                    if (this.string.charAt(i) == ' ' || i == this.string.length() - 1) {
                        counter++;
                        position = i;
                        break;
                    }
                }
            }
            position++;
        }
        return counter;
    }
}


text:
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using JdSdk.Request.Ware;

namespace JdSdk.Response.Ware
{
    [Serializable]
    public class WareUpdateVenderSellSkuResponse : JdResponse
    {
        [JsonProperty("wareupdatevender_sellsku")]
        public WareUpdateVenderSellSkuRequest WareupdateVenderSellSkuRequest
        {
            get;
            set;
        }

    }

}


text:
package net.sourceforge.ganttproject.task;

import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: bard
 */
public interface TaskManagerConfig {
    Color getDefaultColor();
}


text:
@interface PPLLaunchTests : XCTestCase

@end

@implementation PPLLaunchTests

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each
    // test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of
    // each test method in the class.
    [super tearDown];
}

- (void)testCheckFirstLaunchMarked
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if ([prefs boolForKey:kLauchFirstTime])
    {
        [prefs removeObjectForKey:kLauchFirstTime];
    }
    [delegate markFirstLaunch];
    XCTAssertFalse([delegate checkFirstLaunch]);
}

- (void)testSkipLaunchScreenOnSecondLaunch
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate checkFirstLaunch])
    {
        XCTAssertTrue([[delegate selectRootViewController]
            isKindOfClass:[PPLLaunchViewController class]]);
    }
    else
    {
        XCTAssertTrue([[delegate selectRootViewController]
            isKindOfClass:[PPLVoteViewController class]]);
    }
}

@end


text:
namespace content {

// static
ChildIOSurfaceManager* ChildIOSurfaceManager::GetInstance() {
  return Singleton<ChildIOSurfaceManager,
                   LeakySingletonTraits<ChildIOSurfaceManager>>::get();
}

bool ChildIOSurfaceManager::RegisterIOSurface(int io_surface_id,
                                              int client_id,
                                              IOSurfaceRef io_surface) {
  DCHECK(service_port_.is_valid());
  DCHECK(!token_.IsZero());

  mach_port_t reply_port;
  kern_return_t kr = mach_port_allocate(mach_task_self(),
                                        MACH_PORT_RIGHT_RECEIVE, &reply_port);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_port_allocate";
    return false;
  }
  base::mac::ScopedMachReceiveRight scoped_receive_right(reply_port);

  // Deallocate the right after sending a copy to the parent.
  base::mac::ScopedMachSendRight scoped_io_surface_right(
      IOSurfaceCreateMachPort(io_surface));

  union {
    IOSurfaceManagerHostMsg_RegisterIOSurface request;
    struct {
      IOSurfaceManagerMsg_RegisterIOSurfaceReply msg;
      mach_msg_trailer_t trailer;
    } reply;
  } data = {{{0}}};
  data.request.header.msgh_bits =
      MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE) |
      MACH_MSGH_BITS_COMPLEX;
  data.request.header.msgh_remote_port = service_port_;
  data.request.header.msgh_local_port = reply_port;
  data.request.header.msgh_size = sizeof(data.request);
  data.request.header.msgh_id = IOSurfaceManagerHostMsg_RegisterIOSurface::ID;
  data.request.body.msgh_descriptor_count = 1;
  data.request.io_surface_port.name = scoped_io_surface_right;
  data.request.io_surface_port.disposition = MACH_MSG_TYPE_COPY_SEND;
  data.request.io_surface_port.type = MACH_MSG_PORT_DESCRIPTOR;
  data.request.io_surface_id = io_surface_id;
  data.request.client_id = client_id;
  memcpy(data.request.token_name, token_.name, sizeof(token_.name));

  kr = mach_msg(&data.request.header, MACH_SEND_MSG | MACH_RCV_MSG,
                sizeof(data.request), sizeof(data.reply), reply_port,
                MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_msg";
    return false;
  }

  return data.reply.msg.result;
}

void ChildIOSurfaceManager::UnregisterIOSurface(int io_surface_id,
                                                int client_id) {
  DCHECK(service_port_.is_valid());
  DCHECK(!token_.IsZero());

  IOSurfaceManagerHostMsg_UnregisterIOSurface request = {{0}};
  request.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
  request.header.msgh_remote_port = service_port_;
  request.header.msgh_local_port = MACH_PORT_NULL;
  request.header.msgh_size = sizeof(request);
  request.header.msgh_id = IOSurfaceManagerHostMsg_UnregisterIOSurface::ID;
  request.io_surface_id = io_surface_id;
  request.client_id = client_id;
  memcpy(request.token_name, token_.name, sizeof(token_.name));

  kern_return_t kr =
      mach_msg(&request.header, MACH_SEND_MSG, sizeof(request), 0,
               MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_msg";
  }
}

IOSurfaceRef ChildIOSurfaceManager::AcquireIOSurface(int io_surface_id) {
  DCHECK(service_port_.is_valid());
  DCHECK(!token_.IsZero());

  mach_port_t reply_port;
  kern_return_t kr = mach_port_allocate(mach_task_self(),
                                        MACH_PORT_RIGHT_RECEIVE, &reply_port);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_port_allocate";
    return nullptr;
  }
  base::mac::ScopedMachReceiveRight scoped_receive_right(reply_port);

  union {
    IOSurfaceManagerHostMsg_AcquireIOSurface request;
    struct {
      IOSurfaceManagerMsg_AcquireIOSurfaceReply msg;
      mach_msg_trailer_t trailer;
    } reply;
  } data = {{{0}}};
  data.request.header.msgh_bits =
      MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE);
  data.request.header.msgh_remote_port = service_port_;
  data.request.header.msgh_local_port = reply_port;
  data.request.header.msgh_size = sizeof(data.request);
  data.request.header.msgh_id = IOSurfaceManagerHostMsg_AcquireIOSurface::ID;
  data.request.io_surface_id = io_surface_id;
  memcpy(data.request.token_name, token_.name, sizeof(token_.name));

  kr = mach_msg(&data.request.header, MACH_SEND_MSG | MACH_RCV_MSG,
                sizeof(data.request), sizeof(data.reply), reply_port,
                MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  if (kr != KERN_SUCCESS) {
    MACH_LOG(ERROR, kr) << "mach_msg";
    return nullptr;
  }

  // Deallocate the right after creating an IOSurface reference.
  base::mac::ScopedMachSendRight scoped_io_surface_right(
      data.reply.msg.io_surface_port.name);

  return IOSurfaceLookupFromMachPort(scoped_io_surface_right);
}

ChildIOSurfaceManager::ChildIOSurfaceManager() {
}

ChildIOSurfaceManager::~ChildIOSurfaceManager() {
}

}  // namespace content


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;

#[test]
fn vscalefss_1() {
    run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSS, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3)), operand3: Some(Direct(XMM6)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Down), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 242, 101, 191, 45, 222], OperandSize::Dword)
}

#[test]
fn vscalefss_2() {
    run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSS, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM0)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, ECX, Eight, 1004331378, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 242, 125, 138, 45, 172, 202, 114, 225, 220, 59], OperandSize::Dword)
}

#[test]
fn vscalefss_3() {
    run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSS, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM31)), operand3: Some(Direct(XMM30)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Down), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 146, 5, 181, 45, 222], OperandSize::Qword)
}

#[test]
fn vscalefss_4() {
    run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSS, operand1: Some(Direct(XMM20)), operand2: Some(Direct(XMM10)), operand3: Some(IndirectScaledDisplaced(RDX, Two, 1347849466, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 226, 45, 141, 45, 36, 85, 250, 140, 86, 80], OperandSize::Qword)
}


text:
class TestFacility: public cyclus::Facility {
 public:
  static std::string proto_name() { return "test_fac_prototype"; }
  static std::string spec() { return "test_fac_impl"; }

  TestFacility(cyclus::Context* ctx) : cyclus::Facility(ctx) {
    cyclus::Agent::prototype(proto_name());
    cyclus::Agent::spec(spec());
  }
  virtual ~TestFacility() {}

  virtual cyclus::Agent* Clone() { return new TestFacility(context()); }
  virtual void InitInv(cyclus::Inventories& inv) {}
  virtual cyclus::Inventories SnapshotInv() {return cyclus::Inventories();}

  void Tick() {}
  void Tock() {}

  #pragma cyclus var dict(shape=[10])
  std::vector<double> sized_test;
};

#endif  // CYCLUS_TESTS_TEST_AGENTS_TEST_FACILITY_H_


text:
Smart parking prototype for academic purposes

## Instructions:
- Install Ruby (and Rails) -> https://rvm.io/rvm/install
- Clone repo ```$ git clone git@github.com:santi-git/smart_parking.git ``` (Recordar que se necesita tener la clave ssh en git)
- Install all dependencies ```$ bundle install ```
- Run database migrations ```$ rake db:migrate ```
- Code !!! \o/ !!!


text:
<?php

namespace Toadsuck\Core\Tests\App\Controllers;

use Toadsuck\Core\Console as ConsoleController;

class Console extends ConsoleController
{
	public function __construct($opts)
	{
		parent::__construct($opts);
	}

	public function sayHello($name = 'Dave')
	{
		printf('Hello, %s', $name);
	}
}


text:
package org.javabits.yar.guice;

import com.google.inject.*;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.binder.ScopedBindingBuilder;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;

import static java.util.Objects.requireNonNull;

/**
 * TODO comment
 * Date: 2/10/13
 * Time: 10:13 AM
 *
 * @author Romain Gilles
 */
class RegistrationBindingBuilderImpl<T> implements RegistrationAnnotatedBindingBuilder<T> {

    private final Binder binder;
    private Key<T> key;

    private AnnotatedBindingBuilder<T> annotatedBindingBuilder;
    private LinkedBindingBuilder<T> linkedBindingBuilder;

    RegistrationBindingBuilderImpl(Binder binder, Class<T> type) {
        this.binder = requireNonNull(binder, "binder");
        key = Key.get(type);
        linkedBindingBuilder = annotatedBindingBuilder = binder.bind(type);
    }

    RegistrationBindingBuilderImpl(Binder binder, TypeLiteral<T> typeLiteral) {
        this.binder = requireNonNull(binder, "binder");
        key = Key.get(typeLiteral);
        linkedBindingBuilder = annotatedBindingBuilder = binder.bind(typeLiteral);
    }

    RegistrationBindingBuilderImpl(Binder binder, Key<T> key) {
        this.binder = requireNonNull(binder, "binder");
        requireNonNull(key, "key");
        this.key = key;
        linkedBindingBuilder = binder.bind(key);
    }

    @Override
    public RegistrationLinkedBindingBuilder<T> annotatedWith(Class<? extends Annotation> annotationType) {
        key = Key.get(key.getTypeLiteral(), annotationType);
        linkedBindingBuilder = annotatedBindingBuilder.annotatedWith(annotationType);
        return this;
    }

    @Override
    public RegistrationLinkedBindingBuilder<T> annotatedWith(Annotation annotation) {
        key = Key.get(key.getTypeLiteral(), annotation);
        linkedBindingBuilder = annotatedBindingBuilder.annotatedWith(annotation);
        return this;
    }

    private void bindRegistration() {
        bindRegistration(binder, key);
    }

    static void bindRegistration(Binder binder, Key<?> key) {
        binder.bind(Key.get(GuiceRegistration.class, UniqueAnnotations.create())).toInstance(GuiceRegistration.get(key));
    }

    @Override
    public ScopedBindingBuilder to(Class<? extends T> implementation) {
        bindRegistration();
        return linkedBindingBuilder.to(implementation);
    }

    @Override
    public ScopedBindingBuilder to(TypeLiteral<? extends T> implementation) {
        bindRegistration();
        return linkedBindingBuilder.to(implementation);
    }

    @Override
    public ScopedBindingBuilder to(Key<? extends T> targetKey) {
        bindRegistration();
        return linkedBindingBuilder.to(targetKey);
    }

    @Override
    public void toInstance(T instance) {
        bindRegistration();
        linkedBindingBuilder.toInstance(instance);
    }

    @Override
    public ScopedBindingBuilder toProvider(Provider<? extends T> provider) {
        bindRegistration();
        return linkedBindingBuilder.toProvider(provider);
    }

    @Override
    public ScopedBindingBuilder toProvider(Class<? extends javax.inject.Provider<? extends T>> providerType) {
        bindRegistration();
        return linkedBindingBuilder.toProvider(providerType);
    }

    @Override
    public ScopedBindingBuilder toProvider(TypeLiteral<? extends javax.inject.Provider<? extends T>> providerType) {
        bindRegistration();
        return linkedBindingBuilder.toProvider(providerType);
    }

    @Override
    public ScopedBindingBuilder toProvider(Key<? extends javax.inject.Provider<? extends T>> providerKey) {
        bindRegistration();
        return linkedBindingBuilder.toProvider(providerKey);
    }

    @Override
    public ScopedBindingBuilder toProvider(javax.inject.Provider<? extends T> provider) {
        bindRegistration();
        return linkedBindingBuilder.toProvider(provider);
    }

    @Override
    public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor) {
        bindRegistration();
        return linkedBindingBuilder.toConstructor(constructor);
    }

    @Override
    public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor, TypeLiteral<? extends S> type) {
        bindRegistration();
        return linkedBindingBuilder.toConstructor(constructor, type);
    }

    @Override
    public void in(Class<? extends Annotation> scopeAnnotation) {
        linkedBindingBuilder.in(scopeAnnotation);
    }

    @Override
    public void in(Scope scope) {
        linkedBindingBuilder.in(scope);
    }

    @Override
    public void asEagerSingleton() {
        linkedBindingBuilder.asEagerSingleton();
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLogActivitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('log_activities', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username', 30)->nullable();
            $table->string('activity', 277)->nullable();
            $table->string('url', 30)->nullable();
            $table->string('method', 30)->nullable();
            $table->string('ip', 30)->nullable();
            $table->string('agent', 30)->nullable();
            $table->string('activity_time', 30)->nullable();

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('log_activities');
    }
}


text:
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
import json

from flash import analytics

import logging
log = logging.getLogger(__name__)

@login_required
@require_http_methods(["POST"])
def track(request):
    actor = request.user
    statements_json = request.POST.get('statements', '')
    statements = json.loads(statements_json)
    num_statements = len(statements)
    results = []

    for s in statements:
        verb = s.get('verb', '')
        object = s.get('object', '')
        context = s.get('context', '')
        if context == '':
            context = None
        timestamp = s.get('timestamp', '')
        if timestamp == '':
            timestamp = None

        result = {"success": False, "data": s}

        if verb != '' and object != '':
            statement = analytics.track(
                actor=actor,
                verb=verb,
                object=object,
                timestamp=timestamp,
                context=context,
            )
            result['success'] = True
            result['data'] = statement.as_dict()

        results.append(result)

    return HttpResponse(json.dumps({"statements": results}), content_type="application/json")


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using puzzles.Models;

namespace puzzles.Migrations
{
    [DbContext(typeof(PuzzlesDbContext))]
    [Migration("20170515032240_AddTopicsTags")]
    partial class AddTopicsTags
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.1.1");

            modelBuilder.Entity("puzzles.Models.Puzzle", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<string>("Name");

                    b.Property<string>("Tags");

                    b.Property<string>("Topics");

                    b.HasKey("Id");

                    b.ToTable("Puzzles");
                });

            modelBuilder.Entity("puzzles.Models.PuzzleWord", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("PuzzleId");

                    b.Property<string>("Word");

                    b.HasKey("Id");

                    b.HasIndex("PuzzleId");

                    b.ToTable("PuzzleWords");
                });

            modelBuilder.Entity("puzzles.Models.Tag", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<string>("Name");

                    b.HasKey("Id");

                    b.ToTable("Tags");
                });

            modelBuilder.Entity("puzzles.Models.Topic", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Description");

                    b.Property<string>("Name");

                    b.HasKey("Id");

                    b.ToTable("Topics");
                });

            modelBuilder.Entity("puzzles.Models.PuzzleWord", b =>
                {
                    b.HasOne("puzzles.Models.Puzzle")
                        .WithMany("PuzzleWords")
                        .HasForeignKey("PuzzleId");
                });
        }
    }
}


text:
#include "cdmi.h"

#include "logging.h"
#include "util/base64.h"

#include <boost/crc.hpp>

#include <iomanip>
#include <iostream>

namespace one {
namespace client {
namespace util {
namespace cdmi {

/**
 * Converts a base16 encoded number passed as string to an ASCII string
 */
std::string hexstr2str(const std::string &hexstr)
{
    auto len = hexstr.length();
    std::string out;
    out.reserve(len / 2);
    constexpr auto kHexBase = 16U;
    for (auto i = 0UL; i < len; i += 2) {
        std::string hexByte = hexstr.substr(i, 2);
        out.push_back(static_cast<char>(stoi(hexByte, nullptr, kHexBase)));
    }
    return out;
}

std::string objectIdToUUID(const std::string &objectId)
{
    auto objectIdBytes = hexstr2str(objectId);

    const auto kCDMIObjectIDDataOffset = 8U;

    std::string result;
    base64::base64_url_encode(
        objectIdBytes.substr(kCDMIObjectIDDataOffset), result);
    return result;
}

std::string uuidToObjectId(const std::string &input)
{
    std::string decodedUuid;
    base64::base64_decode(input, decodedUuid);

    const uint32_t enterpriseNumber = 0;
    const auto kCDMIObjectIDSize = 64;

    /*
     * Build an object ID given an enterprise number and data as a
     * binary. We ensure here that the Data is not more than 32 bytes. The
     * object ID is composed of a number of fields:
     *
     * +----------+------------+-----------+--------+-------+-----------+
     * |     0    | 1 | 2 | 3  |     4     |   5    | 6 | 7 | 8 |..| 39 |
     * +----------+------------+-----------+--------+-------+-----------+
     * | Reserved | Enterprise | Reserverd | Length |  CRC  | Opaque    |
     * | (zero)   | Number     | (zero)    |        |       | Data      |
     * +----------+------------+-----------+--------+-------+-----------+
     */
    std::vector<uint8_t> objectId;
    objectId.reserve(kCDMIObjectIDSize);

    // Reserved
    objectId.push_back(0);

    // Enterprise number
    objectId.push_back((0x00FFFFFF & enterpriseNumber) >> 16); // NOLINT
    objectId.push_back((0x0000FFFF & enterpriseNumber) >> 8);  // NOLINT
    objectId.push_back(0x0000FF & enterpriseNumber);           // NOLINT

    // Reserved
    objectId.push_back(0);

    if (decodedUuid.size() > 255) // NOLINT
        throw std::runtime_error(
            "Input too long to encode as CDMI Object ID: " + decodedUuid);

    // Length
    objectId.push_back(decodedUuid.size());

    // CRC
    // At first set to 0x0000 - then replace with CRC of entire message
    objectId.push_back(static_cast<uint8_t>(0));
    objectId.push_back(static_cast<uint8_t>(0));

    // Opaque data
    for (char &c : decodedUuid)
        objectId.push_back(static_cast<uint8_t>(c));

    // The CDMI specification requires a CRC field as part of the object
    // ID. The CRC algorithim specified has the following parameters:
    // -- Name: "CRC-16"
    // -- Width: 16
    // -- Poly: 0x8005
    // -- Init: 0x0000
    // -- RefIn: True
    // -- RefOut: True
    // -- XorOut: 0x0000
    // -- Check: 0xBB3D
    const auto kCRCWidth = 16U;
    const auto kCRCPoly = 0x8005;
    boost::crc_optimal<kCRCWidth, kCRCPoly, 0, 0, true, true> crc16;
    crc16.process_bytes(objectId.data(), objectId.size());
    objectId[6] = static_cast<uint8_t>(crc16.checksum() >> 8);   // NOLINT
    objectId[7] = static_cast<uint8_t>(crc16.checksum() & 0xFF); // NOLINT

    // Convert to Base 16
    std::stringstream ss;
    for (uint8_t &b : objectId)
        ss << n2hexstr(b);

    return ss.str();
}
} // namespace cdmi
} // namespace util
} // namespace client
} // namespace one


text:
/**
 * (created at 2011-1-23)
 */
package org.opencloudb.paser.ast.expression.function.datetime;

import java.util.List;

import org.opencloudb.paser.ast.expression.Expression;
import org.opencloudb.paser.ast.expression.function.FunctionExpression;

/**
 * @author mycat
 */
public class UtcTimestamp extends FunctionExpression {
    public UtcTimestamp(List<Expression> arguments) {
        super("UTC_TIMESTAMP", arguments);
    }

    @Override
    public FunctionExpression constructFunction(List<Expression> arguments) {
        return new UtcTimestamp(arguments);
    }

}


text:
KesselRun
=========

~~A simple web-based http(s)/ftp management server for NAS boxes.~~

This project didn't pan out, but it's a cool name so I'm keeping the repo.


text:
package org.skfiy.maven.plugin.fastconfig;

import org.skfiy.maven.plugin.fastconfig.model.ConfigFile;
import org.skfiy.maven.plugin.fastconfig.model.Replacement;
import org.skfiy.maven.plugin.fastconfig.model.Fastconfig;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import java.io.File;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.PluginParameterExpressionEvaluator;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

/**
 * 配置资源文件插件.
 *
 * @author Kevin Zou <kevinz@skfiy.org>
 */
@Mojo(name = "configure", defaultPhase = LifecyclePhase.PREPARE_PACKAGE)
public class FastconfigMojo extends AbstractMojo {

    /**
     * fast-config.xml文件.
     */
    @Parameter(required = true)
    private File config;
    /**
     * 目标文件的编码.
     */
    @Parameter(required = true, readonly = true, defaultValue = "${project.build.sourceEncoding}")
    private String encoding;
    /**
     * 资源文件的输出目录.
     */
    @Parameter(readonly = true, defaultValue = "${project.build.outputDirectory}")
    private File outputDirectory;

    @Parameter(readonly = true, defaultValue = "${session}")
    private MavenSession session;
    @Parameter(readonly = true, defaultValue = "${mojo}")
    private MojoExecution execution;

    @Override
    public void execute() throws MojoExecutionException {
        if (config == null || !config.exists()) {
            getLog().warn("no fast-config file is provided, skipping running.");
        }

        Fastconfig fastconfig;
        try {
            fastconfig = buildFastconfig();
        } catch (Exception e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }

        BasicProcessor processor = new BasicProcessor(encoding);
        for (ConfigFile cf : fastconfig.getConfigFiles()) {
            if (processor.isSupported(cf.getFile())) {
                processor.process(cf);
            }
        }
    }

    private Fastconfig buildFastconfig() throws Exception {
        PluginParameterExpressionEvaluator pel = new PluginParameterExpressionEvaluator(session, execution);
        Fastconfig fastconfig = new Fastconfig();

        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(config);
        Element root = doc.getRootElement();

        // config-file
        for (Element cf : root.getChildren()) {
            String path = String.valueOf(pel.evaluate(cf.getAttributeValue("path")));
            File file = new File(path);
            if (!file.isAbsolute()) {
                file = new File(outputDirectory, path);
            }

            ConfigFile.Mode mode;
            if (StringUtils.isNotEmpty(cf.getAttributeValue("mode"))) {
                mode = ConfigFile.Mode.valueOf(cf.getAttributeValue("mode"));
            } else {
                mode = toMode(path.substring(path.lastIndexOf(".") + 1));
            }

            if (mode == null) {
                throw new FastconfigException("Not found file[" + path + "] replace mode");
            }

            ConfigFile configFile = new ConfigFile(file, mode);
            // replacement
            for (Element rt : cf.getChildren()) {
                String expression = rt.getAttributeValue("expression");
                String value = String.valueOf(pel.evaluate(rt.getTextTrim()));
                configFile.addReplacement(new Replacement(expression, value));
            }
            fastconfig.addConfigFile(configFile);
        }
        return fastconfig;
    }

    private ConfigFile.Mode toMode(String suffix) {
        if ("xml".equals(suffix)) {
            return ConfigFile.Mode.xpath;
        } else if ("json".equals(suffix)) {
            return ConfigFile.Mode.jsonpath;
        } else if ("properties".equals(suffix)) {
            return ConfigFile.Mode.property;
        }
        return null;
    }

}


text:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const basePath = path.resolve(__dirname, '../../');

module.exports = {
  entry: {
    site: path.join(basePath, 'site')
  },
  output: {
    path: path.resolve(basePath, 'dist/site'),
    chunkFilename: '[chunkhash:12].js',
    filename: '[chunkhash:12].js'
  },
  optimization: {
    minimize: true
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[chunkhash:12].css'
    }),
    new HtmlWebpackPlugin({
      template: './index.html',
      favicon: path.join(basePath, 'site/assets/favicon.ico')
    })
  ].concat(process.env.TRAVIS_CI ? [] : [
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
    new webpack.optimize.ModuleConcatenationPlugin()
  ]),
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [{
      test: /\.jsx?$/,
      loader: 'babel-loader',
      include: [
        path.join(basePath, 'site'),
        path.join(basePath, 'src'),
        path.join(basePath, 'libs')
      ]
    }, {
      test: /\.css$/,
      use: [MiniCssExtractPlugin.loader, "css-loader"]
    }, {
      test: /\.scss$/,
      use: ['style-loader', 'css-loader', 'sass-loader']
    }, {
      test: /\.(ttf|eot|svg|woff|woff2)(\?.+)?$/,
      loader: 'file-loader?name=[hash:12].[ext]'
    }, {
      test: /\.(jpe?g|png|gif)(\?.+)?$/,
      loader: 'url-loader?name=[hash:12].[ext]&limit=25000'
    }, {
      test: /\.md$/,
      loader: 'raw-loader'
    }]
  },
  mode: 'production'
};


text:
from __future__ import division

import json
import os
import pickle
import pprint
import nltk

import patterny.semafor.frame as _frame
from patterny.config import Config
from patterny.ml.tmodel import TopicModel
from patterny.semafor.adapter import SemaforClient
from test_main import PatternyTest
from utils import SCRIPT_FOLDER, KDE_DATASET
from time import time
from patterny.nlp.ne import lemmatize_ngram
from patterny.nlp.ne import NOUN, VERB, NOUN_VERB
from nltk.corpus import stopwords as _stopwords
STOPWORDS = set(_stopwords.words('english'))

def tag_sentences(txt):
    sentences = nltk.sent_tokenize(txt)
    sentences = [nltk.word_tokenize(sent) for sent in sentences]
    tagged_sentences = [nltk.pos_tag(sent) for sent in sentences]
    return tagged_sentences

def extract_entities(document, chunk_pattern, labels):
    chunks = set()

    for sentence in document:
        tree = chunk_pattern.parse(sentence)
        for subtree in tree.subtrees():
            # print subtree.label()
            if subtree.label() in labels:
                leaves = tuple(subtree.leaves())
                chunks = chunks.union(set(leaves))

    result = [lemmatize_ngram(word, tag) for word, tag in chunks]
    result = list(filter(lambda word: word not in STOPWORDS, result))
    return result

class TestDatasetSimilarity(PatternyTest):
    def setup(self):
        self.pp = pprint.PrettyPrinter(indent=2)
        self.base_url = 'https://bugs.kde.org/show_bug.cgi?id={}'
        with open(KDE_DATASET) as f:
            self.config = Config(f)
            self.client = SemaforClient(self.config)

    def teardown(self):
        pass

    def test_script(self):
        t0 = time()
        print 'Starting test script'

        semafor_frames_file = os.path.join(SCRIPT_FOLDER, 'semafor_new_analysis.json')
        with open(semafor_frames_file, 'rb') as data:
            bug_semafor_map = json.load(data)

        # # first example
        # test_ids = ['256397', '103266', '112958', '244091']
        # self.similarity_for(bug_semafor_map, test_ids)
        #
        # #  second example
        # test_ids = ['344376', '349681', '330782', '349619', '331159']
        # self.similarity_for(bug_semafor_map, test_ids)

        # Real data
        test_ids = bug_semafor_map.keys()
        self.similarity_for(bug_semafor_map, test_ids)
        print
        print "done in %0.3fs." % (time() - t0)

    def similarity_for(self, bug_semafor_map, test_ids):
        similarity_file = os.path.join(SCRIPT_FOLDER, 'similar_bugs_matrix.sav')
        # result = self.build_semafor_similarity_matrix(bug_semafor_map, test_ids)
        # pickle.dump(result, open(similarity_file, 'wb'))

        t0 = time()
        print '  Loading semafor similarity matrix'
        result = pickle.load(open(similarity_file, 'rb'))
        print "  >> done in %0.3fs." % (time() - t0)
        similar_bugs_map = self.build_bug_similar_sentences_map(result, test_ids)

        new_similar_bugs_map = self.refine_similar_bugs(similar_bugs_map)

        similar_bug_analysis_file = os.path.join(SCRIPT_FOLDER, 'similar_bug_analysis.json')
        with open(similar_bug_analysis_file, 'w') as outfile:
            json.dump(new_similar_bugs_map, outfile, indent=4, sort_keys=True)

    @staticmethod
    def refine_similar_bugs(similar_bugs_map):
        t0 = time()
        print '  Refining similar bugs with nouns/verbs'

        noun_grammar = r"""
                    NP: {<NN>}   # noun
                        {<NNP>+} # proper nouns
                """
        noun_chunk_pattern = nltk.RegexpParser(noun_grammar)

        delete_ids = []
        for i, bug_id in enumerate(sorted(similar_bugs_map.keys())):
            print '  {}. Processing :: {}'.format(i, bug_id)
            current_bug = similar_bugs_map[bug_id]
            non_overlapping = []
            to_remove = []
            new_ids, new_sentences = TestDatasetSimilarity.filter_analysis_of(
                current_bug, non_overlapping, noun_chunk_pattern, to_remove)

            if not new_ids or not new_sentences:
                delete_ids.append(bug_id)
            else:
                current_bug['ids'] = new_ids
                current_bug['sentences'] = new_sentences

        print 'Pre-processed bugs in dataset :: {}'.format(len(similar_bugs_map.keys()))

        for bug_id in delete_ids:
            del similar_bugs_map[bug_id]

        print 'Number of similar bugs in dataset :: {}'.format(len(similar_bugs_map.keys()))

        print "  >> done in %0.3fs." % (time() - t0)
        return similar_bugs_map

    @staticmethod
    def filter_analysis_of(current_bug, non_overlapping, noun_chunk_pattern, to_remove):
        for j, analysis in enumerate(current_bug['sentences']):
            bug_id_similar = analysis['id']
            sentence = analysis['idx_i']
            similar_to = analysis['idx_j']

            d1 = tag_sentences(sentence)
            d2 = tag_sentences(similar_to)

            #  do the same with NOUNS
            d1_nouns = extract_entities(d1, noun_chunk_pattern, ['NP'])
            d2_nouns = extract_entities(d2, noun_chunk_pattern, ['NP'])

            overlap = list(set(d1_nouns).intersection(set(d2_nouns)))
            if not overlap:
                non_overlapping.append(j)
                to_remove.append(bug_id_similar)

        new_sentences = []
        for j, analysis in enumerate(current_bug['sentences']):
            if j not in non_overlapping:
                new_sentences.append(analysis)
        new_ids = []
        for id in current_bug['ids']:
            if id not in to_remove:
                new_ids.append(id)

        return new_ids, new_sentences

    @staticmethod
    def build_bug_similar_sentences_map(result, test_ids):
        t0 = time()
        print '  Creating json map'
        similar_bugs_map = {}
        count = 0
        output_file = os.path.join(SCRIPT_FOLDER, 'similar_bugs_map.json')
        for i, row in enumerate(result):
            similar = [(j, value) for j, value in enumerate(row) if j != i and value is not None]
            if similar:
                count += 1

                id_i = int(test_ids[i])

                if id_i not in similar_bugs_map:
                    similar_bugs_map[id_i] = dict(ids=[], sentences=[])

                for j, value in similar:
                    sentence_i = value[0]
                    sentence_j = value[1]

                    if j != i:
                        id_j = int(test_ids[j])
                        if id_j not in similar_bugs_map:
                            similar_bugs_map[id_j] = dict(ids=[], sentences=[])

                        if id_j not in similar_bugs_map[id_i]['ids']:
                            similar_bugs_map[id_i]['ids'].append(id_j)
                            similar_bugs_map[id_i]['sentences'].append(
                                dict(id=id_j, idx_i=sentence_i, idx_j=sentence_j)
                            )

                        if id_i not in similar_bugs_map[id_j]['ids']:
                            similar_bugs_map[id_j]['ids'].append(id_i)
                            similar_bugs_map[id_j]['sentences'].append(
                                dict(id=id_i, idx_i=sentence_j, idx_j=sentence_i)
                            )
        print "  >> done in %0.3fs." % (time() - t0)
        print
        print 'Number of similar bugs in dataset :: {}'.format(len(similar_bugs_map.keys()))
        print
        with open(output_file, 'w') as outfile:
            json.dump(similar_bugs_map, outfile, indent=4, sort_keys=True)

        return similar_bugs_map

    @staticmethod
    def build_semafor_similarity_matrix(bug_semafor_map, test_ids):
        result = []
        for i in xrange(0, len(test_ids)):
            print i
            row = []
            for j in xrange(0, len(test_ids)):
                if i == j:
                    row.append(1)
                else:
                    bug_i = bug_semafor_map[test_ids[i]]
                    bug_j = bug_semafor_map[test_ids[j]]

                    similar = _frame.similar(bug_i, bug_j, threshold=0.35)
                    if similar:
                        sentence_i = bug_i['sentences'][similar[0]]
                        sentence_j = bug_j['sentences'][similar[1]]
                        row.append((sentence_i, sentence_j))
                    else:
                        row.append(None)

            result.append(row)
        return result

    @staticmethod
    def id_of(url):
        return url.replace('https://bugs.kde.org/show_bug.cgi?id=', '')


text:
"""
File timerdeco-test.py
"""
from __future__ import print_function # 2.X
from timerdeco import timer
import sys
force = list if sys.version_info[0] == 3 else (lambda X: X)

print('---------------------------------------------------')
# Test on functions

@timer(trace=True, label='[CCC]==>')
def listcomp(N):                             # Like listcomp = timer(...)(listcomp)
    return [x * 2 for x in range(N)]         # listcomp(...) triggers onCall

@timer('[MMM]==>')
def mapcall(N):
    return force(map((lambda x: x * 2), range(N)))   # list() for 3.X views

for func in (listcomp, mapcall):
    result = func(5)                  # Time for this call, all calls, return value
    func(5000000)
    print(result)
    print('allTime = %s\n' % func.alltime)   # Total time for all calls

print('---------------------------------------------------')
# Test on methods

class Person:
    def __init__(self, name, pay):
        self.name = name
        self.pay  = pay

    @timer()
    def giveRaise(self, percent):            # giveRaise = timer()(giveRaise)
        self.pay *= (1.0 + percent)          # tracer remembers giveRaise

    @timer(label='**')
    def lastName(self):                      # lastName = timer(...)(lastName)
        return self.name.split()[-1]         # alltime per class, not instance

bob = Person('Bob Smith', 50000)
sue = Person('Sue Jones', 100000)
bob.giveRaise(.10)
sue.giveRaise(.20)                           # runs onCall(sue, .10)
print(int(bob.pay), int(sue.pay))
print(bob.lastName(), sue.lastName())        # runs onCall(bob), remembers lastName
print('%.5f %.5f' % (Person.giveRaise.alltime, Person.lastName.alltime))


text:
```cpp
int rank() const;
```

Returns the local processor id

## Return value

- `int`: The id of the local processor.


text:
package ws.ament.hammock.jpa.hibernate;

import javax.persistence.*;

@Entity
@Table(name="uuid_entities")
public class UUIDEntity {
    @Id
    @GeneratedValue(generator = "customer-registered")
    @Column(name = "uuid", unique = true)
    private String uuid;

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}


text:
package com.marcinjasinski.sshpasswords.web.form.app.position;

import com.marcinjasinski.sshpasswords.core.enums.AttackMethod;

/**
 * Class AddPositionForm
 *
 * @author Marcin Jasiński {@literal <mkjasinski@gmail.com>}
 */
public class AddPositionForm {

    private AttackMethod attackMethod;

    private String ip;

    private Integer port;

    private String username;

    public AddPositionForm() {
    }

    public AttackMethod getAttackMethod() {
        return attackMethod;
    }

    public void setAttackMethod(AttackMethod attackMethod) {
        this.attackMethod = attackMethod;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "AddPositionForm{" +
               "attackMethod=" + attackMethod +
               ", ip='" + ip + '\'' +
               ", port=" + port +
               ", username='" + username + '\'' +
               '}';
    }
}


text:
require_relative 'printable'
require_relative 'writable'
require_relative 'todo_item'
require_relative 'todo_category'
require 'yaml'

class TodoList < Writable
  def initialize
    @title = stored_list["title"]
    @body = list
  end

  def list
    out = []
    stored_list["categories"].each do |name, category|
      out << TodoCategory.new(name, *category["items"])
    end
    out
  end

  def stored_list
    YAML.load_file('data/todo.yml')["list"]
  end

  def print_body
    @body.map(&:print)
  end
end


text:
from datetime import date

from EPPs.common import StepEPP

class PopulateBatchID(StepEPP):
#CST batch ID has the format YY-MM-DD_CST_Batch#{1-9}{1,3} where {1-9}{1,3} represents the next available number for
#that date. Assigns the Adapter Type and Prep Workflow udfs for all output analytes

    def create_cst_batch_id(self):
        today = str(date.today())
        name_template = today + '_CST_Batch#%d'
        # find next available batch id and use range limit to prevent infinite loop
        for batch_count in range(1, 999):
            new_batch_name = name_template % batch_count
            if not self.lims.get_containers(name=new_batch_name):
                return new_batch_name
        raise ValueError('Cannot allocate more than 999 cst batch IDs with date %s ' % today)

    def _run(self):
        # assign CST Batch ID
        self.process.analytes()[0][0].container.name = self.create_cst_batch_id()
        self.process.analytes()[0][0].container.put()
        #assing Adapter Type and Prep Workflow UDFs for all output analytes
        # assumes input artifacts have already been checked to allow only 1 adapter type
        adapter_type = self.lims.get_reagent_types(name=self.process.all_inputs()[0].reagent_labels[0])[0].category
        # assumes input artifacts have already been checked to allow only 1 library type at beginning of step
        prep_workflow = self.process.all_inputs()[0].samples[0].udf['Prep Workflow']
        # Name all pools and assign the prep workflow and adapter type to them then put into LIMS
        for i_art in self.artifacts:
            for o_art in self.process.outputs_per_input(i_art.id, Analyte=True):
                o_art.udf['Prep Workflow'] = prep_workflow
                o_art.udf['Adapter Type'] = adapter_type
                o_art.put()

if __name__ == "__main__":
    PopulateBatchID().run()


text:
A Machine Learning project implemented for the Artificial Intelligence Society DataSci '17 competition. The UCI Student Performance Data Set was used to effectively predict if a student is expected to fail the course or not, using school reports and questionnaires. Different classification models were compared. The best model, Logistic Regression achieved about 70% accuracy.

### Prerequisites

This project requires Python 3.4 and the following Python libraries installed:

- [Pandas](http://pandas.pydata.org/)
- [scikit-learn](http://scikit-learn.org/stable/)

## Install

On Unix systems, the above libraries can be installed using these (or corresponding ones for your distribution) commands,

```
sudo apt-get install build-essential python3-dev python3-setuptools python3-numpy python3-scipy libatlas-dev libatlas3gf-base

sudo apt-get install python3-pip

sudo -H pip3 install -U scikit-learn

sudo -H pip3 install pandas
```

## Observations and Evaluating Criterions

### 1. In which class of problems, does this qualify?

This is a classification problem. The reason for terming it as a classification problem being, we are asked to identify students who might end up failing the final exam.

Thus, we need to identify such students and intervene before it's too late. Or in other words, we have to classify the whole group of students into two sections - Ones who are expected to fail the course and others who are expected to pass the course.

### 2. Observations from Given Data

- Total number of students: 395
- Total number of features: 30
- Target: 1 ("passed")
- Number of students who passed: 265
- Number of students who failed: 130
- Number of columns with numeral values: 13

### 3. What are the features and Relevant Target?

```
Feature column(s):-
['school', 'sex', 'age', 'address', 'famsize', 'Pstatus', 'Medu', 'Fedu', 'Mjob', 'Fjob', 'reason',
 'guardian', 'traveltime', 'studytime', 'failures', 'schoolsup', 'famsup', 'paid', 'activities', 'nursery',
 'higher', 'internet', 'romantic', 'famrel', 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences']

Target column: passed
```

### 4. Which is the best model to use?

```

Support Vector Machine - Linear

Total execution time: 23.7 milliseconds
Accuracy is 69.62%

Support Vector Machine - Polynomial

Total execution time: 478.0 milliseconds
Accuracy is 63.92%

Support Vector Machine - Radial Basis Function

Total execution time: 8.7 milliseconds
Accuracy is 66.46%

Logistic Regression

Total execution time: 2.7 milliseconds
Accuracy is 69.62%

Decision Tree

Total execution time: 1.7 milliseconds
Accuracy is 56.33%

Random Forest

Total execution time: 201.7 milliseconds
Accuracy is 69.62%

Random Forest (Optimised)

Total execution time: 47.6 milliseconds
Accuracy is 63.29%

```

Based on the statistics obtained, Logistic Regression provides the best performance and also in the least time.

The other models didn't perform well in comparison with Logistic regression. Though Logistic Regression appears to be a clear winner in both measures used to decide the best model i.e. performance and training and testing time, I would've still chosen to trade off the training time for the higher performance. The reason being that failing a course in school can have some adverse effect on the mental and psychological health of the student, making accuracy a dominant factor in comparing different models.

Thus, as the predictions need to be very accurate, we would have to value the accuracy more as compared to training and testing time.

## Appendix

Attributes for Data Set along with the DataSet itself can be found at [UCI ML Repository](https://archive.ics.uci.edu/ml/datasets/Student+Performance)

## Author

* **Pranav Dixit** - [Github](https://github.com/prnvdixit) - [Linkedin](https://www.linkedin.com/in/prnvdixit/)

## License

This project is licensed under the MIT License - see the [LICENSE.md](https://github.com/prnvdixit/Stinsight/blob/master/LICENSE.md) file for details

## Acknowledgments

* Paulo Cortez - For making the Data Set public by donating it to the UCI ML Repository.


text:
package org.elasticsoftware.sip.codec;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.handler.codec.embedder.EncoderEmbedder;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Tests for encoding (outgoing) SIP Request
 * <p/>
 * http://biasedbit.com/netty-tutorial-replaying-decoder/
 *
 * @author Leonard Wolters
 */
public class SipResponseEncoderTest extends AbstractSipTest {

    @Test
    public void testMessageBadRequest() throws Exception {
        testMessageBadRequest(new SipResponseImpl(SipVersion.SIP_2_0, SipResponseStatus.BAD_REQUEST));
    }

    protected void testMessageBadRequest(SipMessage msg) {
        SipMessageEncoder encoder = new SipMessageEncoder();
        EncoderEmbedder<ChannelBuffer> embedder = new EncoderEmbedder<ChannelBuffer>(encoder);
        embedder.offer(msg);

        ChannelBuffer buffer = embedder.poll();
        Assert.assertEquals("SIP/2.0 400 Bad Request", buffer.toString(SipMessageEncoder.charSet).trim());
    }

    @Test
    public void testHeaders() throws Exception {
        testHeaders(new SipResponseImpl(SipVersion.SIP_2_0, SipResponseStatus.OK));
    }

    protected void testHeaders(SipResponse msg) throws Exception {
        msg.addHeader(SipHeader.VIA, "SIP/2.0/UDP server10.biloxi.com\n ;branch=z9hG4bKnashds8;received=192.0.2.3");
        msg.addHeader(SipHeader.VIA, "SIP/2.0/UDP bigbox3.site3.atlanta.com\n ;branch=z9hG4bK77ef4c2312983.1;received=192.0.2.2");
        msg.addHeader(SipHeader.VIA, "SIP/2.0/UDP pc33.atlanta.com\n ;branch=z9hG4bK776asdhds ;received=192.0.2.1");
        msg.addHeader(SipHeader.TO, "Bob <sip:bob@biloxi.com>;tag=a6c85cf");
        msg.addHeader(SipHeader.FROM, "Alice <sip:alice@atlanta.com>;tag=1928301774");
        msg.addHeader(SipHeader.CALL_ID, "a84b4c76e66710@pc33.atlanta.com");
        msg.addHeader(SipHeader.CSEQ, "314159 INVITE");
        msg.addHeader(SipHeader.CONTACT, "<sip:bob@192.0.2.4>");
        msg.addHeader(SipHeader.CONTENT_TYPE, "application/sdp");
        msg.addHeader(SipHeader.CONTENT_LENGTH, "131");

        SipMessageEncoder encoder = new SipMessageEncoder();
        EncoderEmbedder<ChannelBuffer> embedder = new EncoderEmbedder<ChannelBuffer>(encoder);
        embedder.offer(msg);

        ChannelBuffer buffer = embedder.poll();
        String content = prepare(getFileContent("bob_ack_invite.txt", SipMessageEncoder.charSet));
        String generated = prepare((buffer.toString(SipMessageEncoder.charSet)));
        Assert.assertTrue(checkCharacters(content, generated));
        Assert.assertEquals(content.trim(), generated.trim());
    }
}


text:
package com.google.cloud.compute.v1;

import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;

@Generated("by GAPIC")
@BetaApi
/**
 * Information for an interconnect attachment when this belongs to an interconnect of type
 * DEDICATED.
 */
public final class InterconnectAttachmentPrivateInfo implements ApiMessage {
  private final Integer tag8021q;

  private InterconnectAttachmentPrivateInfo() {
    this.tag8021q = null;
  }

  private InterconnectAttachmentPrivateInfo(Integer tag8021q) {
    this.tag8021q = tag8021q;
  }

  @Override
  public Object getFieldValue(String fieldName) {
    if ("tag8021q".equals(fieldName)) {
      return tag8021q;
    }
    return null;
  }

  @Nullable
  @Override
  public ApiMessage getApiMessageRequestBody() {
    return null;
  }

  @Nullable
  @Override
  /**
   * The fields that should be serialized (even if they have empty values). If the containing
   * message object has a non-null fieldmask, then all the fields in the field mask (and only those
   * fields in the field mask) will be serialized. If the containing object does not have a
   * fieldmask, then only non-empty fields will be serialized.
   */
  public List<String> getFieldMask() {
    return null;
  }

  /**
   * [Output Only] 802.1q encapsulation tag to be used for traffic between Google and the customer,
   * going to and from this network and region.
   */
  public Integer getTag8021q() {
    return tag8021q;
  }

  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

  public static Builder newBuilder(InterconnectAttachmentPrivateInfo prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }

  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
  }

  public static InterconnectAttachmentPrivateInfo getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final InterconnectAttachmentPrivateInfo DEFAULT_INSTANCE;

  static {
    DEFAULT_INSTANCE = new InterconnectAttachmentPrivateInfo();
  }

  public static class Builder {
    private Integer tag8021q;

    Builder() {}

    public Builder mergeFrom(InterconnectAttachmentPrivateInfo other) {
      if (other == InterconnectAttachmentPrivateInfo.getDefaultInstance()) return this;
      if (other.getTag8021q() != null) {
        this.tag8021q = other.tag8021q;
      }
      return this;
    }

    Builder(InterconnectAttachmentPrivateInfo source) {
      this.tag8021q = source.tag8021q;
    }

    /**
     * [Output Only] 802.1q encapsulation tag to be used for traffic between Google and the
     * customer, going to and from this network and region.
     */
    public Integer getTag8021q() {
      return tag8021q;
    }

    /**
     * [Output Only] 802.1q encapsulation tag to be used for traffic between Google and the
     * customer, going to and from this network and region.
     */
    public Builder setTag8021q(Integer tag8021q) {
      this.tag8021q = tag8021q;
      return this;
    }

    public InterconnectAttachmentPrivateInfo build() {
      return new InterconnectAttachmentPrivateInfo(tag8021q);
    }

    public Builder clone() {
      Builder newBuilder = new Builder();
      newBuilder.setTag8021q(this.tag8021q);
      return newBuilder;
    }
  }

  @Override
  public String toString() {
    return "InterconnectAttachmentPrivateInfo{" + "tag8021q=" + tag8021q + "}";
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o instanceof InterconnectAttachmentPrivateInfo) {
      InterconnectAttachmentPrivateInfo that = (InterconnectAttachmentPrivateInfo) o;
      return Objects.equals(this.tag8021q, that.getTag8021q());
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(tag8021q);
  }
}


text:
(function () {
    // Controller
    function analyzerSelectorController($scope, analyzeService) {
        analyzeService.GetStructure()
            .then(function (response) {
                $scope.analyzerSummaries = response;
                $scope.load();
                $scope.loading = false;
            },
            function (message) {
                $scope.error = message;
                $scope.loading = false;
            });

        $scope.load = function () {
            var tempObject = [];
            var firstTime = false;
            if (!$scope.model.value) {
                $scope.model.value = [];
                firstTime = true;
            }

            angular.forEach($scope.analyzerSummaries,
                function (analyzerSummary) {
                    var analyzerSummaryObject = _.findWhere($scope.model.value, { name: analyzerSummary.Name });

                    if (!analyzerSummaryObject) {
                        analyzerSummaryObject = {
                            name: analyzerSummary.Name,
                            checked: firstTime,
                            analyzers: []
                        };
                    }
                    angular.forEach(analyzerSummary.Analyzers,
                        function (analyzer) {
                            var analyzerObject = _.findWhere(analyzerSummaryObject.analyzers, { name: analyzer });

                            if (!analyzerObject) {
                                analyzerObject = {
                                    name: analyzer,
                                    checked: firstTime
                                }
                                analyzerSummaryObject.analyzers.push(analyzerObject);
                            }
                        });

                    tempObject.push(analyzerSummaryObject);
                });

            $scope.model.value = tempObject;
        }
    }

    // Register the controller
    angular.module("umbraco").controller('analyzerSelectorController', analyzerSelectorController);
})();


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>T826813186007408640</title>
  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600">
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/custom.css">

	<link rel="shortcut icon" href="https://micro.blog/curt/favicon.png" type="image/x-icon" />
  <link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.xml" />

  <link rel="alternate" type="application/json" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.json" />
  <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" />

  <link rel="me" href="https://micro.blog/curt" />

  	<link rel="me" href="https://twitter.com/curtclifton" />

  <link rel="authorization_endpoint" href="https://micro.blog/indieauth/auth" />
  <link rel="token_endpoint" href="https://micro.blog/indieauth/token" />
  <link rel="micropub" href="https://micro.blog/micropub" />
  <link rel="webmention" href="https://micro.blog/webmention" />
  <link rel="subscribe" href="https://micro.blog/users/follow" />

    Curt Clifton

    <time class="dt-published" datetime="2017-02-01 07:23:19 -0800">01 Feb 2017</time>

Eliot A. Cohen Responds to Donald Trump's First Week - The Atlantic https://t.co/YvT1Ijw3y2