text:
"""%(prog)s is a command to manipulate ROS workspaces. %(prog)s replaces its predecessor rosinstall.

Official usage:
  %(prog)s CMD [ARGS] [OPTIONS]

%(prog)s will try to infer install path from context

Type '%(prog)s help' for usage.
"""

from __future__ import print_function
import os
import sys
import yaml

from optparse import OptionParser

from wstool.cli_common import get_info_list, get_info_table, \
    get_info_table_raw_csv, get_workspace, ONLY_OPTION_VALID_ATTRS
import rosinstall.rosinstall_cmd as rosinstall_cmd
from wstool.multiproject_cmd import get_config, cmd_install_or_update, \
    cmd_snapshot, cmd_version, cmd_info, cmd_find_unmanaged_repos
import rosinstall.__version__

from wstool.common import MultiProjectException, select_elements
from wstool.helpers import ROSINSTALL_FILENAME
from rosinstall.helpers import get_ros_package_path, get_ros_stack_path
from wstool.multiproject_cli import MultiprojectCLI, __MULTIPRO_CMD_DICT__, \
    __MULTIPRO_CMD_HELP_LIST__, __MULTIPRO_CMD_ALIASES__, \
    IndentedHelpFormatterWithNL, list_usage

## This file adds or extends commands from multiproject_cli where ROS
## specific output has to be generated.

# extend the commands of multiproject
__ROSWS_CMD_DICT__ = {}
__ROSWS_CMD_DICT__.update(__MULTIPRO_CMD_DICT__)
__ROSWS_CMD_DICT__["regenerate"] = "create ROS workspace specific setup files"

__ROSWS_CMD_HELP_LIST__ = __MULTIPRO_CMD_HELP_LIST__[:]
__ROSWS_CMD_HELP_LIST__.extend([None, 'regenerate'])

_PROGNAME = 'rosws'
_VARNAME = 'ROS_WORKSPACE'

class RoswsCLI(MultiprojectCLI):

    def __init__(self, config_filename=ROSINSTALL_FILENAME, progname=_PROGNAME):
        MultiprojectCLI.__init__(self,
                                 progname=progname,
                                 config_filename=config_filename,
                                 allow_other_element=True,
                                 config_generator=rosinstall_cmd.cmd_persist_config)

    def cmd_init(self, argv):
        if self.config_filename is None:
            print('Error: Bug: config filename required for init')
            return 1
        parser = OptionParser(
            usage="""usage: %s init [TARGET_PATH [SOURCE_PATH]]?""" % self.progname,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["init"] + """

%(prog)s init does the following:
  1. Reads folder/file/web-uri SOURCE_PATH looking for a rosinstall yaml
  2. Creates new %(cfg_file)s file at TARGET-PATH
  3. Generates ROS setup files

SOURCE_PATH can e.g. be a folder like /opt/ros/electric
If PATH is not given, uses current dir.

Examples:
$ %(prog)s init ~/fuerte /opt/ros/fuerte
""" % {'cfg_file': self.config_filename, 'prog': self.progname},
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option("-c", "--catkin", dest="catkin", default=False,
                          help="Declare this is a catkin build.",
                          action="store_true")
        parser.add_option("--cmake-prefix-path", dest="catkinpp", default=None,
                          help="Where to set the CMAKE_PREFIX_PATH",
                          action="store")
        parser.add_option("--continue-on-error", dest="robust", default=False,
                          help="Continue despite checkout errors",
                          action="store_true")
        parser.add_option("-j", "--parallel", dest="jobs", default=1,
                          help="How many parallel threads to use for installing",
                          action="store")
        (options, args) = parser.parse_args(argv)
        if len(args) < 1:
            target_path = '.'
        else:
            target_path = args[0]

        if not os.path.isdir(target_path):
            if not os.path.exists(target_path):
                os.mkdir(target_path)
            else:
                print('Error: Cannot create in target path %s ' % target_path)

        if os.path.exists(os.path.join(target_path, self.config_filename)):
            print('Error: There already is a workspace config file %s at "%s". Use %s install/modify.' %
                  (self.config_filename, target_path, self.progname))
            return 1
        if len(args) > 2:
            parser.error('Too many arguments')
        config_uris = []
        if len(args) == 2:
            config_uris.append(args[1])
        if len(config_uris) > 0:
            print('Using ROS_ROOT: %s' % config_uris[0])

        config = get_config(basepath=target_path,
                            additional_uris=config_uris,
                            config_filename=self.config_filename)

        # includes ROS specific files

        print("Writing %s" % os.path.join(config.get_base_path(),
              self.config_filename))
        rosinstall_cmd.cmd_persist_config(config)

        ## install or update each element
        install_success = cmd_install_or_update(
            config,
            robust=False,
            num_threads=int(options.jobs))

        rosinstall_cmd.cmd_generate_ros_files(config,
                                              target_path,
                                              nobuild=True,
                                              rosdep_yes=False,
                                              catkin=options.catkin,
                                              catkinpp=options.catkinpp,
                                              no_ros_allowed=True)

        if not install_success:
            print("Warning: installation encountered errors, but --continue-on-error was requested.  Look above for warnings.")
        print("\nrosinstall update complete.")
        if (options.catkin is False
            and options.catkinpp is None):
            print("\nType 'source %s/setup.bash' to change into this environment. Add that source command to the bottom of your ~/.bashrc to set it up every time you log in.\n\nIf you are not using bash please see http://www.ros.org/wiki/rosinstall/NonBashShells " % os.path.abspath(target_path))
        return 0

    def cmd_regenerate(self, target_path, argv, config=None):
        parser = OptionParser(usage="usage: %s regenerate" % self.progname,
                              formatter=IndentedHelpFormatterWithNL(),
                              description=__MULTIPRO_CMD_DICT__["remove"] + """

this command without options generates files setup.sh, setup.bash and
setup.zsh. Note that doing this is unnecessary in general, as these
files do not change anymore, unless you change from one ROS distro to
another (which you should never do like this, create a separate new
workspace instead), or you deleted or modified any of those files
accidentally.
""",
                              epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option("-c", "--catkin", dest="catkin", default=False,
                          help="Declare this is a catkin build.",
                          action="store_true")
        parser.add_option("--cmake-prefix-path", dest="catkinpp", default=None,
                          help="Where to set the CMAKE_PREFIX_PATH",
                          action="store")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option("-t", "--target-workspace", dest="workspace", default=None,
                          help="which workspace to use",
                          action="store")
        (options, args) = parser.parse_args(argv)
        if len(args) > 0:
            print("Error: Too many arguments.")
            print(parser.usage)
            return -1

        if config is None:
            config = get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException(
                "Config path does not match %s %s " % (config.get_base_path(),
                                                       target_path))
        rosinstall_cmd.cmd_generate_ros_files(config,
                                              target_path,
                                              nobuild=True,
                                              rosdep_yes=False,
                                              catkin=options.catkin,
                                              catkinpp=options.catkinpp,
                                              no_ros_allowed=True)
        return 0

    def cmd_info(self, target_path, argv, reverse=True, config=None):
        # similar to multiproject_cli except shows ros-pkg-path
        # options
        parser = OptionParser(
            usage="usage: %s info [localname]* [OPTIONS]" % self.progname,
            formatter=IndentedHelpFormatterWithNL(),
            description=__MULTIPRO_CMD_DICT__["info"] + """

The Status (S) column shows
 x  for missing
 L  for uncommited (local) changes
 V  for difference in version and/or remote URI
 C  for difference in local and remote versions

The 'Version-Spec' column shows what tag, branch or revision was given
in the .rosinstall file. The 'UID' column shows the unique ID of the
current (and specified) version. The 'URI' column shows the configured
URL of the repo.

If status is V, the difference between what was specified and what is
real is shown in the respective column. For SVN entries, the url is
split up according to standard layout (trunk/tags/branches).  The
ROS_PACKAGE_PATH follows the order of the table, earlier entries
overlay later entries.

When given one localname, just show the data of one element in list form.
This also has the generic properties element which is usually empty.

The --only option accepts keywords: %(opts)s

Examples:
$ %(prog)s info -t ~/ros/fuerte
$ %(prog)s info robot_model
$ %(prog)s info --yaml
$ %(prog)s info --only=path,cur_uri,cur_revision robot_model geometry
""" % {'prog': self.progname, 'opts': ONLY_OPTION_VALID_ATTRS},
            epilog="See: http://www.ros.org/wiki/rosinstall for details\n")
        parser.add_option(
            "--root", dest="show_ws_root", default=False,
            help="Show workspace root path",
            action="store_true")
        parser.add_option(
            "--data-only", dest="data_only", default=False,
            help="Does not provide explanations",
            action="store_true")
        parser.add_option(
            "--no-pkg-path", dest="no_pkg_path", default=False,
            help="Suppress ROS_PACKAGE_PATH.",
            action="store_true")
        parser.add_option(
            "--pkg-path-only", dest="pkg_path_only", default=False,
            help="Shows only ROS_PACKAGE_PATH separated by ':'. Supercedes all other options.",
            action="store_true")
        parser.add_option(
            "--only", dest="only", default=False,
            help="Shows comma-separated lists of only given comma-separated attribute(s).",
            action="store")
        parser.add_option(
            "--yaml", dest="yaml", default=False,
            help="Shows only version of single entry. Intended for scripting.",
            action="store_true")
        parser.add_option(
            "--fetch", dest="fetch", default=False,
            help="When used, retrieves version information from remote (takes longer).",
            action="store_true")
        parser.add_option(
            "-u", "--untracked", dest="untracked",
            default=False,
            help="Also show untracked files as modifications",
            action="store_true")
        # -t option required here for help but used one layer above, see cli_common
        parser.add_option(
            "-t", "--target-workspace", dest="workspace", default=None,
            help="which workspace to use",
            action="store")
        parser.add_option(
            "-m", "--managed-only", dest="unmanaged", default=True,
            help="only show managed elements",
            action="store_false")
        (options, args) = parser.parse_args(argv)

        if config is None:
            config = get_config(
                target_path,
                additional_uris=[],
                config_filename=self.config_filename)
        elif config.get_base_path() != target_path:
            raise MultiProjectException("Config path does not match %s %s " %
                                        (config.get_base_path(), target_path))

        if options.show_ws_root:
            print(config.get_base_path())
            return 0

        if args == []:
            args = None

        if options.pkg_path_only:
            print(":".join(get_ros_package_path(config)))
            return 0
        if options.no_pkg_path:
            header = 'workspace: %s\nROS_ROOT: %s' % (target_path,
                                                      get_ros_stack_path(config))
            print(header)
            return 0
        elif options.only:
            only_options = options.only.split(",")
            if only_options == '':
                parser.error('No valid options given')
            lines = get_info_table_raw_csv(config,
                                           properties=only_options,
                                           localnames=args)
            print('\n'.join(lines))
            return 0
        elif options.yaml:
            source_aggregate = cmd_snapshot(config, localnames=args)
            print(yaml.safe_dump(source_aggregate), end='')
            return 0

        # this call takes long, as it invokes scms.
        outputs = cmd_info(config, localnames=args,
                           untracked=options.untracked,
                           fetch=options.fetch)
        if args and len(args) == 1:
            # if only one element selected, print just one line
            print(get_info_list(config.get_base_path(),
                                outputs[0],
                                options.data_only))
            return 0

        header = 'workspace: %s\nROS_ROOT: %s' % (target_path,
                                                  get_ros_stack_path(config))
        print(header)
        table = get_info_table(config.get_base_path(),
                               outputs,
                               options.data_only,
                               reverse=reverse)
        if table is not None and table != '':
            print("\n%s" % table)

        if options.unmanaged:
            outputs2 = cmd_find_unmanaged_repos(config)
            table2 = get_info_table(config.get_base_path(),
                                   outputs2,
                                   options.data_only,
                                   reverse=reverse,
                                   unmanaged=True)
            if table2 is not None and table2 != '':
                print("\nAlso detected these repositories in the workspace, add using '%s set':\n\n%s" % (self.progname, table2))

        return 0

def rosws_main(argv=None, usage=None):
    """
    Calls the function corresponding to the first argument.

    :param argv: sys.argv by default
    :param usage: function printing usage string, multiproject_cli.list_usage by default
    """
    if argv is None:
        argv = sys.argv
    if (sys.argv[0] == '-c'):
        sys.argv = [_PROGNAME] + sys.argv[1:]
    if '--version' in argv:
        print("%s: \t%s\n%s" %
              (_PROGNAME, rosinstall.__version__.version, cmd_version()))
        sys.exit(0)

    if not usage:
        usage = lambda: print(list_usage(progname=_PROGNAME,
                                         description=__doc__,
                                         command_keys=__ROSWS_CMD_HELP_LIST__,
                                         command_helps=__ROSWS_CMD_DICT__,
                                         command_aliases=__MULTIPRO_CMD_ALIASES__))
    workspace = None
    if len(argv) < 2:
        try:
            workspace = get_workspace(argv,
                                      os.getcwd(),
                                      config_filename=ROSINSTALL_FILENAME,
                                      varname=_VARNAME)
            argv.append('info')
        except MultiProjectException as e:
            print(str(e))
            usage()
            return 0

    if argv[1] in ['--help', '-h']:
        usage()
        return 0

    try:
        command = argv[1]
        args = argv[2:]

        if command == 'help':
            if len(argv) < 3:
                usage()
                return 0

            else:
                command = argv[2]
                args = argv[3:]
                args.insert(0, "--help")
                # help help
                if command == 'help':
                    usage()
                    return 0
        cli = RoswsCLI()

        # commands for which we do not infer target workspace
        commands = {'init': cli.cmd_init}
        # commands which work on a workspace
        ws_commands = {
            'info': cli.cmd_info,
            'remove': cli.cmd_remove,
            'regenerate': cli.cmd_regenerate,
            'set': cli.cmd_set,
            'merge': cli.cmd_merge,
            'foreach': cli.cmd_foreach,
            'scrape': cli.cmd_scrape,
            'diff': cli.cmd_diff,
            'status': cli.cmd_status,
            'update': cli.cmd_update}
        for label in list(ws_commands.keys()):
            alias = __MULTIPRO_CMD_ALIASES__.get(label, None)
            if alias:
                ws_commands[alias] = ws_commands[label]

        if command not in commands and command not in ws_commands:
            if os.path.exists(command):
                args = ['-t', command] + args
                command = 'info'
            else:
                if command.startswith('-'):
                    print("First argument must be name of a command: %s" %
                          command)
                else:
                    print("Error: unknown command: %s" % command)
                usage()
                return 1

        if command in commands:
            return commands[command](args)
        else:
            if workspace is None and not '--help' in args and not '-h' in args:
                workspace = get_workspace(args,
                                          os.getcwd(),
                                          config_filename=ROSINSTALL_FILENAME,
                                          varname=_VARNAME)
            return ws_commands[command](workspace, args)

    except KeyboardInterrupt:
        return 1

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import { Provider } from 'react-redux'
import nock from 'nock'
import { mount } from 'enzyme'
import App from '../../../../apps/github-api-sample/containers/App'
import configureStore from '../../../../apps/github-api-sample/store'
import goEuro from '../../../data/github-goeuro-user-snapshot.json'
import assert from 'assert'

describe('<App />', () => {
  afterEach(() => nock.cleanAll())

  let wrapper
  let findForm
  let userTextInput

  beforeEach(() => {
    const store = configureStore()
    wrapper = mount(<Provider store={store}><App /></Provider>)

    // i agree it should be way easier to change an input's value, but the airbnb guys don't
    // you should be able to test the highest level component (i.e. container components don't have props and they live at the highest point)
    // w/o hassle resorting to props or state IMO
    //
    // https://github.com/airbnb/enzyme/issues/76#issuecomment-189606849 is legit
    userTextInput = wrapper.find('form input[type="text"]')
    findForm = wrapper.find('form')
  })

  describe('when the user does not exist', () => {
    before(() => {
      nock('https://api.github.com')
        .get('/users/goeuro-2012/repos?sort=created')
        .reply(404)
    })

    it('should display a message saying "User not found."', (done) => {
      userTextInput.simulate('change', { target: { value: 'goeuro-2012' } });
      findForm.simulate('submit')

      const loading = wrapper.find('.request-status')

      assert.equal(loading.text(), 'Loading...')

      setTimeout(() => {
        assert.equal(loading.text(), 'User not found.')

        done()
      }, 100)
    })
  })

  describe('when an unexpected error occurs', () => {
    before(() => {
      nock('https://api.github.com')
        .get('/users/goeuro-2012/repos?sort=created')
        .reply(500)
    })

    it('should display a message saying "An unexpected error occurred."', (done) => {
      userTextInput.simulate('change', { target: { value: 'goeuro-2012' } });
      findForm.simulate('submit')

      const loading = wrapper.find('.request-status')

      assert.equal(loading.text(), 'Loading...')

      setTimeout(() => {
        assert.equal(loading.text(), 'An unexpected error occurred.')

        done()
      }, 100)
    })
  })

  describe('when the user exists and has public repositories', () => {
    before(() => {
      nock('https://api.github.com')
        .get('/users/goeuro-2012/repos?sort=created')
        .reply(200, goEuro)
    })

    it('should display a list of the user\'s repositories with a link to each repo', (done) => {
      userTextInput.simulate('change', { target: { value: 'goeuro-2012' } });
      findForm.simulate('submit')

      const loading = wrapper.find('.request-status')

      assert.equal(loading.text(), 'Loading...')

      setTimeout(() => {
        const hrefs = wrapper.find('.repositories .repository a')

        assert.equal(hrefs.length, 18)

        done()
      }, 100)
    })
  })

  describe('when the user exists and has no public repositories', () => {
    before(() => {
      nock('https://api.github.com')
        .get('/users/goeuro-2012/repos?sort=created')
        .reply(200, [])
    })

    it('should display a message saying "No public repositories exist for this user."', (done) => {
      userTextInput.simulate('change', { target: { value: 'goeuro-2012' } });
      findForm.simulate('submit')

      const loading = wrapper.find('.request-status')

      assert.equal(loading.text(), 'Loading...')

      setTimeout(() => {
        const noUsers = wrapper.find('.repositories .no-users')

        assert.equal(noUsers.text(), 'No public repositories exist for this user.')

        done()
      }, 100)
    })
  })

})


text:
from pahera.models import Person
from django.db import connection, transaction
from pahera.Utilities import DictFetchAll

# To check whether there exists a user with same email or phone no before registering the new user..!!!
def VerifyTheUser(data):
    cursor = connection.cursor()
    email = data['email']
    phone = data['phone']
    cursor.execute("SELECT * from pahera_person WHERE email = %s OR phone_no = %s", [email, phone])
    person_Data = {}
    person_Data = DictFetchAll.dictfetchall(cursor)
    if person_Data:
        if person_Data[0]['email'] == email or person_Data[0]['phone_no'] == phone:
            return False
        else:
            return True
    else:
        return True

# To check whether there exists a user with same email or phone no, before Updating the user..!!!
def VerifyTheUserUpdate(data, person):
    cursor = connection.cursor()
    email = data['email']
    phone = data['phone']
    cursor.execute("SELECT * from pahera_person WHERE email = %s OR phone_no = %s", [email, phone])
    person_Data = {}
    person_Data = DictFetchAll.dictfetchall(cursor)
    if person_Data:
        for post in person_Data:
            if post['email'] == email or post['phone_no'] == phone:
                if post['id'] == person.id:
                    return True
                else:
                    return False
        else:
            return True
    else:
        return True


text:
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

namespace Google.Cloud.EntityFrameworkCore.Spanner.Tests.MigrationTests.Migrations
{
    [DbContext(typeof(MockMigrationSampleDbContext))]
    [Migration("20210830_V2")]
    public class V2 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // Drop the TableWithAllColumnTypes table, including the related index.
            migrationBuilder.DropIndex("IDX_TableWithAllColumnTypes_ColDate_ColCommitTS", "TableWithAllColumnTypes");
            migrationBuilder.DropTable("TableWithAllColumnTypes");
        }
    }
}


text:
package org.motechproject.nms.flw.domain;

import org.motechproject.mds.annotations.Entity;
import org.motechproject.mds.annotations.Field;
import org.motechproject.mds.annotations.InstanceLifecycleListeners;
import org.motechproject.mds.domain.MdsEntity;
import org.motechproject.nms.region.domain.State;
import org.motechproject.nms.tracking.annotation.TrackClass;
import org.motechproject.nms.tracking.annotation.TrackFields;

import javax.jdo.annotations.Column;
import javax.jdo.annotations.Unique;
import javax.validation.constraints.NotNull;

/**
 * A state that has the whitelist enabled will appear in this table
 */
@Entity(tableName = "nms_whitelisted_states")
@TrackClass
@TrackFields
@InstanceLifecycleListeners
public class WhitelistState extends MdsEntity {
    @Field
    @NotNull
    @Unique
    @Column(allowsNull = "false")
    private State state;

    public WhitelistState(State state) {
        this.state = state;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        WhitelistState whitelistState = (WhitelistState) o;

        return !(state != null ? !state.equals(whitelistState.state) : whitelistState.state != null);

    }

    @Override
    public int hashCode() {
        return state != null ? state.hashCode() : 0;
    }

    @Override
    public String toString() {
        return "WhitelistState{" +
                "state=" + state +
                '}';
    }
}


text:
"use strict";
module.exports = function(Promise, INTERNAL, debug) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
var async = Promise._async;

function HandleWrapper(handle)  {
    this.handle = handle;
}

HandleWrapper.prototype._resultCancelled = function() {
    clearTimeout(this.handle);
};

var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
    var ret;
    var handle;
    if (value !== undefined) {
        ret = Promise.resolve(value)
                ._then(afterValue, null, null, ms, undefined);
        if (debug.cancellation() && value instanceof Promise) {
            ret._setOnCancel(value);
        }
    } else {
        ret = new Promise(INTERNAL);

        var setTimeout = async.getTimeoutFn();
        handle = setTimeout(function() { ret._fulfill(); }, +ms);
        if (debug.cancellation()) {
            ret._setOnCancel(new HandleWrapper(handle));
        }
        ret._captureStackTrace();
    }
    ret._setAsyncGuaranteed();
    return ret;
};

Promise.prototype.delay = function (ms) {
    return delay(ms, this);
};

var afterTimeout = function (promise, message, parent) {
    var err;
    if (typeof message !== "string") {
        if (message instanceof Error) {
            err = message;
        } else {
            err = new TimeoutError(TIMEOUT_ERROR);
        }
    } else {
        err = new TimeoutError(message);
    }
    util.markAsOriginatingFromRejection(err);
    promise._attachExtraTrace(err);
    promise._reject(err);

    if (parent != null) {
        parent.cancel();
    }
};

function successClear(value) {
    clearTimeout(this.handle);
    return value;
}

function failureClear(reason) {
    clearTimeout(this.handle);
    throw reason;
}

Promise.prototype.timeout = function (ms, message) {
    ms = +ms;
    var ret, parent;

    var setTimeout = async.getTimeoutFn();
    var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
        if (ret.isPending()) {
            afterTimeout(ret, message, parent);
        }
    }, ms));

    if (debug.cancellation()) {
        parent = this.then();
        ret = parent._then(successClear, failureClear,
                            undefined, handleWrapper, undefined);
        ret._setOnCancel(handleWrapper);
    } else {
        ret = this._then(successClear, failureClear,
                            undefined, handleWrapper, undefined);
    }

    return ret;
};

};


text:
class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def show?
    false
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  # Used by Pundit's #policy_scope
  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end


text:
using System.Data;

namespace FluentCommand;

/// <summary>
/// An <see langword="interface"/> defining a data query operations asynchronously.
/// </summary>
public interface IDataQueryAsync
#if !NETSTANDARD2_0
    : IAsyncDisposable
#endif

{
    /// <summary>
    /// Executes the command against the connection and converts the results to <typeparamref name="TEntity" /> objects asynchronously.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <param name="factory">The <see langword="delegate" /> factory to convert the <see cref="T:System.Data.IDataReader" /> to <typeparamref name="TEntity" />.</param>
    /// <param name="cancellationToken">The cancellation instruction.</param>
    /// <returns>
    /// An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <typeparamref name="TEntity" /> objects.
    /// </returns>
    /// <exception cref="System.ArgumentNullException"><paramref name="factory"/> is null</exception>
    Task<IEnumerable<TEntity>> QueryAsync<TEntity>(Func<IDataReader, TEntity> factory, CancellationToken cancellationToken = default);

    /// <summary>
    /// Executes the query and returns the first row in the result as a <typeparamref name="TEntity" /> object asynchronously.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <param name="factory">The <see langword="delegate" /> factory to convert the <see cref="T:System.Data.IDataReader" /> to <typeparamref name="TEntity" />.</param>
    /// <param name="cancellationToken">The cancellation instruction.</param>
    /// <returns>
    /// A instance of <typeparamref name="TEntity" /> if row exists; otherwise null.
    /// </returns>
    /// <exception cref="System.ArgumentNullException"><paramref name="factory"/> is null</exception>
    Task<TEntity> QuerySingleAsync<TEntity>(Func<IDataReader, TEntity> factory, CancellationToken cancellationToken = default);

    /// <summary>
    /// Executes the query and returns the first column of the first row in the result set returned by the query asynchronously. All other columns and rows are ignored.
    /// </summary>
    /// <typeparam name="TValue">The type of the value.</typeparam>
    /// <param name="convert">The <see langword="delegate" /> to convert the value..</param>
    /// <param name="cancellationToken">The cancellation instruction.</param>
    /// <returns>
    /// The value of the first column of the first row in the result set.
    /// </returns>
    Task<TValue> QueryValueAsync<TValue>(Func<object, TValue> convert, CancellationToken cancellationToken = default);

    /// <summary>
    /// Executes the command against the connection and converts the results to a <see cref="DataTable" /> asynchronously.
    /// </summary>
    /// <param name="cancellationToken">The cancellation instruction.</param>
    /// <returns>
    /// A <see cref="DataTable" /> of the results.
    /// </returns>
    Task<DataTable> QueryTableAsync(CancellationToken cancellationToken = default);
}


text:
var url = 'http://true_type_bug.dev';

var page1, page2;

page1 = require('webpage').create();
page1.open(url, function () {

  // uncomment this to cause the crash
  //page1.release();

  page2 = require('webpage').create();

  page2.open(url, function () {
    phantom.exit();
  });

});


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<link rel="stylesheet" type="text/css" href="logi/reset.css" />
	<link rel="stylesheet" type="text/css" href="index.css" />
	<link rel="stylesheet" type="text/css" href="slideshow/slideshow.css" />
	<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
	<meta name="description" content="Spice up your java" />
	<title>Project Lombok</title>

Project Lombok

				Okay, download lombok | I use maven

				Cancel

				Feature Overview

				Discuss / Help

				Contribute

				Report an issue

					Download!

					Version: @VERSION@ | changelog

				Imagine you have a very simple class:

public class Mountain {
	private final String name;
	private final double latitude, longitude;
	private String country;
}

				While that is fairly clear, that class is not complete. In fact, it won't compile like that.

				You'll need to add a constructor to initialize those final fields, you probably want getters, a setter for country,
				and to be complete, a nice toString as well as an implementation for equals and hashCode.
				Eclipse can generate all these methods for you, but then you end up with over 70 lines of boilerplate. It's going to be hard
				to see any surprises buried amongst all those lines of code! Lombok has the answer to this problem.

				So instead of this mess:

				lombok simply offers you an annotation that tells eclipse to generate all this stuff for us silently, without
				cluttering up your source file, like so:

				Note how we haven't even saved the file yet, but in the outline view you can already see all the various methods generated
				by the @Data annotation. That's because lombok is completely integrated into eclipse. The moment you type
				the last character of your annotation, all the methods exist, just as if you write the last character on a method declaration.
				In other words, lombok is not just an annotation processor!

				But what about your build process? Lombok works just as well in javac. All you need to do is add
				lombok.jar to the class path as you compile. Like so:

				@Data is nice, but its certainly not the only boilerplate buster that lombok has to offer. If you need
				more fine grained control, there's @Getter and @Setter, and to help you in correctly
				cleaning up your resources, @Cleanup can automatically and without cluttering your source files generate
				try/finally blocks to safely call close() on your resource objects. That's not all, but for the complete
				list you'll need to head over to the feature overview.

				Ready to install lombok? Start by clicking the download button at the top of this page. Going from clicking that button
				to having your eclipse ready to go takes less than 12 seconds - it's that simple.

				Thanks for checking out Project Lombok, and let us know what you think!

				If you'd like to read more, check out
				Reducing boilerplate code with Project Lombok
				written by Michael Kimberlin.

			I changed my mind - I do want to see the video!

			credits | Copyright © 2009 The Project Lombok Authors, licensed under the MIT license.


text:
import { ElementBinder } from './element_binder';
import { RenderProtoViewRef } from '../../api';
export declare function resolveInternalDomProtoView(protoViewRef: RenderProtoViewRef): DomProtoView;
export declare class DomProtoViewRef extends RenderProtoViewRef {
    _protoView: DomProtoView;
    constructor(_protoView: DomProtoView);
}
export declare class DomProtoView {
    element: any;
    elementBinders: List<ElementBinder>;
    isTemplateElement: boolean;
    rootBindingOffset: number;
    transitiveContentTagCount: number;
    boundTextNodeCount: number;
    rootNodeCount: number;
    constructor({elementBinders, element, transitiveContentTagCount}: {
        elementBinders: any;
        element: any;
        transitiveContentTagCount: any;
    });
}
export declare var __esModule: boolean;


text:
using System.Collections.Generic;
using System.Linq;
using Leak.Common;
using Leak.Events;
using Leak.Peer.Coordinator.Events;

namespace Leak.Data.Map.Components
{
    public class OmnibusStateCollection
    {
        private readonly Dictionary<PeerHash, OmnibusStateEntry> byPeer;

        public OmnibusStateCollection()
        {
            byPeer = new Dictionary<PeerHash, OmnibusStateEntry>();
        }

        public void Handle(PeerConnected data)
        {
            OmnibusStateEntry entry;

            if (byPeer.TryGetValue(data.Peer, out entry) == false)
            {
                entry = new OmnibusStateEntry(data.Peer);
                byPeer.Add(data.Peer, entry);
            }

            entry.State = new PeerState();
        }

        public void Handle(PeerDisconnected data)
        {
            byPeer.Remove(data.Peer);
        }

        public void Handle(StatusChanged data)
        {
            OmnibusStateEntry entry;

            if (byPeer.TryGetValue(data.Peer, out entry) == false)
            {
                entry = new OmnibusStateEntry(data.Peer);
                byPeer.Add(data.Peer, entry);
            }

            entry.State = new PeerState(data.State);
        }

        public IEnumerable<PeerHash> All()
        {
            return byPeer.Keys;
        }

        public OmnibusStateEntry ByPeer(PeerHash peer)
        {
            OmnibusStateEntry entry;
            byPeer.TryGetValue(peer, out entry);
            return entry;
        }

        public IEnumerable<PeerHash> Find(int ranking, int count)
        {
            foreach (OmnibusStateEntry state in byPeer.Values.OrderByDescending(x => x.Ranking))
            {
                if (count == 0)
                    break;

                if (state.Ranking < ranking)
                    continue;

                if (state.State.IsRemoteChokingLocal)
                    continue;

                if (state.State.IsLocalInterestedInRemote == false)
                    continue;

                count--;
                yield return state.Peer;
            }
        }
    }
}


text:
if ENV['SIMPLECOV']
  require 'simplecov'
  SimpleCov.start
end

require 'bundler/setup'
Bundler.setup

require 'discogs2'
require 'json'
require 'vcr'

VCR.configure do |c|
  c.cassette_library_dir = 'spec/cassettes'
  c.hook_into :webmock
  c.default_cassette_options = { :record => :new_episodes, :re_record_interval => 7200 }
  c.configure_rspec_metadata!
end

RSpec.configure do |config|
  # some (optional) config here
  #VCR
  config.treat_symbols_as_metadata_keys_with_true_values = true
  #config.extend VCR::RSpec::Macros
end


text:
import rtorrent.rpc
# from rtorrent.rpc import Method
import rtorrent.peer
import rtorrent.tracker
import rtorrent.file
import rtorrent.compat

from rtorrent.common import safe_repr

Peer = rtorrent.peer.Peer
Tracker = rtorrent.tracker.Tracker
File = rtorrent.file.File
Method = rtorrent.rpc.Method

class Torrent:
    """Represents an individual torrent within a L{RTorrent} instance."""

    def __init__(self, _rt_obj, info_hash, **kwargs):
        self._rt_obj = _rt_obj
        self.info_hash = info_hash  # : info hash for the torrent
        self.rpc_id = self.info_hash  # : unique id to pass to rTorrent
        for k in kwargs.keys():
            setattr(self, k, kwargs.get(k, None))

        self.peers = []
        self.trackers = []
        self.files = []

        self._call_custom_methods()

    def __repr__(self):
        return safe_repr("Torrent(info_hash=\"{0}\" name=\"{1}\")",
                        self.info_hash, self.name)

    def _call_custom_methods(self):
        """only calls methods that check instance variables."""
        self._is_hash_checking_queued()
        self._is_started()
        self._is_paused()

    def get_peers(self):
        """Get list of Peer instances for given torrent.

        @return: L{Peer} instances
        @rtype: list

        @note: also assigns return value to self.peers
        """
        self.peers = []
        retriever_methods = [m for m in rtorrent.peer.methods
                             if m.is_retriever() and m.is_available(self._rt_obj)]
        # need to leave 2nd arg empty (dunno why)
        m = rtorrent.rpc.Multicall(self)
        m.add("p.multicall", self.info_hash, "",
              *[method.rpc_call + "=" for method in retriever_methods])

        results = m.call()[0]  # only sent one call, only need first result

        for result in results:
            results_dict = {}
            # build results_dict
            for m, r in zip(retriever_methods, result):
                results_dict[m.varname] = rtorrent.rpc.process_result(m, r)

            self.peers.append(Peer(
                self._rt_obj, self.info_hash, **results_dict))

        return(self.peers)

    def get_trackers(self):
        """Get list of Tracker instances for given torrent.

        @return: L{Tracker} instances
        @rtype: list

        @note: also assigns return value to self.trackers
        """
        self.trackers = []
        retriever_methods = [m for m in rtorrent.tracker.methods
                             if m.is_retriever() and m.is_available(self._rt_obj)]

        # need to leave 2nd arg empty (dunno why)
        m = rtorrent.rpc.Multicall(self)
        m.add("t.multicall", self.info_hash, "",
              *[method.rpc_call + "=" for method in retriever_methods])

        results = m.call()[0]  # only sent one call, only need first result

        for result in results:
            results_dict = {}
            # build results_dict
            for m, r in zip(retriever_methods, result):
                results_dict[m.varname] = rtorrent.rpc.process_result(m, r)

            self.trackers.append(Tracker(
                self._rt_obj, self.info_hash, **results_dict))

        return(self.trackers)

    def get_files(self):
        """Get list of File instances for given torrent.

        @return: L{File} instances
        @rtype: list

        @note: also assigns return value to self.files
        """

        self.files = []
        retriever_methods = [m for m in rtorrent.file.methods
                             if m.is_retriever() and m.is_available(self._rt_obj)]
        # 2nd arg can be anything, but it'll return all files in torrent
        # regardless
        m = rtorrent.rpc.Multicall(self)
        m.add("f.multicall", self.info_hash, "",
              *[method.rpc_call + "=" for method in retriever_methods])

        results = m.call()[0]  # only sent one call, only need first result

        offset_method_index = retriever_methods.index(
            rtorrent.rpc.find_method("f.get_offset"))

        # make a list of the offsets of all the files, sort appropriately
        offset_list = sorted([r[offset_method_index] for r in results])

        for result in results:
            results_dict = {}
            # build results_dict
            for m, r in zip(retriever_methods, result):
                results_dict[m.varname] = rtorrent.rpc.process_result(m, r)

            # get proper index positions for each file (based on the file
            # offset)
            f_index = offset_list.index(results_dict["offset"])

            self.files.append(File(self._rt_obj, self.info_hash,
                                   f_index, **results_dict))

        return(self.files)

    def set_directory(self, d):
        """Modify download directory

        @note: Needs to stop torrent in order to change the directory.
        Also doesn't restart after directory is set, that must be called
        separately.
        """
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.try_stop")
        self.multicall_add(m, "d.set_directory", d)

        self.directory = m.call()[-1]

    def set_directory_base(self, d):
        """Modify base download directory

        @note: Needs to stop torrent in order to change the directory.
        Also doesn't restart after directory is set, that must be called
        separately.
        """
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.try_stop")
        self.multicall_add(m, "d.set_directory_base", d)

    def start(self):
        """Start the torrent"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.try_start")
        self.multicall_add(m, "d.is_active")

        self.active = m.call()[-1]
        return(self.active)

    def stop(self):
        """"Stop the torrent"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.try_stop")
        self.multicall_add(m, "d.is_active")

        self.active = m.call()[-1]
        return(self.active)

    def pause(self):
        """Pause the torrent"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.pause")

        return(m.call()[-1])

    def resume(self):
        """Resume the torrent"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.resume")

        return(m.call()[-1])

    def close(self):
        """Close the torrent and it's files"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.close")

        return(m.call()[-1])

    def erase(self):
        """Delete the torrent

        @note: doesn't delete the downloaded files"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.erase")

        return(m.call()[-1])

    def check_hash(self):
        """(Re)hash check the torrent"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.check_hash")

        return(m.call()[-1])

    def poll(self):
        """poll rTorrent to get latest peer/tracker/file information"""
        self.get_peers()
        self.get_trackers()
        self.get_files()

    def update(self):
        """Refresh torrent data

        @note: All fields are stored as attributes to self.

        @return: None
        """
        multicall = rtorrent.rpc.Multicall(self)
        retriever_methods = [m for m in methods
                             if m.is_retriever() and m.is_available(self._rt_obj)]
        for method in retriever_methods:
            multicall.add(method, self.rpc_id)

        multicall.call()

        # custom functions (only call private methods, since they only check
        # local variables and are therefore faster)
        self._call_custom_methods()

    def accept_seeders(self, accept_seeds):
        """Enable/disable whether the torrent connects to seeders

        @param accept_seeds: enable/disable accepting seeders
        @type accept_seeds: bool"""
        if accept_seeds:
            call = "d.accepting_seeders.enable"
        else:
            call = "d.accepting_seeders.disable"

        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, call)

        return(m.call()[-1])

    def announce(self):
        """Announce torrent info to tracker(s)"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.tracker_announce")

        return(m.call()[-1])

    @staticmethod
    def _assert_custom_key_valid(key):
        assert type(key) == int and key > 0 and key < 6, \
            "key must be an integer between 1-5"

    def get_custom(self, key):
        """
        Get custom value

        @param key: the index for the custom field (between 1-5)
        @type key: int

        @rtype: str
        """

        self._assert_custom_key_valid(key)
        m = rtorrent.rpc.Multicall(self)

        field = "custom{0}".format(key)
        self.multicall_add(m, "d.get_{0}".format(field))
        setattr(self, field, m.call()[-1])

        return (getattr(self, field))

    def set_custom(self, key, value):
        """
        Set custom value

        @param key: the index for the custom field (between 1-5)
        @type key: int

        @param value: the value to be stored
        @type value: str

        @return: if successful, value will be returned
        @rtype: str
        """

        self._assert_custom_key_valid(key)
        m = rtorrent.rpc.Multicall(self)

        self.multicall_add(m, "d.set_custom{0}".format(key), value)

        return(m.call()[-1])

    def set_visible(self, view, visible=True):
        p = self._rt_obj._get_conn()

        if visible:
            return p.view.set_visible(self.info_hash, view)
        else:
            return p.view.set_not_visible(self.info_hash, view)

    ############################################################################
    # CUSTOM METHODS (Not part of the official rTorrent API)
    ##########################################################################
    def _is_hash_checking_queued(self):
        """Only checks instance variables, shouldn't be called directly"""
        # if hashing == 3, then torrent is marked for hash checking
        # if hash_checking == False, then torrent is waiting to be checked
        self.hash_checking_queued = (self.hashing == 3 and
                                     self.hash_checking is False)

        return(self.hash_checking_queued)

    def is_hash_checking_queued(self):
        """Check if torrent is waiting to be hash checked

        @note: Variable where the result for this method is stored Torrent.hash_checking_queued"""
        m = rtorrent.rpc.Multicall(self)
        self.multicall_add(m, "d.get_hashing")
        self.multicall_add(m, "d.is_hash_checking")
        results = m.call()

        setattr(self, "hashing", results[0])
        setattr(self, "hash_checking", results[1])

        return(self._is_hash_checking_queued())

    def _is_paused(self):
        """Only checks instance variables, shouldn't be called directly"""
        self.paused = (self.state == 0)
        return(self.paused)

    def is_paused(self):
        """Check if torrent is paused

        @note: Variable where the result for this method is stored: Torrent.paused"""
        self.get_state()
        return(self._is_paused())

    def _is_started(self):
        """Only checks instance variables, shouldn't be called directly"""
        self.started = (self.state == 1)
        return(self.started)

    def is_started(self):
        """Check if torrent is started

        @note: Variable where the result for this method is stored: Torrent.started"""
        self.get_state()
        return(self._is_started())

methods = [
    # RETRIEVERS
    Method(Torrent, 'is_hash_checked', 'd.is_hash_checked',
           boolean=True,
           ),
    Method(Torrent, 'is_hash_checking', 'd.is_hash_checking',
           boolean=True,
           ),
    Method(Torrent, 'get_peers_max', 'd.get_peers_max'),
    Method(Torrent, 'get_tracker_focus', 'd.get_tracker_focus'),
    Method(Torrent, 'get_skip_total', 'd.get_skip_total'),
    Method(Torrent, 'get_state', 'd.get_state'),
    Method(Torrent, 'get_peer_exchange', 'd.get_peer_exchange'),
    Method(Torrent, 'get_down_rate', 'd.get_down_rate'),
    Method(Torrent, 'get_connection_seed', 'd.get_connection_seed'),
    Method(Torrent, 'get_uploads_max', 'd.get_uploads_max'),
    Method(Torrent, 'get_priority_str', 'd.get_priority_str'),
    Method(Torrent, 'is_open', 'd.is_open',
           boolean=True,
           ),
    Method(Torrent, 'get_peers_min', 'd.get_peers_min'),
    Method(Torrent, 'get_peers_complete', 'd.get_peers_complete'),
    Method(Torrent, 'get_tracker_numwant', 'd.get_tracker_numwant'),
    Method(Torrent, 'get_connection_current', 'd.get_connection_current'),
    Method(Torrent, 'is_complete', 'd.get_complete',
           boolean=True,
           ),
    Method(Torrent, 'get_peers_connected', 'd.get_peers_connected'),
    Method(Torrent, 'get_chunk_size', 'd.get_chunk_size'),
    Method(Torrent, 'get_state_counter', 'd.get_state_counter'),
    Method(Torrent, 'get_base_filename', 'd.get_base_filename'),
    Method(Torrent, 'get_state_changed', 'd.get_state_changed'),
    Method(Torrent, 'get_peers_not_connected', 'd.get_peers_not_connected'),
    Method(Torrent, 'get_directory', 'd.get_directory'),
    Method(Torrent, 'is_incomplete', 'd.incomplete',
           boolean=True,
           ),
    Method(Torrent, 'get_tracker_size', 'd.get_tracker_size'),
    Method(Torrent, 'is_multi_file', 'd.is_multi_file',
           boolean=True,
           ),
    Method(Torrent, 'get_local_id', 'd.get_local_id'),
    Method(Torrent, 'get_ratio', 'd.get_ratio',
           post_process_func=lambda x: x / 1000.0,
           ),
    Method(Torrent, 'get_loaded_file', 'd.get_loaded_file'),
    Method(Torrent, 'get_max_file_size', 'd.get_max_file_size'),
    Method(Torrent, 'get_size_chunks', 'd.get_size_chunks'),
    Method(Torrent, 'is_pex_active', 'd.is_pex_active',
           boolean=True,
           ),
    Method(Torrent, 'get_hashing', 'd.get_hashing'),
    Method(Torrent, 'get_bitfield', 'd.get_bitfield'),
    Method(Torrent, 'get_local_id_html', 'd.get_local_id_html'),
    Method(Torrent, 'get_connection_leech', 'd.get_connection_leech'),
    Method(Torrent, 'get_peers_accounted', 'd.get_peers_accounted'),
    Method(Torrent, 'get_message', 'd.get_message'),
    Method(Torrent, 'is_active', 'd.is_active',
           boolean=True,
           ),
    Method(Torrent, 'get_size_bytes', 'd.get_size_bytes'),
    Method(Torrent, 'get_ignore_commands', 'd.get_ignore_commands'),
    Method(Torrent, 'get_creation_date', 'd.get_creation_date'),
    Method(Torrent, 'get_base_path', 'd.get_base_path'),
    Method(Torrent, 'get_left_bytes', 'd.get_left_bytes'),
    Method(Torrent, 'get_size_files', 'd.get_size_files'),
    Method(Torrent, 'get_size_pex', 'd.get_size_pex'),
    Method(Torrent, 'is_private', 'd.is_private',
           boolean=True,
           ),
    Method(Torrent, 'get_max_size_pex', 'd.get_max_size_pex'),
    Method(Torrent, 'get_num_chunks_hashed', 'd.get_chunks_hashed',
           aliases=("get_chunks_hashed",)),
    Method(Torrent, 'get_num_chunks_wanted', 'd.wanted_chunks'),
    Method(Torrent, 'get_priority', 'd.get_priority'),
    Method(Torrent, 'get_skip_rate', 'd.get_skip_rate'),
    Method(Torrent, 'get_completed_bytes', 'd.get_completed_bytes'),
    Method(Torrent, 'get_name', 'd.get_name'),
    Method(Torrent, 'get_completed_chunks', 'd.get_completed_chunks'),
    Method(Torrent, 'get_throttle_name', 'd.get_throttle_name'),
    Method(Torrent, 'get_free_diskspace', 'd.get_free_diskspace'),
    Method(Torrent, 'get_directory_base', 'd.get_directory_base'),
    Method(Torrent, 'get_hashing_failed', 'd.get_hashing_failed'),
    Method(Torrent, 'get_tied_to_file', 'd.get_tied_to_file'),
    Method(Torrent, 'get_down_total', 'd.get_down_total'),
    Method(Torrent, 'get_bytes_done', 'd.get_bytes_done'),
    Method(Torrent, 'get_up_rate', 'd.get_up_rate'),
    Method(Torrent, 'get_up_total', 'd.get_up_total'),
    Method(Torrent, 'is_accepting_seeders', 'd.accepting_seeders',
           boolean=True,
           ),
    Method(Torrent, "get_chunks_seen", "d.chunks_seen",
           min_version=(0, 9, 1),
           ),
    Method(Torrent, "is_partially_done", "d.is_partially_done",
           boolean=True,
           ),
    Method(Torrent, "is_not_partially_done", "d.is_not_partially_done",
           boolean=True,
           ),
    Method(Torrent, "get_time_started", "d.timestamp.started"),
    Method(Torrent, "get_custom1", "d.get_custom1"),
    Method(Torrent, "get_custom2", "d.get_custom2"),
    Method(Torrent, "get_custom3", "d.get_custom3"),
    Method(Torrent, "get_custom4", "d.get_custom4"),
    Method(Torrent, "get_custom5", "d.get_custom5"),

    # MODIFIERS
    Method(Torrent, 'set_uploads_max', 'd.set_uploads_max'),
    Method(Torrent, 'set_tied_to_file', 'd.set_tied_to_file'),
    Method(Torrent, 'set_tracker_numwant', 'd.set_tracker_numwant'),
    Method(Torrent, 'set_priority', 'd.set_priority'),
    Method(Torrent, 'set_peers_max', 'd.set_peers_max'),
    Method(Torrent, 'set_hashing_failed', 'd.set_hashing_failed'),
    Method(Torrent, 'set_message', 'd.set_message'),
    Method(Torrent, 'set_throttle_name', 'd.set_throttle_name'),
    Method(Torrent, 'set_peers_min', 'd.set_peers_min'),
    Method(Torrent, 'set_ignore_commands', 'd.set_ignore_commands'),
    Method(Torrent, 'set_max_file_size', 'd.set_max_file_size'),
    Method(Torrent, 'set_custom5', 'd.set_custom5'),
    Method(Torrent, 'set_custom4', 'd.set_custom4'),
    Method(Torrent, 'set_custom2', 'd.set_custom2'),
    Method(Torrent, 'set_custom1', 'd.set_custom1'),
    Method(Torrent, 'set_custom3', 'd.set_custom3'),
    Method(Torrent, 'set_connection_current', 'd.set_connection_current'),
]


text:
package com.adonis.ui.persons;

import com.adonis.data.persons.Address;
import com.adonis.data.service.PersonService;
import com.adonis.ui.MainUI;
import com.adonis.utils.GeoService;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.*;
import com.vaadin.v7.data.fieldgroup.BeanFieldGroup;
import com.vaadin.v7.data.fieldgroup.FieldGroup;
import com.vaadin.v7.data.util.BeanItem;

/**
 * Created by oksdud on 18.04.2017.
 */
@Widgetset("com.vaadin.v7.Vaadin7WidgetSet")
public class AddressUI extends UI {

    private GeoService geoService = GeoService.getInstance();

    public FieldGroup fieldGroup = new BeanFieldGroup<Address>(Address.class);
    public FormLayout layout = new FormLayout();
    public com.vaadin.v7.ui.TextArea street = new com.vaadin.v7.ui.TextArea("Street address:");
    public com.vaadin.v7.ui.TextField zip = new com.vaadin.v7.ui.TextField("Postal zip code:");

    public com.vaadin.v7.ui.ComboBox country = new com.vaadin.v7.ui.ComboBox("Country:", geoService.getCountries());
    public com.vaadin.v7.ui.ComboBox city = new com.vaadin.v7.ui.ComboBox("City:");
    public String countryName="Latvia";
    public String cityName="Riga";
    PersonService personService;
    @Override
    protected void init(VaadinRequest request) {
        personService = MainUI.personsCrudView.personService;
        fieldGroup.setItemDataSource(new BeanItem<Address>(AddressPopup.currentAddress, Address.class));
        fieldGroup.bind(street, "street");
        fieldGroup.bind(zip, "zip");
        fieldGroup.bind(city, "city");
        fieldGroup.bind(country, "country");

        country.addListener(new Listener() {
            @Override
            public void componentEvent(Event event) {
                countryName = (String) country.getValue();
//                if(country.getValue()==null)country.setValue(geoService.getCountry(geoService.getIpInetAdress()));
                if(countryName!=null)city.addItems(geoService.getCitiesByCountry(countryName));
            }
        });

        city.addListener(new Listener() {
            @Override
            public void componentEvent(Event event) {
                cityName = (String) city.getValue();
            }
        });

        HorizontalLayout inLayout = new HorizontalLayout();
        Button close = new Button("Ok");
        close.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                Address address = new Address();
                address.setCity(cityName);
                address.setCountry(countryName);
                address.setStreet(street.getValue());
                address.setZip(zip.getValue());
                try {
                    fieldGroup.commit();
                    JavaScript.eval("close()");
                    getUI().close();

                } catch (Exception e) {
                    e.printStackTrace();
                    JavaScript.eval("close()");
                    getUI().close();

                }
            }
        });
//        Button cancel = new Button("Cancel");
        inLayout.addComponents( close);

        layout.addComponent(street);
        layout.addComponent(zip);
        layout.addComponent(country);
        layout.addComponent(city);
        layout.addComponent(inLayout);
        fieldGroup.bind(street, "street");
        fieldGroup.bind(zip, "zip");
        fieldGroup.bind(city, "city");
        fieldGroup.bind(country, "country");
        setContent(layout);
    }
}


text:
/**
 * dist.conf.js
 * Author: H.Alper Tuna <halpertuna@gmail.com>
 * Date: 18.08.2016
 */

const config = require('./base.conf');

// Webpack Production Settings
module.exports = Object.assign(config, {
  entry: './src/RouterLink.jsx',
  output: {
    path: 'dist',
    filename: 'react-metismenu-router-link.js',
    library: 'ReactMetismenuRouterLink',
    libraryTarget: 'umd',
  },
  externals: [
    {
      react: true,
    },
  ],
});


text:
package java.time;

class _TimeConsts {
	static public final int SECONDS_IN_MINUTE = 60;
	static public final int SECONDS_IN_HOUR = 3_600;
	static public final int SECONDS_IN_DAY = 86_400;
	static public final int NANOSECONDS_IN_SECOND = 1_000_000_000;
	static public final int NANOSECONDS_IN_MILLISECOND = 1_000_000;
	static public final int MILLISECONDS_IN_SECOND = 1_000;
}


text:
package iso20022

// Choice of format between a rate, an amount or a unspecified rate.
type RateAndAmountFormat14Choice struct {

	// Value expressed as a rate.
	Rate *PercentageRate `xml:"Rate"`

	// Value of the rate not specified.
	NotSpecifiedRate *RateValueType7Code `xml:"NotSpcfdRate"`

	// Value is expressed as a currency and amount.
	Amount *ActiveCurrencyAnd13DecimalAmount `xml:"Amt"`
}

func (r *RateAndAmountFormat14Choice) SetRate(value string) {
	r.Rate = (*PercentageRate)(&value)
}

func (r *RateAndAmountFormat14Choice) SetNotSpecifiedRate(value string) {
	r.NotSpecifiedRate = (*RateValueType7Code)(&value)
}

func (r *RateAndAmountFormat14Choice) SetAmount(value, currency string) {
	r.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)
}


text:
import assert from 'assert';
import { relative, join } from 'path';
import { readFile } from 'fs';
import {
  build,
  createEntryModule,
  install,
} from '../../src/utils/build';
import { rm, ls } from 'shelljs';
import _ from 'lodash';
import Promise from 'bluebird';

const { describe, it, afterEach } = global;
const readFileAsync = Promise.promisify(readFile);

const location = relative(join(process.cwd(), 'test'), __filename);
const tmpFolder = join(__dirname, 'tmp');

function includesAll(array, items) {
  const isIncludedInArray = _.curry(_.includes)(array);
  return _.every(items, isIncludedInArray);
}

const fixture = {
  assetId: 3,
  assetPath: join(tmpFolder, 'asset'),
  dependencies: {
    mathjs: {
      version: '2.5.0',
      bindings: [
        {
          modulePath: 'index',
          propertyName: 'mathjs',
        },
      ],
    },
    should: {
      version: '7.0.2',
      bindings: [
        {
          modulePath: 'as-function',
          propertyName: 'should',
        },
      ],
    },
    lodash: {
      version: '3.9.1',
      bindings: [
        {
          modulePath: 'index',
          propertyName: 'lodash',
        },
      ],
    },
  },
};

describe(location, function buildTest() {
  const buildTestTimeout = 20000;
  this.timeout(buildTestTimeout);

  afterEach(() => {
    rm('-rf', tmpFolder);
  });

  describe('build', () => {

    it('should build the asset correctly', () => {
      const { assetId, assetPath, dependencies } = fixture;
      return build(assetId, assetPath, dependencies).then(() => {
        const files = ls(assetPath);
        assert(includesAll(files, ['entry.js', 'bundle.js']), 'Asset directory contains expected files.');
        const modules = ls(join(assetPath, 'node_modules'));
        assert(includesAll(modules, Object.keys(dependencies)), 'Modules in dependencies are installed.');
      });
    });
  });

  describe('createEntryModule', () =>
    it('should output the correct entry.js file content', () => {
      const expectedResult = [
        'global.__dependencyBundles[3]={\'mathjs\':require(\'mathjs/index\'),\'should\'',
        ':require(\'should/as-function\'),\'lodash\':require(\'lodash/index\'),}',
      ].join('');
      const { assetId, dependencies } = fixture;
      const result = createEntryModule(assetId, dependencies);
      assert(result === expectedResult, 'The result is the same as the expected entry module content.');
    })
  );

  describe('install', () => {
    it('should install the dependencies', () => {
      const { dependencies, assetPath } = fixture;
      return install(assetPath, dependencies).then(() => {
        const modules = ls(join(assetPath, 'node_modules'));
        assert(includesAll(modules, Object.keys(dependencies)), 'Modules in dependencies are installed.');
      });
    });

    it('should change the version of the dependency', async () => { // eslint-disable-line arrow-parens
      const { assetPath, dependencies } = fixture;
      const lodashPackagePath = join(assetPath, 'node_modules', 'lodash', 'package.json');
      await install(assetPath, dependencies);
      const modules = ls(join(assetPath, 'node_modules'));
      assert(includesAll(modules, Object.keys(dependencies)), 'Modules in dependencies are installed.');
      const lodashPackage = await readFileAsync(lodashPackagePath, 'utf8');
      const lodashVersion = JSON.parse(lodashPackage).version;
      assert(lodashVersion === dependencies.lodash.version, 'The installed version is the one specified.');

      const updatedDependencies = Object.assign(_.cloneDeep(dependencies), {
        lodash: {
          version: '3.10.1',
          bindings: [
            {
              modulePath: 'index',
              propertyName: 'lodash',
            },
          ],
        },
      });
      await install(assetPath, updatedDependencies);
      const newLodashPackage = await readFileAsync(lodashPackagePath, 'utf8');
      const newLodashVersion = JSON.parse(newLodashPackage).version;
      assert(newLodashVersion === updatedDependencies.lodash.version, 'The installed version is the new one.');
    });
  });
});


text:
var Client = function(){
	this.socket = io({forceNew:true});;
	this.clients = {};
	this.id = false;
	this.maxClient = 100;
	this.clientIP = false;
	this.host = false;
	this.hostRight = false;
	this.heartBeat = false;
	this.timeArray = [[]];
	this.numClients = 0;
	this.socket.on('getConnected',function(data){
		if (!data.accept) {
			this.socket.disconnect();
			alert("Game is running, please join later.");
			return;
		};
		if (!data.host) {
			this.socket.disconnect();
			alert("Please wait for host first before entering your name.");
			return;
		};
		if (data.totalClients > this.maxClient){
			this.socket.disconnect();
			alert("No more places, please try again later.");
			return;
		};
		if(!this.id){
			this.clientNumber = data.clientNumber;
			this.id = data.clientID;
			this.clientIP = data.clientIP;
			this.host = data.host;
			this.totalClients = data.totalClients
			if(data.host == this.id){
				this.hostRight = true;
			}
			console.log("My id: "+ this.id + ", Host: " + this.host);
		}
	}.bind(this));

	this.socket.on('updatedInfo', function(data){
		this.id = data.clientID;
		this.clientIP = data.clientIP;
		this.host = data.host;
		this.totalClients = data.totalClients
	}.bind(this));

	this.socket.on('accepted',function(data){
		this.clients = data.clients;
		resetLog();
		this.numClients = 0;
		for (var k in this.clients){
			var client = this.clients[k];
			var name = client.name;
			updateLog(name);
			this.numClients++;
		}
	}.bind(this));

	this.socket.on('disconnection', function(data){
		this.clients = data.clients;
		resetLog();
		for (var k in this.clients){
			var client = this.clients[k];
			var name = client.name;
			updateLog(name);
		}
		this.numClients--;
	}.bind(this));

	// this.socket.on('gameOperate', function(data){
		// switch(data.action){
			// case "submitTime":

				// console.log("Client " + data.clientNumber + " has submitted time " + data.reactionTime);

				// if(this.timeArray.length == 0){
					// this.timeArray.push(0, 0);
				// }

				// var pushingValue = {};
				// pushingValue.clientNumber = data.clientNumber;
				// pushingValue.timeTaken = data.reactionTime;
				// this.timeArray.push(pushingValue);

				// if((this.timeArray.length-1) == this.numClients){

					// var minimumValue = 0;
					// var minimumClient = 0;

					// for(var k = 1; k < this.timeArray.length; k++){
						// if(this.timeArray[k].timeTaken < minimumValue || minimumValue == 0){
							// minimumValue = this.timeArray[k].timeTaken;
							// minimumClient = this.timeArray[k].clientNumber;
						// }
					// }

					// displayWinner(minimumValue, minimumClient);
					// this.timeArray = [[]];
				// }
				// break;

			// }
		// }.bind(this));

	this.socket.on('submitTime',function(data){
	console.log("Client " + data.clientNumber + " has submitted time " + data.reactionTime);

				if(this.timeArray.length == 0){
					this.timeArray.push(0, 0);
				}

				var pushingValue = {};
				pushingValue.clientNumber = data.clientNumber;
				pushingValue.timeTaken = data.reactionTime;
				this.timeArray.push(pushingValue);

				if((this.timeArray.length-1) == this.numClients){

					var minimumValue = 0;
					var minimumClient = 0;

					for(var k = 1; k < this.timeArray.length; k++){
						if(this.timeArray[k].timeTaken < minimumValue || minimumValue == 0){
							minimumValue = this.timeArray[k].timeTaken;
							minimumClient = this.timeArray[k].clientNumber;
						}
					}

					displayWinner(minimumValue, minimumClient);
					this.timeArray = [[]];
				}

	}.bind(this));

	this.socket.on('changeState', function(data){
		switch(data.state){
			case "1":
				init(data.time);
				break;
			}
		}.bind(this));
}


text: Udacity iOS Degree: OnTheMap project


text:
package com.yuxifu.everneeds.ui.main;

import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.yuxifu.everneeds.R;
import com.yuxifu.everneeds.system.AppPreferences;
import com.yuxifu.everneeds.ui._exp.PlaceholderItemFragment;
import com.yuxifu.everneeds.ui._exp.dummy.DummyContent;
import com.yuxifu.everneeds.ui.adapters.ViewPagerAdapter;
import com.yuxifu.everneeds.ui.categories.more.MoreNavigationFragment;
import com.yuxifu.everneeds.ui.categories.plan.PlanNavigationFragment;
import com.yuxifu.everneeds.ui.custom_views.CanDisableSwipingViewPager;
import com.yuxifu.everneeds.ui.products.calendar.CalendarWidgetFragment;
import com.yuxifu.everneeds.ui.products.todolist.TodoWidgetFragment;
import com.yuxifu.everneeds.util.ResourceHelper;

/**
 * Main entrance of the application.  Main activity
 */
public class MainActivity extends AppCompatActivity implements
        CalendarWidgetFragment.OnFragmentInteractionListener,
        TodoWidgetFragment.OnFragmentInteractionListener,
        PlaceholderItemFragment.OnListFragmentInteractionListener,
        PlanNavigationFragment.OnFragmentInteractionListener,
        MoreNavigationFragment.OnFragmentInteractionListener {

    //constants
    public static int[] navTabs() {
        return new int[]{
                R.string.nav_home_title,
                R.string.nav_note_title,
                R.string.nav_plan_title,
                R.string.nav_track_title,
                R.string.nav_discover_title,
                R.string.nav_more_title
        };
    }

    //
    private MainActivity self;
    private CoordinatorLayout coordinatorLayout;
    private AppBarLayout appBarLayout;
    private Toolbar toolbar;
    private CanDisableSwipingViewPager viewPager;

    @Override
    @CallSuper
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //must be called before onCreate() to apply theme
        enableNightMode(AppPreferences.getNightModeOn(this));

        //super
        super.onCreate(savedInstanceState);
        self = this;
        setContentView(R.layout.activity_main_auto_scroll_toolbar);

        //
        coordinatorLayout = findViewById(R.id.main_content);
        appBarLayout = findViewById(R.id.main_appbar);

        // Toolbar
        toolbar = findViewById(R.id.main_toolbar);
        setSupportActionBar(toolbar);
        enableActionBarHideOnScroll(AppPreferences.getActionBarHideOnScroll(this));

        viewPager = findViewById(R.id.main_viewpager);
        setupViewPager(viewPager);
        viewPager.disableSwiping(!AppPreferences.getMainNavigationSwipingOn(this));

        SmartTabLayout smartLayout = findViewById(R.id.main_bottom_tab);
        setupNavigationTabs(smartLayout);

        smartLayout.setViewPager(viewPager);
    }

    private void setupViewPager(final ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFragment(PlaceholderItemFragment.newInstance(1), getResources().getString(navTabs()[0]));
        adapter.addFragment(PlaceholderItemFragment.newInstance(1), getResources().getString(navTabs()[1]));
        adapter.addFragment(new PlanNavigationFragment(), getResources().getString(navTabs()[2]));
        adapter.addFragment(PlaceholderItemFragment.newInstance(2), getResources().getString(navTabs()[3]));
        adapter.addFragment(PlaceholderItemFragment.newInstance(1), getResources().getString(navTabs()[4]));
        adapter.addFragment(new MoreNavigationFragment(), getResources().getString(navTabs()[5]));
        viewPager.setAdapter(adapter);

        viewPager.setCurrentItem(AppPreferences.getCurrentMainNavigationIndex(this, navTabs().length - 1));

        final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0 || position == navTabs().length - 1) {
                    toolbar.setTitle(R.string.app_name);
                } else {   //display app name at the "home" page
                    toolbar.setTitle(navTabs()[position]);
                }
                AppPreferences.putCurrentMainNavigationIndex(self, position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };

        viewPager.addOnPageChangeListener(pageChangeListener);

        // do this in a runnable to make sure the viewPager's views are already instantiated
        // before triggering the onPageSelected call
        viewPager.post(new Runnable() {
            @Override
            public void run() {
                pageChangeListener.onPageSelected(viewPager.getCurrentItem());
            }
        });
    }

    public void setupNavigationTabs(SmartTabLayout layout) {

        final LayoutInflater inflater = LayoutInflater.from(layout.getContext());
        final Resources res = layout.getContext().getResources();

        layout.setCustomTabView(new SmartTabLayout.TabProvider() {
            @Override
            public View createTabView(ViewGroup container, int position, PagerAdapter adapter) {
                View v = inflater.inflate(R.layout.custom_tab_icon_and_text, container,
                        false);

                ImageView icon = v.findViewById(R.id.custom_tab_icon);
                TextView text = v.findViewById(R.id.custom_tab_text);
                switch (position) {
                    case 0:     //home
                        icon.setImageDrawable(res.getDrawable(R.drawable.ic_main_home_selector));
                        text.setText(navTabs()[position]);
                        break;
                    case 1:     //home
                        icon.setImageDrawable(res.getDrawable(R.drawable.ic_main_note_selector));
                        text.setText(navTabs()[position]);
                        break;
                    case 2:     //schedule/plan
                        icon.setImageDrawable(res.getDrawable(R.drawable.ic_main_schedule_selector));
                        text.setText(navTabs()[position]);
                        break;
                    case 3:     //track
                        icon.setImageDrawable(res.getDrawable(R.drawable.ic_main_track_selector));
                        text.setText(navTabs()[position]);
                        break;
                    case 4:     //discover
                        icon.setImageDrawable(res.getDrawable(R.drawable.ic_main_compass_selector));
                        text.setText(navTabs()[position]);
                        break;
                    case 5:     //more
                        icon.setImageDrawable(res.getDrawable(R.drawable.ic_main_more_selector));
                        text.setText(navTabs()[position]);
                        break;
                    default:    //
                        throw new IllegalStateException("Invalid position: " + position);
                }
                return v;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.nav_actionbar_options, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        //menu.findItem(R.id.nav_actionbar_options_night_mode).setChecked(isNightModeOn());

        //
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            /*case R.id.nav_actionbar_options_night_mode:
                boolean newNightMode = !item.isChecked();
                enableNightMode(newNightMode);
                item.setChecked(newNightMode);
                break;
            case R.id.nav_actionbar_options_about:*/
            case R.id.nav_actionbar_options_search:
                showSnackbarShortNotImplementedIdMessage(id);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //
    private void setNightMode(@AppCompatDelegate.NightMode int newNightMode) {
        AppCompatDelegate.setDefaultNightMode(newNightMode);
    }

    public void enableNightMode(Boolean newNightModeOn) {
        setNightMode(newNightModeOn ? AppCompatDelegate.MODE_NIGHT_YES
                : AppCompatDelegate.MODE_NIGHT_NO);
    }

    public boolean isNightModeOn() {
        return AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES;
    }

    public void ResetNightModeOn(boolean nightModeOn) {
        enableNightMode(nightModeOn);
        AppPreferences.putNightModeOn(this, (nightModeOn));

        //restart this activity
        Intent intent = new Intent(MainActivity.this, MainActivity.class);
        startActivity(intent); // start same activity
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        finish(); // destroy older activity
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        //Save SharedPreference data here unless accomplished somewhere else in more frequent manner.
        //AppPreferences.putNightModeOn(this, isNightModeOn());
        //AppPreferences.putCurrentMainNavigationIndex(this, viewPager.getCurrentItem());
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public Toolbar getToolbar() {
        return toolbar;
    }

    public void showSnackbar(Snackbar snackbar) {
        CoordinatorLayout.LayoutParams params
                = (CoordinatorLayout.LayoutParams) snackbar.getView().getLayoutParams();
        params.setMargins(params.leftMargin, params.topMargin, params.rightMargin,
                params.bottomMargin);
        snackbar.getView().setLayoutParams(params);
        snackbar.show();
    }

    public void showSnackbarShortMessage(CharSequence message) {
        Snackbar snackbar = Snackbar
                .make(coordinatorLayout,
                        message,
                        Snackbar.LENGTH_SHORT);
        showSnackbar(snackbar);
    }

    public void showSnackbarShortNotImplementedIdMessage(int id) {
        showSnackbarShortMessage("Not implemented: " + ResourceHelper.idToName(this, id));
    }

    public void showSnackbarShortNotImplementedIdMessage(CharSequence message) {
        showSnackbarShortMessage("Not implemented: " + message);
    }

    private Toast toast;

    public void showToast(String message) {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
        toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        toast.show();
    }

    //
    public int getThemePrimaryColor() {
        final TypedValue value = new TypedValue();
        this.getTheme().resolveAttribute(R.attr.colorPrimary, value, true);
        return value.data;
    }

    public int getThemePrimaryDarkColor() {
        final TypedValue value = new TypedValue();
        this.getTheme().resolveAttribute(R.attr.colorPrimaryDark, value, true);
        return value.data;
    }

    public int getThemeAccentColor() {
        final TypedValue value = new TypedValue();
        this.getTheme().resolveAttribute(R.attr.colorAccent, value, true);
        return value.data;
    }

    // Communication with child fragment
    public void onFragmentInteraction(Uri uri) {
        //
    }

    // Communication with child fragment
    public void onListFragmentInteraction(DummyContent.DummyItem item) {
        showSnackbarShortMessage(item.content);
    }

    //
    public void onPreferencesChange(){
        enableActionBarHideOnScroll(AppPreferences.getActionBarHideOnScroll(this));
        viewPager.disableSwiping(!AppPreferences.getMainNavigationSwipingOn(this));
    }

    //
    public void enableActionBarHideOnScroll(boolean enable) {
        AppBarLayout.LayoutParams params =
                (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
        if (enable) {
            int newFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
                    | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
                    | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP;
            if (params.getScrollFlags() != newFlags) {
                params.setScrollFlags(newFlags);
                appBarLayout.requestLayout();
            }
        } else {
            if (params.getScrollFlags() != 0) {
                params.setScrollFlags(0);
                appBarLayout.requestLayout();
            }
        }
    }

    //
}


text:
"""
Testing s3.py module

+ Check that required environment variables for AWS have been set
    * AWS_DEFAULT_REGION    (us-west-2) for plot-pdx bucket
    * AWS_ACCESS_KEY_ID
    * AWS_SECRET_ACCESS_KEY
+ Check that we can store, retrieve and delete objects from S3 bucket
+ The tests will try and use environment variables for bucket name and prefix
    * URBANDEV_S3_BUCKET    (default='plot-pdx')
    * URBANDEV_S3_PREFIX    (default='data/v1')
"""

import json
import os
import sys
import unittest
import uuid

try:
    import s3
except ImportError:
    PARENT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    sys.path.insert(0, PARENT)
    import s3 # pylint: disable=import-error

def setUpModule(): # pylint: disable=invalid-name
    """
    check that required environment variables are set
    will cause early termination by raising EnvironmentError
    """
    for envvar in s3.S3Bucket.ENVVARS:
        s3.check_envvar(envvar)

class TestBucketExists(unittest.TestCase):
    """ check aws S3 bucket exists """

    def test_valid_bucket(self):
        """ check that valid bucket name exists """
        bucket = s3.S3Bucket(s3.BUCKET)
        exists = bucket._bucket_exists() # pylint: disable=protected-access
        self.assertTrue(exists)

    def test_invalid_bucket(self):
        """ check that random bucket name throws LookupError """
        random_bucket = str(uuid.uuid4())
        bucket = s3.S3Bucket(random_bucket)
        exists = bucket._bucket_exists # pylint: disable=protected-access
        self.assertRaises(LookupError, exists)

class TestPrefixExists(unittest.TestCase):
    """ check that bucket prefix exists """

    def test_validate_prefix(self):
        """ validate that bucket PREFIX actually exists """
        bucket = s3.S3Bucket(s3.BUCKET)
        match = False
        for key in bucket.get_keys():
            if key.startswith(s3.PREFIX):
                match = True
                break
        error = "No key found with matching prefix '%s'" % s3.PREFIX
        self.assertTrue(match, error)

class TestBasicBucketOperations(unittest.TestCase):
    """ test some basic bucket operations """

    def setUp(self):
        """ create bucket """
        self.bucket = s3.S3Bucket(s3.BUCKET)
        self.key = 'test-%s' % uuid.uuid4()
        self.filepath = None
        self.data = dict(foo='bar')

    def tearDown(self):
        """ remove temp file and remove test object from bucket """
        if self.filepath and os.path.isfile(self.filepath):
            os.remove(self.filepath)
        self.bucket.delete(self.key)

    def test_empty_parameters(self):
        """ test trying to store empty keys or files """
        error = "Expected False return value"
        self.assertFalse(self.bucket.store(None, None), error)
        self.assertFalse(self.bucket.store('', None), error)
        self.assertFalse(self.bucket.store('', ''), error)
        self.assertFalse(self.bucket.store(None, ''), error)

    def test_invalid_file(self):
        """ test path to non-existant file """
        error = "Expected False return value"
        filepath = os.path.join('/tmp', str(uuid.uuid4()))
        self.assertFalse(self.bucket.store('foobar', filepath), error)

    def test_missing_key_get(self):
        """ test that KeyError is raised for non-existant key """
        with self.assertRaises(KeyError):
            self.bucket.get(self.key)

    def test_delete_nonexistant_object(self):
        """ check that existing object gets deleted """
        # should handle gracefully
        self.bucket.delete(self.key)

    def test_valid_store_get_delete(self):
        """ test entire chain of storing, retrieving and deleting an object """
        error = "Expected True return value when storing object"
        # store object with test data
        self.filepath = os.path.join('/tmp', str(uuid.uuid4()))
        json.dump(self.data, open(self.filepath, 'wb'))
        self.assertTrue(self.bucket.store(self.key, self.filepath), error)
        # retrieve object and check contents
        data = json.loads(self.bucket.get(self.key)['Body'].read())
        error = "Expected data %s actual data retrieved %s" % (self.data, data)
        self.assertEqual(self.data, data, error)
        # delete object and check that we cannot retrieve it
        self.bucket.delete(self.key)
        with self.assertRaises(KeyError):
            self.bucket.get(self.key)

if __name__ == '__main__':
    unittest.main()


text:
package controller

import (
	"context"
	"fmt"
	"runtime/debug"
	"strings"

	k8sv1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/log"
	cdiv1 "kubevirt.io/containerized-data-importer/pkg/apis/core/v1alpha1"
)

const (
	// BurstReplicas is the maximum amount of requests in a row for CRUD operations on resources by controllers,
	// to avoid unintentional DoS
	BurstReplicas uint = 250
)

// NewListWatchFromClient creates a new ListWatch from the specified client, resource, kubevirtNamespace and field selector.
func NewListWatchFromClient(c cache.Getter, resource string, namespace string, fieldSelector fields.Selector, labelSelector labels.Selector) *cache.ListWatch {
	listFunc := func(options metav1.ListOptions) (runtime.Object, error) {
		options.FieldSelector = fieldSelector.String()
		options.LabelSelector = labelSelector.String()
		return c.Get().
			Namespace(namespace).
			Resource(resource).
			VersionedParams(&options, metav1.ParameterCodec).
			Do(context.Background()).
			Get()
	}
	watchFunc := func(options metav1.ListOptions) (watch.Interface, error) {
		options.FieldSelector = fieldSelector.String()
		options.LabelSelector = labelSelector.String()
		return c.Get().
			Prefix("watch").
			Namespace(namespace).
			Resource(resource).
			VersionedParams(&options, metav1.ParameterCodec).
			Watch(context.Background())
	}
	return &cache.ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}
}

func HandlePanic() {
	if r := recover(); r != nil {
		log.Log.Level(log.FATAL).Log("stacktrace", debug.Stack(), "msg", r)
	}
}

func NewResourceEventHandlerFuncsForWorkqueue(queue workqueue.RateLimitingInterface) cache.ResourceEventHandlerFuncs {
	return cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			key, err := KeyFunc(obj)
			if err == nil {
				queue.Add(key)
			}
		},
		UpdateFunc: func(old interface{}, new interface{}) {
			key, err := KeyFunc(new)
			if err == nil {
				queue.Add(key)
			}
		},
		DeleteFunc: func(obj interface{}) {
			key, err := KeyFunc(obj)
			if err == nil {
				queue.Add(key)
			}
		},
	}
}

func MigrationKey(migration *v1.VirtualMachineInstanceMigration) string {
	return fmt.Sprintf("%v/%v", migration.ObjectMeta.Namespace, migration.ObjectMeta.Name)
}

func VirtualMachineKey(vmi *v1.VirtualMachineInstance) string {
	return fmt.Sprintf("%v/%v", vmi.ObjectMeta.Namespace, vmi.ObjectMeta.Name)
}

func PodKey(pod *k8sv1.Pod) string {
	return fmt.Sprintf("%v/%v", pod.Namespace, pod.Name)
}

func DataVolumeKey(dataVolume *cdiv1.DataVolume) string {
	return fmt.Sprintf("%v/%v", dataVolume.Namespace, dataVolume.Name)
}

func VirtualMachineKeys(vmis []*v1.VirtualMachineInstance) []string {
	keys := []string{}
	for _, vmi := range vmis {
		keys = append(keys, VirtualMachineKey(vmi))
	}
	return keys
}

func HasFinalizer(object metav1.Object, finalizer string) bool {
	for _, f := range object.GetFinalizers() {
		if f == finalizer {
			return true
		}
	}
	return false
}

func RemoveFinalizer(object metav1.Object, finalizer string) {
	filtered := []string{}
	for _, f := range object.GetFinalizers() {
		if f != finalizer {
			filtered = append(filtered, f)
		}
	}
	object.SetFinalizers(filtered)
}

func AddFinalizer(object metav1.Object, finalizer string) {
	if HasFinalizer(object, finalizer) {
		return
	}
	object.SetFinalizers(append(object.GetFinalizers(), finalizer))
}

func ObservedLatestApiVersionAnnotation(object metav1.Object) bool {
	annotations := object.GetAnnotations()
	if annotations == nil {
		return false
	}

	version, ok := annotations[v1.ControllerAPILatestVersionObservedAnnotation]
	if !ok || version != v1.ApiLatestVersion {
		return false
	}
	return true
}

func SetLatestApiVersionAnnotation(object metav1.Object) {
	annotations := object.GetAnnotations()
	if annotations == nil {
		annotations = make(map[string]string)
	}

	annotations[v1.ControllerAPILatestVersionObservedAnnotation] = v1.ApiLatestVersion
	annotations[v1.ControllerAPIStorageVersionObservedAnnotation] = v1.ApiStorageVersion
	object.SetAnnotations(annotations)
}

func ApplyVolumeRequestOnVMISpec(vmiSpec *v1.VirtualMachineInstanceSpec, request *v1.VirtualMachineVolumeRequest) *v1.VirtualMachineInstanceSpec {
	if request.AddVolumeOptions != nil {
		alreadyAdded := false
		for _, volume := range vmiSpec.Volumes {
			if volume.Name == request.AddVolumeOptions.Name {
				alreadyAdded = true
				break
			}
		}

		if !alreadyAdded {
			newVolume := v1.Volume{
				Name: request.AddVolumeOptions.Name,
			}

			if request.AddVolumeOptions.VolumeSource.PersistentVolumeClaim != nil {
				newVolume.VolumeSource.PersistentVolumeClaim = request.AddVolumeOptions.VolumeSource.PersistentVolumeClaim
			} else if request.AddVolumeOptions.VolumeSource.DataVolume != nil {

				newVolume.VolumeSource.DataVolume = request.AddVolumeOptions.VolumeSource.DataVolume
			}

			vmiSpec.Volumes = append(vmiSpec.Volumes, newVolume)

			if request.AddVolumeOptions.Disk != nil {
				newDisk := request.AddVolumeOptions.Disk.DeepCopy()
				newDisk.Name = request.AddVolumeOptions.Name

				vmiSpec.Domain.Devices.Disks = append(vmiSpec.Domain.Devices.Disks, *newDisk)
			}
		}

	} else if request.RemoveVolumeOptions != nil {

		newVolumesList := []v1.Volume{}
		newDisksList := []v1.Disk{}

		for _, volume := range vmiSpec.Volumes {
			if volume.Name != request.RemoveVolumeOptions.Name {
				newVolumesList = append(newVolumesList, volume)
			}
		}

		for _, disk := range vmiSpec.Domain.Devices.Disks {
			if disk.Name != request.RemoveVolumeOptions.Name {
				newDisksList = append(newDisksList, disk)
			}
		}

		vmiSpec.Volumes = newVolumesList
		vmiSpec.Domain.Devices.Disks = newDisksList
	}

	return vmiSpec
}

func CurrentVMIPod(vmi *v1.VirtualMachineInstance, podInformer cache.SharedIndexInformer) (*k8sv1.Pod, error) {

	// current pod is the most recent pod created on the current VMI node
	// OR the most recent pod created if no VMI node is set.

	// Get all pods from the namespace
	objs, err := podInformer.GetIndexer().ByIndex(cache.NamespaceIndex, vmi.Namespace)
	if err != nil {
		return nil, err
	}
	pods := []*k8sv1.Pod{}
	for _, obj := range objs {
		pod := obj.(*k8sv1.Pod)
		pods = append(pods, pod)
	}

	var curPod *k8sv1.Pod = nil
	for _, pod := range pods {
		if !IsControlledBy(pod, vmi) {
			continue
		}

		if vmi.Status.NodeName != "" &&
			vmi.Status.NodeName != pod.Spec.NodeName {
			// This pod isn't scheduled to the current node.
			// This can occur during the initial migration phases when
			// a new target node is being prepared for the VMI.
			continue
		}

		if curPod == nil || curPod.CreationTimestamp.Before(&pod.CreationTimestamp) {
			curPod = pod
		}
	}

	return curPod, nil
}

func VMIActivePodsCount(vmi *v1.VirtualMachineInstance, vmiPodInformer cache.SharedIndexInformer) int {

	objs, err := vmiPodInformer.GetIndexer().ByIndex(cache.NamespaceIndex, vmi.Namespace)
	if err != nil {
		return 0
	}

	running := 0
	for _, obj := range objs {
		pod := obj.(*k8sv1.Pod)

		if pod.Status.Phase == k8sv1.PodSucceeded || pod.Status.Phase == k8sv1.PodFailed {
			// not interested in terminated pods
			continue
		} else if !IsControlledBy(pod, vmi) {
			// not interested pods not associated with the vmi
			continue
		}
		running++
	}

	return running
}

func GeneratePatchBytes(ops []string) []byte {

	return []byte(fmt.Sprintf("[%s]", strings.Join(ops, ", ")))
}


text:
import calendar
import time
import random

import pytest

@pytest.fixture
def cookie(webserver):
    cookie = {
        'name': 'foo',
        'value': 'bar',
        'domain': webserver.host,
        'path': '/',
        'secure': False}
    return cookie

@pytest.fixture
def same_site_cookie_strict(webserver):
    same_site_cookie_strict = {
        'name': 'foo',
        'value': 'bar',
        'path': '/',
        'domain': webserver.host,
        'sameSite': 'Strict',
        'secure': False}
    return same_site_cookie_strict

@pytest.fixture
def same_site_cookie_lax(webserver):
    same_site_cookie_lax = {
        'name': 'foo',
        'value': 'bar',
        'path': '/',
        'domain': webserver.host,
        'sameSite': 'Lax',
        'secure': False}
    return same_site_cookie_lax

@pytest.fixture(autouse=True)
def pages(request, driver, pages):
    pages.load('simpleTest.html')
    yield pages
    driver.delete_all_cookies()

def testAddCookie(cookie, driver):
    driver.add_cookie(cookie)
    returned = driver.execute_script('return document.cookie')
    assert cookie['name'] in returned

@pytest.mark.xfail_firefox(reason='sameSite cookie attribute not implemented')
@pytest.mark.xfail_remote(reason='sameSite cookie attribute not implemented')
@pytest.mark.xfail_safari
def testAddCookieSameSiteStrict(same_site_cookie_strict, driver):
    driver.add_cookie(same_site_cookie_strict)
    returned = driver.get_cookie('foo')
    assert 'sameSite' in returned and returned['sameSite'] == 'Strict'

@pytest.mark.xfail_firefox(reason='sameSite cookie attribute not implemented')
@pytest.mark.xfail_remote(reason='sameSite cookie attribute not implemented')
@pytest.mark.xfail_safari
def testAddCookieSameSiteLax(same_site_cookie_lax, driver):
    driver.add_cookie(same_site_cookie_lax)
    returned = driver.get_cookie('foo')
    assert 'sameSite' in returned and returned['sameSite'] == 'Lax'

@pytest.mark.xfail_ie
@pytest.mark.xfail_safari
def testAddingACookieThatExpiredInThePast(cookie, driver):
    expired = cookie.copy()
    expired['expiry'] = calendar.timegm(time.gmtime()) - 1
    driver.add_cookie(expired)
    assert 0 == len(driver.get_cookies())

def testDeleteAllCookie(cookie, driver):
    driver.add_cookie(cookie)
    driver.delete_all_cookies()
    assert not driver.get_cookies()

def testDeleteCookie(cookie, driver):
    driver.add_cookie(cookie)
    driver.delete_cookie('foo')
    assert not driver.get_cookies()

def testShouldGetCookieByName(driver):
    key = 'key_{}'.format(int(random.random() * 10000000))
    driver.execute_script("document.cookie = arguments[0] + '=set';", key)
    cookie = driver.get_cookie(key)
    assert 'set' == cookie['value']

def testShouldReturnNoneWhenCookieDoesNotExist(driver):
    key = 'key_{}'.format(int(random.random() * 10000000))
    cookie = driver.get_cookie(key)
    assert cookie is None

def testGetAllCookies(cookie, driver, pages, webserver):
    cookies = driver.get_cookies()
    count = len(cookies)

    for i in range(2):
        cookie['name'] = 'key_{}'.format(int(random.random() * 10000000))
        driver.add_cookie(cookie)

    pages.load('simpleTest.html')
    assert count + 2 == len(driver.get_cookies())

def testShouldNotDeleteCookiesWithASimilarName(cookie, driver, webserver):
    cookie2 = cookie.copy()
    cookie2['name'] = '{}x'.format(cookie['name'])
    driver.add_cookie(cookie)
    driver.add_cookie(cookie2)
    driver.delete_cookie(cookie['name'])
    cookies = driver.get_cookies()
    assert cookie['name'] != cookies[0]['name']
    assert cookie2['name'] == cookies[0]['name']